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