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