1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
32 # include <QSslSocket>
33 # include "sslserver.h"
35 # include <QTcpSocket>
36 # include <QTcpServer>
39 #include "authenticator.h"
40 #include "bufferinfo.h"
41 #include "deferredptr.h"
43 #include "oidentdconfiggenerator.h"
44 #include "sessionthread.h"
48 class CoreAuthHandler;
54 class AbstractSqlMigrationReader;
55 class AbstractSqlMigrationWriter;
57 class Core : public QObject
62 static Core *instance();
63 static void destroy();
65 static void saveState();
66 static void restoreState();
68 /*** Storage access ***/
69 // These methods are threadsafe.
73 * \param userName The user's login name
74 * \param password The user's uncrypted password
75 * \return The user's ID if valid; 0 otherwise
77 static inline UserId validateUser(const QString &userName, const QString &password) {
78 return instance()->_storage->validateUser(userName, password);
81 //! Authenticate user against auth backend
83 * \param userName The user's login name
84 * \param password The user's uncrypted password
85 * \return The user's ID if valid; 0 otherwise
87 static inline UserId authenticateUser(const QString &userName, const QString &password) {
88 return instance()->_authenticator->validateUser(userName, password);
91 //! Add a new user, exposed so auth providers can call this without being the storage.
93 * \param userName The user's login name
94 * \param password The user's uncrypted password
95 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
96 * \return The user's ID if valid; 0 otherwise
98 static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") {
99 return instance()->_storage->addUser(userName, password, authenticator);
102 //! Does a comparison test against the authenticator in the database and the authenticator currently in use for a UserID.
104 * \param userid The user's ID (note: not login name).
105 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
106 * \return True if the userid was configured with the passed authenticator, false otherwise.
108 static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) {
109 return instance()->_storage->getUserAuthenticator(userid) == authenticator;
112 //! Change a user's password
114 * \param userId The user's ID
115 * \param password The user's unencrypted new password
116 * \return true, if the password change was successful
118 static bool changeUserPassword(UserId userId, const QString &password);
120 //! Check if we can change a user password.
122 * \param userID The user's ID
123 * \return true, if we can change their password, false otherwise
125 static bool canChangeUserPassword(UserId userId);
127 //! Store a user setting persistently
129 * \param userId The users Id
130 * \param settingName The Name of the Setting
131 * \param data The Value
133 static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
135 instance()->_storage->setUserSetting(userId, settingName, data);
139 //! Retrieve a persistent user setting
141 * \param userId The users Id
142 * \param settingName The Name of the Setting
143 * \param defaultValue Value to return in case it's unset.
144 * \return the Value of the Setting or the default value if it is unset.
146 static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
148 return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
152 /* Identity handling */
153 static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
155 return instance()->_storage->createIdentity(user, identity);
159 static bool updateIdentity(UserId user, const CoreIdentity &identity)
161 return instance()->_storage->updateIdentity(user, identity);
165 static void removeIdentity(UserId user, IdentityId identityId)
167 instance()->_storage->removeIdentity(user, identityId);
171 static QList<CoreIdentity> identities(UserId user)
173 return instance()->_storage->identities(user);
177 //! Create a Network in the Storage and store it's Id in the given NetworkInfo
178 /** \note This method is thredsafe.
180 * \param user The core user
181 * \param networkInfo a NetworkInfo definition to store the newly created ID in
182 * \return true if successfull.
184 static bool createNetwork(UserId user, NetworkInfo &info);
186 //! Apply the changes to NetworkInfo info to the storage engine
187 /** \note This method is thredsafe.
189 * \param user The core user
190 * \param networkInfo The Updated NetworkInfo
191 * \return true if successfull.
193 static inline bool updateNetwork(UserId user, const NetworkInfo &info)
195 return instance()->_storage->updateNetwork(user, info);
199 //! Permanently remove a Network and all the data associated with it.
200 /** \note This method is thredsafe.
202 * \param user The core user
203 * \param networkId The network to delete
204 * \return true if successfull.
206 static inline bool removeNetwork(UserId user, const NetworkId &networkId)
208 return instance()->_storage->removeNetwork(user, networkId);
212 //! Returns a list of all NetworkInfos for the given UserId user
213 /** \note This method is thredsafe.
215 * \param user The core user
216 * \return QList<NetworkInfo>.
218 static inline QList<NetworkInfo> networks(UserId user)
220 return instance()->_storage->networks(user);
224 //! Get a list of Networks to restore
225 /** Return a list of networks the user was connected at the time of core shutdown
226 * \note This method is threadsafe.
228 * \param user The User Id in question
230 static inline QList<NetworkId> connectedNetworks(UserId user)
232 return instance()->_storage->connectedNetworks(user);
236 //! Update the connected state of a network
237 /** \note This method is threadsafe
239 * \param user The Id of the networks owner
240 * \param networkId The Id of the network
241 * \param isConnected whether the network is connected or not
243 static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
245 return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
249 //! Get a hash of channels with their channel keys for a given network
250 /** The keys are channel names and values are passwords (possibly empty)
251 * \note This method is threadsafe
253 * \param user The id of the networks owner
254 * \param networkId The Id of the network
256 static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
258 return instance()->_storage->persistentChannels(user, networkId);
262 //! Update the connected state of a channel
263 /** \note This method is threadsafe
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
270 static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
272 return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
276 //! Get a hash of buffers with their ciphers for a given network
277 /** The keys are channel names and values are ciphers (possibly empty)
278 * \note This method is threadsafe
280 * \param user The id of the networks owner
281 * \param networkId The Id of the network
283 static inline QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId)
285 return instance()->_storage->bufferCiphers(user, networkId);
289 //! Update the cipher of a buffer
290 /** \note This method is threadsafe
292 * \param user The Id of the networks owner
293 * \param networkId The Id of the network
294 * \param bufferName The Cname of the buffer
295 * \param cipher The cipher for the buffer
297 static inline void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher)
299 return instance()->_storage->setBufferCipher(user, networkId, bufferName, cipher);
303 //! Update the key of a channel
304 /** \note This method is threadsafe
306 * \param user The Id of the networks owner
307 * \param networkId The Id of the network
308 * \param channel The name of the channel
309 * \param key The key of the channel (possibly empty)
311 static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
313 return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
317 //! retrieve last known away message for session restore
318 /** \note This method is threadsafe
320 * \param user The Id of the networks owner
321 * \param networkId The Id of the network
323 static inline QString awayMessage(UserId user, NetworkId networkId)
325 return instance()->_storage->awayMessage(user, networkId);
329 //! Make away message persistent for session restore
330 /** \note This method is threadsafe
332 * \param user The Id of the networks owner
333 * \param networkId The Id of the network
334 * \param awayMsg The current away message of own user
336 static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
338 return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
342 //! retrieve last known user mode for session restore
343 /** \note This method is threadsafe
345 * \param user The Id of the networks owner
346 * \param networkId The Id of the network
348 static inline QString userModes(UserId user, NetworkId networkId)
350 return instance()->_storage->userModes(user, networkId);
354 //! Make our user modes persistent for session restore
355 /** \note This method is threadsafe
357 * \param user The Id of the networks owner
358 * \param networkId The Id of the network
359 * \param userModes The current user modes of own user
361 static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
363 return instance()->_storage->setUserModes(user, networkId, userModes);
367 //! Get the unique BufferInfo for the given combination of network and buffername for a user.
368 /** \note This method is threadsafe.
370 * \param user The core user who owns this buffername
371 * \param networkId The network id
372 * \param type The type of the buffer (StatusBuffer, Channel, etc.)
373 * \param buffer The buffer name (if empty, the net's status buffer is returned)
374 * \param create Whether or not the buffer should be created if it doesnt exist
375 * \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
377 static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
379 return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
383 //! Get the unique BufferInfo for a bufferId
384 /** \note This method is threadsafe
385 * \param user The core user who owns this buffername
386 * \param bufferId The id of the buffer
387 * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
389 static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
391 return instance()->_storage->getBufferInfo(user, bufferId);
395 //! Store a Message in the storage backend and set it's unique Id.
396 /** \note This method is threadsafe.
398 * \param message The message object to be stored
399 * \return true on success
401 static inline bool storeMessage(Message &message)
403 return instance()->_storage->logMessage(message);
407 //! Store a list of Messages in the storage backend and set their unique Id.
408 /** \note This method is threadsafe.
410 * \param messages The list message objects to be stored
411 * \return true on success
413 static inline bool storeMessages(MessageList &messages)
415 return instance()->_storage->logMessages(messages);
419 //! Request a certain number messages stored in a given buffer.
420 /** \param buffer The buffer we request messages from
421 * \param first if != -1 return only messages with a MsgId >= first
422 * \param last if != -1 return only messages with a MsgId < last
423 * \param limit if != -1 limit the returned list to a max of \limit entries
424 * \return The requested list of messages
426 static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
428 return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
432 //! Request a certain number of messages across all buffers
433 /** \param first if != -1 return only messages with a MsgId >= first
434 * \param last if != -1 return only messages with a MsgId < last
435 * \param limit Max amount of messages
436 * \return The requested list of messages
438 static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
440 return instance()->_storage->requestAllMsgs(user, first, last, limit);
444 //! Request a list of all buffers known to a user.
445 /** This method is used to get a list of all buffers we have stored a backlog from.
446 * \note This method is threadsafe.
448 * \param user The user whose buffers we request
449 * \return A list of the BufferInfos for all buffers as requested
451 static inline QList<BufferInfo> requestBuffers(UserId user)
453 return instance()->_storage->requestBuffers(user);
457 //! Request a list of BufferIds for a given NetworkId
458 /** \note This method is threadsafe.
460 * \param user The user whose buffers we request
461 * \param networkId The NetworkId of the network in question
462 * \return List of BufferIds belonging to the Network
464 static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
466 return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
470 //! Remove permanently a buffer and it's content from the storage backend
471 /** This call cannot be reverted!
472 * \note This method is threadsafe.
474 * \param user The user who is the owner of the buffer
475 * \param bufferId The bufferId
476 * \return true if successfull
478 static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
480 return instance()->_storage->removeBuffer(user, bufferId);
485 /** \note This method is threadsafe.
486 * \param user The id of the buffer owner
487 * \param bufferId The bufferId
488 * \param newName The new name of the buffer
489 * \return true if successfull
491 static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
493 return instance()->_storage->renameBuffer(user, bufferId, newName);
497 //! Merge the content of two Buffers permanently. This cannot be reversed!
498 /** \note This method is threadsafe.
499 * \param user The id of the buffer owner
500 * \param bufferId1 The bufferId of the remaining buffer
501 * \param bufferId2 The buffer that is about to be removed
502 * \return true if successfulln
504 static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
506 return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
510 //! Update the LastSeenDate for a Buffer
511 /** This Method is used to make the LastSeenDate of a Buffer persistent
512 * \note This method is threadsafe.
514 * \param user The Owner of that Buffer
515 * \param bufferId The buffer id
516 * \param MsgId The Message id of the message that has been just seen
518 static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
520 return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
523 //! Get the auth username associated with a userId
524 /** \param user The user to retrieve the username for
525 * \return The username for the user
527 static inline QString getAuthUserName(UserId user) {
528 return instance()->_storage->getAuthUserName(user);
531 //! Get a usable sysident for the given user in oidentd-strict mode
532 /** \param user The user to retrieve the sysident for
533 * \return The authusername
535 QString strictSysIdent(UserId user) const;
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.
542 * \param user The Owner of the buffers
544 static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
546 return instance()->_storage->bufferLastSeenMsgIds(user);
550 //! Update the MarkerLineMsgId for a Buffer
551 /** This Method is used to make the marker line position of a Buffer persistent
552 * \note This method is threadsafe.
554 * \param user The Owner of that Buffer
555 * \param bufferId The buffer id
556 * \param MsgId The Message id where the marker line should be placed
558 static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
560 return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
564 //! Get a Hash of all marker line message ids
565 /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
566 * \note This method is threadsafe.
568 * \param user The Owner of the buffers
570 static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
572 return instance()->_storage->bufferMarkerLineMsgIds(user);
575 //! Update the BufferActivity for a Buffer
576 /** This Method is used to make the activity state of a Buffer persistent
577 * \note This method is threadsafe.
579 * \param user The Owner of that Buffer
580 * \param bufferId The buffer id
581 * \param MsgId The Message id where the marker line should be placed
583 static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity) {
584 return instance()->_storage->setBufferActivity(user, bufferId, activity);
588 //! Get a Hash of all buffer activity states
589 /** This Method is called when the Quassel Core is started to restore the BufferActivity
590 * \note This method is threadsafe.
592 * \param user The Owner of the buffers
594 static inline QHash<BufferId, Message::Types> bufferActivities(UserId user) {
595 return instance()->_storage->bufferActivities(user);
598 //! Get the bitset of buffer activity states for a buffer
599 /** This method is used to load the activity state of a buffer when its last seen message changes.
600 * \note This method is threadsafe.
602 * \param bufferId The buffer
603 * \param lastSeenMsgId The last seen message
605 static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) {
606 return instance()->_storage->bufferActivity(bufferId, lastSeenMsgId);
609 //! Update the highlight count for a Buffer
610 /** This Method is used to make the highlight count state of a Buffer persistent
611 * \note This method is threadsafe.
613 * \param user The Owner of that Buffer
614 * \param bufferId The buffer id
615 * \param MsgId The Message id where the marker line should be placed
617 static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount) {
618 return instance()->_storage->setHighlightCount(user, bufferId, highlightCount);
622 //! Get a Hash of all highlight count states
623 /** This Method is called when the Quassel Core is started to restore the highlight count
624 * \note This method is threadsafe.
626 * \param user The Owner of the buffers
628 static inline QHash<BufferId, int> highlightCounts(UserId user) {
629 return instance()->_storage->highlightCounts(user);
631 //! Get the highlight count states for a buffer
632 /** This method is used to load the highlight count of a buffer when its last seen message changes.
633 * \note This method is threadsafe.
635 * \param bufferId The buffer
636 * \param lastSeenMsgId The last seen message
638 static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) {
639 return instance()->_storage->highlightCount(bufferId, lastSeenMsgId);
642 static inline QDateTime startTime() { return instance()->_startTime; }
643 static inline bool isConfigured() { return instance()->_configured; }
644 static bool sslSupported();
647 * Reloads SSL certificates used for connection with clients
649 * @return True if certificates reloaded successfully, otherwise false.
651 static bool reloadCerts();
653 static void cacheSysIdent();
655 static QVariantList backendInfo();
656 static QVariantList authenticatorInfo();
658 static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
660 static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
662 inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
664 static const int AddClientEventId;
667 //! Make storage data persistent
668 /** \note This method is threadsafe.
671 void setupInternalClientSession(InternalPeer *clientConnection);
672 QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
675 //! Sent when a BufferInfo is updated in storage.
676 void bufferInfoUpdated(UserId user, const BufferInfo &info);
678 //! Relay from CoreSession::sessionState(). Used for internal connection only
679 void sessionState(const Protocol::SessionState &sessionState);
682 virtual void customEvent(QEvent *event);
685 bool startListening();
686 void stopListening(const QString &msg = QString());
687 void incomingConnection();
688 void clientDisconnected();
690 bool initStorage(const QString &backend, const QVariantMap &settings, bool setup = false);
691 bool initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup = false);
693 void socketError(QAbstractSocket::SocketError err, const QString &errorString);
694 void setupClientSession(RemotePeer *, UserId);
696 bool changeUserPass(const QString &username);
702 static Core *instanceptr;
704 SessionThread *sessionForUser(UserId userId, bool restoreState = false);
705 void addClientHelper(RemotePeer *peer, UserId uid);
706 //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
707 QString setupCoreForInternalUsage();
711 template<typename Storage>
712 void registerStorageBackend();
714 template<typename Authenticator>
715 void registerAuthenticator();
717 void registerStorageBackends();
718 void registerAuthenticators();
720 DeferredSharedPtr<Storage> storageBackend(const QString& backendId) const;
721 DeferredSharedPtr<Authenticator> authenticator(const QString& authenticatorId) const;
723 bool selectBackend(const QString &backend);
724 bool selectAuthenticator(const QString &backend);
726 bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
727 void saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings);
729 template<typename Backend>
730 QVariantMap promptForSettings(const Backend *backend);
733 QSet<CoreAuthHandler *> _connectingClients;
734 QHash<UserId, SessionThread *> _sessions;
735 DeferredSharedPtr<Storage> _storage; ///< Active storage backend
736 DeferredSharedPtr<Authenticator> _authenticator; ///< Active authenticator
737 QTimer _storageSyncTimer;
738 QMap<UserId, QString> _authUserNames;
741 SslServer _server, _v6server;
743 QTcpServer _server, _v6server;
746 OidentdConfigGenerator *_oidentdConfigGenerator {nullptr};
748 std::vector<DeferredSharedPtr<Storage>> _registeredStorageBackends;
749 std::vector<DeferredSharedPtr<Authenticator>> _registeredAuthenticators;
751 QDateTime _startTime;
755 static std::unique_ptr<AbstractSqlMigrationReader> getMigrationReader(Storage *storage);
756 static std::unique_ptr<AbstractSqlMigrationWriter> getMigrationWriter(Storage *storage);
757 static void stdInEcho(bool on);
758 static inline void enableStdInEcho() { stdInEcho(true); }
759 static inline void disableStdInEcho() { stdInEcho(false); }