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