cmake: avoid de-duplication of user's CXXFLAGS
[quassel.git] / src / core / core.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2022 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #pragma once
22
23 #include "core-export.h"
24
25 #include <memory>
26 #include <vector>
27
28 #include <QDateTime>
29 #include <QPointer>
30 #include <QSslSocket>
31 #include <QString>
32 #include <QTimer>
33 #include <QVariant>
34
35 #include "authenticator.h"
36 #include "bufferinfo.h"
37 #include "deferredptr.h"
38 #include "identserver.h"
39 #include "message.h"
40 #include "metricsserver.h"
41 #include "oidentdconfiggenerator.h"
42 #include "sessionthread.h"
43 #include "singleton.h"
44 #include "sslserver.h"
45 #include "storage.h"
46 #include "types.h"
47
48 class CoreAuthHandler;
49 class CoreSession;
50 class InternalPeer;
51 class SessionThread;
52 class SignalProxy;
53
54 struct NetworkInfo;
55
56 class AbstractSqlMigrationReader;
57 class AbstractSqlMigrationWriter;
58
59 class CORE_EXPORT Core : public QObject, public Singleton<Core>
60 {
61     Q_OBJECT
62
63 public:
64     Core();
65     ~Core() override;
66
67     void init();
68
69     /**
70      * Shuts down active core sessions, saves state and emits the shutdownComplete() signal afterwards.
71      */
72     void shutdown();
73
74     /*** Storage access ***/
75     // These methods are threadsafe.
76
77     //! Validate user
78     /**
79      * \param userName The user's login name
80      * \param password The user's uncrypted password
81      * \return The user's ID if valid; 0 otherwise
82      */
83     static inline UserId validateUser(const QString& userName, const QString& password)
84     {
85         return instance()->_storage->validateUser(userName, password);
86     }
87
88     //! Authenticate user against auth backend
89     /**
90      * \param userName The user's login name
91      * \param password The user's uncrypted password
92      * \return The user's ID if valid; 0 otherwise
93      */
94     static inline UserId authenticateUser(const QString& userName, const QString& password)
95     {
96         return instance()->_authenticator->validateUser(userName, password);
97     }
98
99     //! Add a new user, exposed so auth providers can call this without being the storage.
100     /**
101      * \param userName The user's login name
102      * \param password The user's uncrypted password
103      * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
104      * \return The user's ID if valid; 0 otherwise
105      */
106     static inline UserId addUser(const QString& userName, const QString& password, const QString& authenticator = "Database")
107     {
108         return instance()->_storage->addUser(userName, password, authenticator);
109     }
110
111     //! Does a comparison test against the authenticator in the database and the authenticator currently in use for a UserID.
112     /**
113      * \param userid The user's ID (note: not login name).
114      * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
115      * \return True if the userid was configured with the passed authenticator, false otherwise.
116      */
117     static inline bool checkAuthProvider(const UserId userid, const QString& authenticator)
118     {
119         return instance()->_storage->getUserAuthenticator(userid) == authenticator;
120     }
121
122     //! Gets the authenticator configured for a user.
123     /**
124      * \param userName The user's name as a QString.
125      * \return String value corresponding to the user's configure dauthenticator.
126      */
127     static inline QString getUserAuthenticator(const QString& userName)
128     {
129         return instance()->_storage->getUserAuthenticator(instance()->_storage->getUserId(userName));
130     }
131
132     //! Gets the user ID mapped to a username. This is necessary so that non-database auth methods can log in users properly.
133     /**
134      * \param userName The user's name as a QString.
135      * \return userId  The user's ID.
136      */
137     static inline UserId getUserId(const QString& userName)
138     {
139         return instance()->_storage->getUserId(userName);
140     }
141
142     //! Change a user's password
143     /**
144      * \param userId     The user's ID
145      * \param password   The user's unencrypted new password
146      * \return true, if the password change was successful
147      */
148     static bool changeUserPassword(UserId userId, const QString& password);
149
150     //! Check if we can change a user password.
151     /**
152      * \param userID     The user's ID
153      * \return true, if we can change their password, false otherwise
154      */
155     static bool canChangeUserPassword(UserId userId);
156
157     //! Store a user setting persistently
158     /**
159      * \param userId       The users Id
160      * \param settingName  The Name of the Setting
161      * \param data         The Value
162      */
163     static inline void setUserSetting(UserId userId, const QString& settingName, const QVariant& data)
164     {
165         instance()->_storage->setUserSetting(userId, settingName, data);
166     }
167
168     //! Retrieve a persistent user setting
169     /**
170      * \param userId       The users Id
171      * \param settingName  The Name of the Setting
172      * \param defaultValue Value to return in case it's unset.
173      * \return the Value of the Setting or the default value if it is unset.
174      */
175     static inline QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultValue = QVariant())
176     {
177         return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
178     }
179
180     /* Identity handling */
181     static inline IdentityId createIdentity(UserId user, CoreIdentity& identity)
182     {
183         return instance()->_storage->createIdentity(user, identity);
184     }
185
186     static bool updateIdentity(UserId user, const CoreIdentity& identity) { return instance()->_storage->updateIdentity(user, identity); }
187
188     static void removeIdentity(UserId user, IdentityId identityId) { instance()->_storage->removeIdentity(user, identityId); }
189
190     static std::vector<CoreIdentity> identities(UserId user) { return instance()->_storage->identities(user); }
191
192     //! Create a Network in the Storage and store it's Id in the given NetworkInfo
193     /** \note This method is thredsafe.
194      *
195      *  \param user        The core user
196      *  \param networkInfo a NetworkInfo definition to store the newly created ID in
197      *  \return true if successful.
198      */
199     static bool createNetwork(UserId user, NetworkInfo& info);
200
201     //! Apply the changes to NetworkInfo info to the storage engine
202     /** \note This method is thredsafe.
203      *
204      *  \param user        The core user
205      *  \param networkInfo The Updated NetworkInfo
206      *  \return true if successful.
207      */
208     static inline bool updateNetwork(UserId user, const NetworkInfo& info) { return instance()->_storage->updateNetwork(user, info); }
209
210     //! Permanently remove a Network and all the data associated with it.
211     /** \note This method is thredsafe.
212      *
213      *  \param user        The core user
214      *  \param networkId   The network to delete
215      *  \return true if successful.
216      */
217     static inline bool removeNetwork(UserId user, const NetworkId& networkId)
218     {
219         return instance()->_storage->removeNetwork(user, networkId);
220     }
221
222     //! Returns a list of all NetworkInfos for the given UserId user
223     /** \note This method is thredsafe.
224      *
225      *  \param user        The core user
226      *  \return std::vector<NetworkInfo>.
227      */
228     static inline std::vector<NetworkInfo> networks(UserId user) { return instance()->_storage->networks(user); }
229
230     //! Get a list of Networks to restore
231     /** Return a list of networks the user was connected at the time of core shutdown
232      *  \note This method is threadsafe.
233      *
234      *  \param user  The User Id in question
235      */
236     static inline std::vector<NetworkId> connectedNetworks(UserId user) { return instance()->_storage->connectedNetworks(user); }
237
238     //! Update the connected state of a network
239     /** \note This method is threadsafe
240      *
241      *  \param user        The Id of the networks owner
242      *  \param networkId   The Id of the network
243      *  \param isConnected whether the network is connected or not
244      */
245     static inline void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected)
246     {
247         return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
248     }
249
250     //! Get a hash of channels with their channel keys for a given network
251     /** The keys are channel names and values are passwords (possibly empty)
252      *  \note This method is threadsafe
253      *
254      *  \param user       The id of the networks owner
255      *  \param networkId  The Id of the network
256      */
257     static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId& networkId)
258     {
259         return instance()->_storage->persistentChannels(user, networkId);
260     }
261
262     //! Update the connected state of a channel
263     /** \note This method is threadsafe
264      *
265      *  \param user       The Id of the networks owner
266      *  \param networkId  The Id of the network
267      *  \param channel    The name of the channel
268      *  \param isJoined   whether the channel is connected or not
269      */
270     static inline void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined)
271     {
272         return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
273     }
274
275     //! Get a hash of buffers with their ciphers for a given network
276     /** The keys are channel names and values are ciphers (possibly empty)
277      *  \note This method is threadsafe
278      *
279      *  \param user       The id of the networks owner
280      *  \param networkId  The Id of the network
281      */
282     static inline QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId& networkId)
283     {
284         return instance()->_storage->bufferCiphers(user, networkId);
285     }
286
287     //! Update the cipher of a buffer
288     /** \note This method is threadsafe
289      *
290      *  \param user        The Id of the networks owner
291      *  \param networkId   The Id of the network
292      *  \param bufferName The Cname of the buffer
293      *  \param cipher      The cipher for the buffer
294      */
295     static inline void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher)
296     {
297         return instance()->_storage->setBufferCipher(user, networkId, bufferName, cipher);
298     }
299
300     //! Update the key of a channel
301     /** \note This method is threadsafe
302      *
303      *  \param user       The Id of the networks owner
304      *  \param networkId  The Id of the network
305      *  \param channel    The name of the channel
306      *  \param key        The key of the channel (possibly empty)
307      */
308     static inline void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key)
309     {
310         return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
311     }
312
313     //! retrieve last known away message for session restore
314     /** \note This method is threadsafe
315      *
316      *  \param user       The Id of the networks owner
317      *  \param networkId  The Id of the network
318      */
319     static inline QString awayMessage(UserId user, NetworkId networkId) { return instance()->_storage->awayMessage(user, networkId); }
320
321     //! Make away message persistent for session restore
322     /** \note This method is threadsafe
323      *
324      *  \param user       The Id of the networks owner
325      *  \param networkId  The Id of the network
326      *  \param awayMsg    The current away message of own user
327      */
328     static inline void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg)
329     {
330         return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
331     }
332
333     //! retrieve last known user mode for session restore
334     /** \note This method is threadsafe
335      *
336      *  \param user       The Id of the networks owner
337      *  \param networkId  The Id of the network
338      */
339     static inline QString userModes(UserId user, NetworkId networkId) { return instance()->_storage->userModes(user, networkId); }
340
341     //! Make our user modes persistent for session restore
342     /** \note This method is threadsafe
343      *
344      *  \param user       The Id of the networks owner
345      *  \param networkId  The Id of the network
346      *  \param userModes  The current user modes of own user
347      */
348     static inline void setUserModes(UserId user, NetworkId networkId, const QString& userModes)
349     {
350         return instance()->_storage->setUserModes(user, networkId, userModes);
351     }
352
353     //! Get the unique BufferInfo for the given combination of network and buffername for a user.
354     /** \note This method is threadsafe.
355      *
356      *  \param user      The core user who owns this buffername
357      *  \param networkId The network id
358      *  \param type      The type of the buffer (StatusBuffer, Channel, etc.)
359      *  \param buffer    The buffer name (if empty, the net's status buffer is returned)
360      *  \param create    Whether or not the buffer should be created if it doesn't exist
361      *  \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
362      */
363     static inline BufferInfo bufferInfo(
364         UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true)
365     {
366         return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
367     }
368
369     //! Get the unique BufferInfo for a bufferId
370     /** \note This method is threadsafe
371      *  \param user      The core user who owns this buffername
372      *  \param bufferId  The id of the buffer
373      *  \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
374      */
375     static inline BufferInfo getBufferInfo(UserId user, const BufferId& bufferId)
376     {
377         return instance()->_storage->getBufferInfo(user, bufferId);
378     }
379
380     //! Store a Message in the storage backend and set it's unique Id.
381     /** \note This method is threadsafe.
382      *
383      *  \param message The message object to be stored
384      *  \return true on success
385      */
386     static inline bool storeMessage(Message& message) { return instance()->_storage->logMessage(message); }
387
388     //! Store a list of Messages in the storage backend and set their unique Id.
389     /** \note This method is threadsafe.
390      *
391      *  \param messages The list message objects to be stored
392      *  \return true on success
393      */
394     static inline bool storeMessages(MessageList& messages) { return instance()->_storage->logMessages(messages); }
395
396     //! Request a certain number messages stored in a given buffer.
397     /** \param buffer   The buffer we request messages from
398      *  \param first    if != -1 return only messages with a MsgId >= first
399      *  \param last     if != -1 return only messages with a MsgId < last
400      *  \param limit    if != -1 limit the returned list to a max of \limit entries
401      *  \return The requested list of messages
402      */
403     static inline std::vector<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
404     {
405         return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
406     }
407
408     //! Request a certain number messages stored in a given buffer, matching certain filters
409     /** \param buffer   The buffer we request messages from
410      *  \param first    if != -1 return only messages with a MsgId >= first
411      *  \param last     if != -1 return only messages with a MsgId < last
412      *  \param limit    if != -1 limit the returned list to a max of \limit entries
413      *  \param type     The Message::Types that should be returned
414      *  \return The requested list of messages
415      */
416     static inline std::vector<Message> requestMsgsFiltered(UserId user,
417                                                      BufferId bufferId,
418                                                      MsgId first = -1,
419                                                      MsgId last = -1,
420                                                      int limit = -1,
421                                                      Message::Types type = Message::Types{-1},
422                                                      Message::Flags flags = Message::Flags{-1})
423     {
424         return instance()->_storage->requestMsgsFiltered(user, bufferId, first, last, limit, type, flags);
425     }
426
427     //! Request a certain number messages stored in a given buffer, matching certain filters, ascending
428     /** \param buffer   The buffer we request messages from
429      *  \param first    if != -1 return only messages with a MsgId >= first
430      *  \param last     if != -1 return only messages with a MsgId < last
431      *  \param limit    if != -1 limit the returned list to a max of \limit entries
432      *  \param type     The Message::Types that should be returned
433      *  \param flags     The Message::Flags that should be returned
434      *  \return The requested list of messages
435      */
436     static inline std::vector<Message> requestMsgsForward(UserId user,
437                                                            BufferId bufferId,
438                                                            MsgId first = -1,
439                                                            MsgId last = -1,
440                                                            int limit = -1,
441                                                            Message::Types type = Message::Types{-1},
442                                                            Message::Flags flags = Message::Flags{-1})
443     {
444         return instance()->_storage->requestMsgsForward(user, bufferId, first, last, limit, type, flags);
445     }
446
447     //! Request a certain number of messages across all buffers
448     /** \param first    if != -1 return only messages with a MsgId >= first
449      *  \param last     if != -1 return only messages with a MsgId < last
450      *  \param limit    Max amount of messages
451      *  \return The requested list of messages
452      */
453     static inline std::vector<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
454     {
455         return instance()->_storage->requestAllMsgs(user, first, last, limit);
456     }
457
458     //! Request a certain number of messages across all buffers, matching certain filters
459     /** \param first    if != -1 return only messages with a MsgId >= first
460      *  \param last     if != -1 return only messages with a MsgId < last
461      *  \param limit    Max amount of messages
462      *  \param type     The Message::Types that should be returned
463      *  \return The requested list of messages
464      */
465     static inline std::vector<Message> requestAllMsgsFiltered(UserId user,
466                                                         MsgId first = -1,
467                                                         MsgId last = -1,
468                                                         int limit = -1,
469                                                         Message::Types type = Message::Types{-1},
470                                                         Message::Flags flags = Message::Flags{-1})
471     {
472         return instance()->_storage->requestAllMsgsFiltered(user, first, last, limit, type, flags);
473     }
474
475     //! Request a list of all buffers known to a user.
476     /** This method is used to get a list of all buffers we have stored a backlog from.
477      *  \note This method is threadsafe.
478      *
479      *  \param user  The user whose buffers we request
480      *  \return A list of the BufferInfos for all buffers as requested
481      */
482     static inline std::vector<BufferInfo> requestBuffers(UserId user) { return instance()->_storage->requestBuffers(user); }
483
484     //! Request a list of BufferIds for a given NetworkId
485     /** \note This method is threadsafe.
486      *
487      *  \param user  The user whose buffers we request
488      *  \param networkId  The NetworkId of the network in question
489      *  \return List of BufferIds belonging to the Network
490      */
491     static inline std::vector<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
492     {
493         return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
494     }
495
496     //! Remove permanently a buffer and it's content from the storage backend
497     /** This call cannot be reverted!
498      *  \note This method is threadsafe.
499      *
500      *  \param user      The user who is the owner of the buffer
501      *  \param bufferId  The bufferId
502      *  \return true if successful
503      */
504     static inline bool removeBuffer(const UserId& user, const BufferId& bufferId)
505     {
506         return instance()->_storage->removeBuffer(user, bufferId);
507     }
508
509     //! Rename a Buffer
510     /** \note This method is threadsafe.
511      *  \param user      The id of the buffer owner
512      *  \param bufferId  The bufferId
513      *  \param newName   The new name of the buffer
514      *  \return true if successful
515      */
516     static inline bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName)
517     {
518         return instance()->_storage->renameBuffer(user, bufferId, newName);
519     }
520
521     //! Merge the content of two Buffers permanently. This cannot be reversed!
522     /** \note This method is threadsafe.
523      *  \param user      The id of the buffer owner
524      *  \param bufferId1 The bufferId of the remaining buffer
525      *  \param bufferId2 The buffer that is about to be removed
526      *  \return true if successful
527      */
528     static inline bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2)
529     {
530         return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
531     }
532
533     //! Update the LastSeenDate for a Buffer
534     /** This Method is used to make the LastSeenDate of a Buffer persistent
535      *  \note This method is threadsafe.
536      *
537      * \param user      The Owner of that Buffer
538      * \param bufferId  The buffer id
539      * \param MsgId     The Message id of the message that has been just seen
540      */
541     static inline void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId)
542     {
543         return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
544     }
545
546     //! Get a usable sysident for the given user in oidentd-strict mode
547     /** \param user    The user to retrieve the sysident for
548      *  \return The authusername
549      */
550     QString strictSysIdent(UserId user) const;
551
552     //! Get a Hash of all last message ids
553     /** This Method is called when the Quassel Core is started to restore the lastMsgIds
554      *  \note This method is threadsafe.
555      *
556      * \param user      The Owner of the buffers
557      */
558     static inline QHash<BufferId, MsgId> bufferLastMsgIds(UserId user) { return instance()->_storage->bufferLastMsgIds(user); }
559
560     //! Get a Hash of all last seen message ids
561     /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
562      *  \note This method is threadsafe.
563      *
564      * \param user      The Owner of the buffers
565      */
566     static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user) { return instance()->_storage->bufferLastSeenMsgIds(user); }
567
568     //! Update the MarkerLineMsgId for a Buffer
569     /** This Method is used to make the marker line position of a Buffer persistent
570      *  \note This method is threadsafe.
571      *
572      * \param user      The Owner of that Buffer
573      * \param bufferId  The buffer id
574      * \param MsgId     The Message id where the marker line should be placed
575      */
576     static inline void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId)
577     {
578         return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
579     }
580
581     //! Get a Hash of all marker line message ids
582     /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
583      *  \note This method is threadsafe.
584      *
585      * \param user      The Owner of the buffers
586      */
587     static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user) { return instance()->_storage->bufferMarkerLineMsgIds(user); }
588
589     //! Update the BufferActivity for a Buffer
590     /** This Method is used to make the activity state of a Buffer persistent
591      *  \note This method is threadsafe.
592      *
593      * \param user      The Owner of that Buffer
594      * \param bufferId  The buffer id
595      * \param MsgId     The Message id where the marker line should be placed
596      */
597     static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity)
598     {
599         return instance()->_storage->setBufferActivity(user, bufferId, activity);
600     }
601
602     //! Get a Hash of all buffer activity states
603     /** This Method is called when the Quassel Core is started to restore the BufferActivity
604      *  \note This method is threadsafe.
605      *
606      * \param user      The Owner of the buffers
607      */
608     static inline QHash<BufferId, Message::Types> bufferActivities(UserId user) { return instance()->_storage->bufferActivities(user); }
609
610     //! Get the bitset of buffer activity states for a buffer
611     /** This method is used to load the activity state of a buffer when its last seen message changes.
612      *  \note This method is threadsafe.
613      *
614      * \param bufferId The buffer
615      * \param lastSeenMsgId     The last seen message
616      */
617     static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId)
618     {
619         return instance()->_storage->bufferActivity(bufferId, lastSeenMsgId);
620     }
621
622     //! Update the highlight count for a Buffer
623     /** This Method is used to make the highlight count state of a Buffer persistent
624      *  \note This method is threadsafe.
625      *
626      * \param user      The Owner of that Buffer
627      * \param bufferId  The buffer id
628      * \param MsgId     The Message id where the marker line should be placed
629      */
630     static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount)
631     {
632         return instance()->_storage->setHighlightCount(user, bufferId, highlightCount);
633     }
634
635     //! Get a Hash of all highlight count states
636     /** This Method is called when the Quassel Core is started to restore the highlight count
637      *  \note This method is threadsafe.
638      *
639      * \param user      The Owner of the buffers
640      */
641     static inline QHash<BufferId, int> highlightCounts(UserId user) { return instance()->_storage->highlightCounts(user); }
642     //! Get the highlight count states for a buffer
643     /** This method is used to load the highlight count of a buffer when its last seen message changes.
644      *  \note This method is threadsafe.
645      *
646      * \param bufferId The buffer
647      * \param lastSeenMsgId     The last seen message
648      */
649     static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId)
650     {
651         return instance()->_storage->highlightCount(bufferId, lastSeenMsgId);
652     }
653
654     static inline QDateTime startTime() { return instance()->_startTime; }
655     static inline bool isConfigured() { return instance()->_configured; }
656
657     /**
658      * Whether or not strict ident mode is enabled, locking users' idents to Quassel username
659      *
660      * @return True if strict mode enabled, otherwise false
661      */
662     static inline bool strictIdentEnabled() { return instance()->_strictIdentEnabled; }
663
664     static bool sslSupported();
665
666     static QVariantList backendInfo();
667     static QVariantList authenticatorInfo();
668
669     static QString setup(const QString& adminUser,
670                          const QString& adminPassword,
671                          const QString& backend,
672                          const QVariantMap& setupData,
673                          const QString& authenticator,
674                          const QVariantMap& authSetupMap);
675
676     static inline QTimer* syncTimer() { return &instance()->_storageSyncTimer; }
677
678     inline OidentdConfigGenerator* oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
679     inline IdentServer* identServer() const { return _identServer; }
680     inline MetricsServer* metricsServer() const { return _metricsServer; }
681
682     static const int AddClientEventId;
683
684 signals:
685     //! Sent when a BufferInfo is updated in storage.
686     void bufferInfoUpdated(UserId user, const BufferInfo& info);
687
688     //! Relay from CoreSession::sessionState(). Used for internal connection only
689     void sessionStateReceived(const Protocol::SessionState& sessionState);
690
691     //! Emitted when database schema upgrade starts or ends
692     void dbUpgradeInProgress(bool inProgress);
693
694     //! Emitted when a fatal error was encountered during async initialization
695     void exitRequested(int exitCode, const QString& reason);
696
697     //! Emitted once core shutdown is complete
698     void shutdownComplete();
699
700 public slots:
701     void initAsync();
702
703     /** Persist storage.
704      *
705      * @note This method is threadsafe.
706      */
707     void syncStorage();
708
709     /**
710      * Reload SSL certificates used for connection with clients.
711      *
712      * @return True if certificates reloaded successfully, otherwise false.
713      */
714     bool reloadCerts();
715
716     void cacheSysIdent();
717
718     QString setupCore(const QString& adminUser,
719                       const QString& adminPassword,
720                       const QString& backend,
721                       const QVariantMap& setupData,
722                       const QString& authenticator,
723                       const QVariantMap& authSetupMap);
724
725     void connectInternalPeer(QPointer<InternalPeer> peer);
726
727 protected:
728     void customEvent(QEvent* event) override;
729
730 private slots:
731     bool startListening();
732     void stopListening(const QString& msg = QString());
733     void incomingConnection();
734     void clientDisconnected();
735
736     bool initStorage(const QString& backend,
737                      const QVariantMap& settings,
738                      const QProcessEnvironment& environment,
739                      bool loadFromEnvironment,
740                      bool setup = false);
741     bool initAuthenticator(const QString& backend,
742                            const QVariantMap& settings,
743                            const QProcessEnvironment& environment,
744                            bool loadFromEnvironment,
745                            bool setup = false);
746
747     void socketError(QAbstractSocket::SocketError err, const QString& errorString);
748     void setupClientSession(RemotePeer*, UserId);
749
750     bool changeUserPass(const QString& username);
751
752     void onSessionShutdown(SessionThread* session);
753
754 private:
755     SessionThread* sessionForUser(UserId userId, bool restoreState = false);
756     void addClientHelper(RemotePeer* peer, UserId uid);
757     // void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
758     QString setupCoreForInternalUsage();
759     void setupInternalClientSession(QPointer<InternalPeer> peer);
760
761     bool createUser();
762
763     template<typename Storage>
764     void registerStorageBackend();
765
766     template<typename Authenticator>
767     void registerAuthenticator();
768
769     void registerStorageBackends();
770     void registerAuthenticators();
771
772     DeferredSharedPtr<Storage> storageBackend(const QString& backendId) const;
773     DeferredSharedPtr<Authenticator> authenticator(const QString& authenticatorId) const;
774
775     bool selectBackend(const QString& backend);
776     bool selectAuthenticator(const QString& backend);
777
778     bool saveBackendSettings(const QString& backend, const QVariantMap& settings);
779     void saveAuthenticatorSettings(const QString& backend, const QVariantMap& settings);
780
781     void saveState();
782     void restoreState();
783
784     template<typename Backend>
785     QVariantMap promptForSettings(const Backend* backend);
786
787 private:
788     static Core* _instance;
789     QSet<CoreAuthHandler*> _connectingClients;
790     QHash<UserId, SessionThread*> _sessions;
791     DeferredSharedPtr<Storage> _storage;              ///< Active storage backend
792     DeferredSharedPtr<Authenticator> _authenticator;  ///< Active authenticator
793     QMap<UserId, QString> _authUserNames;
794
795     QTimer _storageSyncTimer;
796
797     SslServer _server, _v6server;
798
799     OidentdConfigGenerator* _oidentdConfigGenerator{nullptr};
800
801     std::vector<DeferredSharedPtr<Storage>> _registeredStorageBackends;
802     std::vector<DeferredSharedPtr<Authenticator>> _registeredAuthenticators;
803
804     QDateTime _startTime;
805
806     IdentServer* _identServer{nullptr};
807     MetricsServer* _metricsServer{nullptr};
808
809     bool _initialized{false};
810     bool _configured{false};
811
812     QPointer<InternalPeer> _pendingInternalConnection;
813
814     /// Whether or not strict ident mode is enabled, locking users' idents to Quassel username
815     bool _strictIdentEnabled;
816
817     static std::unique_ptr<AbstractSqlMigrationReader> getMigrationReader(Storage* storage);
818     static std::unique_ptr<AbstractSqlMigrationWriter> getMigrationWriter(Storage* storage);
819     static void stdInEcho(bool on);
820     static inline void enableStdInEcho() { stdInEcho(true); }
821     static inline void disableStdInEcho() { stdInEcho(false); }
822 };