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