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