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