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 ***************************************************************************/
33 # include <QSslSocket>
34 # include "sslserver.h"
36 # include <QTcpSocket>
37 # include <QTcpServer>
40 #include "authenticator.h"
41 #include "bufferinfo.h"
42 #include "deferredptr.h"
44 #include "oidentdconfiggenerator.h"
45 #include "sessionthread.h"
49 class CoreAuthHandler;
57 class AbstractSqlMigrationReader;
58 class AbstractSqlMigrationWriter;
60 class Core : public QObject
65 static Core *instance();
70 /*** Storage access ***/
71 // These methods are threadsafe.
75 * \param userName The user's login name
76 * \param password The user's uncrypted password
77 * \return The user's ID if valid; 0 otherwise
79 static inline UserId validateUser(const QString &userName, const QString &password) {
80 return instance()->_storage->validateUser(userName, password);
83 //! Authenticate user against auth backend
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
89 static inline UserId authenticateUser(const QString &userName, const QString &password) {
90 return instance()->_authenticator->validateUser(userName, password);
93 //! Add a new user, exposed so auth providers can call this without being the storage.
95 * \param userName The user's login name
96 * \param password The user's uncrypted password
97 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
98 * \return The user's ID if valid; 0 otherwise
100 static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") {
101 return instance()->_storage->addUser(userName, password, authenticator);
104 //! Does a comparison test against the authenticator in the database and the authenticator currently in use for a UserID.
106 * \param userid The user's ID (note: not login name).
107 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
108 * \return True if the userid was configured with the passed authenticator, false otherwise.
110 static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) {
111 return instance()->_storage->getUserAuthenticator(userid) == authenticator;
114 //! Change a user's password
116 * \param userId The user's ID
117 * \param password The user's unencrypted new password
118 * \return true, if the password change was successful
120 static bool changeUserPassword(UserId userId, const QString &password);
122 //! Check if we can change a user password.
124 * \param userID The user's ID
125 * \return true, if we can change their password, false otherwise
127 static bool canChangeUserPassword(UserId userId);
129 //! Store a user setting persistently
131 * \param userId The users Id
132 * \param settingName The Name of the Setting
133 * \param data The Value
135 static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
137 instance()->_storage->setUserSetting(userId, settingName, data);
141 //! Retrieve a persistent user setting
143 * \param userId The users Id
144 * \param settingName The Name of the Setting
145 * \param defaultValue Value to return in case it's unset.
146 * \return the Value of the Setting or the default value if it is unset.
148 static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
150 return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
154 /* Identity handling */
155 static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
157 return instance()->_storage->createIdentity(user, identity);
161 static bool updateIdentity(UserId user, const CoreIdentity &identity)
163 return instance()->_storage->updateIdentity(user, identity);
167 static void removeIdentity(UserId user, IdentityId identityId)
169 instance()->_storage->removeIdentity(user, identityId);
173 static QList<CoreIdentity> identities(UserId user)
175 return instance()->_storage->identities(user);
179 //! Create a Network in the Storage and store it's Id in the given NetworkInfo
180 /** \note This method is thredsafe.
182 * \param user The core user
183 * \param networkInfo a NetworkInfo definition to store the newly created ID in
184 * \return true if successfull.
186 static bool createNetwork(UserId user, NetworkInfo &info);
188 //! Apply the changes to NetworkInfo info to the storage engine
189 /** \note This method is thredsafe.
191 * \param user The core user
192 * \param networkInfo The Updated NetworkInfo
193 * \return true if successfull.
195 static inline bool updateNetwork(UserId user, const NetworkInfo &info)
197 return instance()->_storage->updateNetwork(user, info);
201 //! Permanently remove a Network and all the data associated with it.
202 /** \note This method is thredsafe.
204 * \param user The core user
205 * \param networkId The network to delete
206 * \return true if successfull.
208 static inline bool removeNetwork(UserId user, const NetworkId &networkId)
210 return instance()->_storage->removeNetwork(user, networkId);
214 //! Returns a list of all NetworkInfos for the given UserId user
215 /** \note This method is thredsafe.
217 * \param user The core user
218 * \return QList<NetworkInfo>.
220 static inline QList<NetworkInfo> networks(UserId user)
222 return instance()->_storage->networks(user);
226 //! Get a list of Networks to restore
227 /** Return a list of networks the user was connected at the time of core shutdown
228 * \note This method is threadsafe.
230 * \param user The User Id in question
232 static inline QList<NetworkId> connectedNetworks(UserId user)
234 return instance()->_storage->connectedNetworks(user);
238 //! Update the connected state of a network
239 /** \note This method is threadsafe
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
245 static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
247 return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
251 //! Get a hash of channels with their channel keys for a given network
252 /** The keys are channel names and values are passwords (possibly empty)
253 * \note This method is threadsafe
255 * \param user The id of the networks owner
256 * \param networkId The Id of the network
258 static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
260 return instance()->_storage->persistentChannels(user, networkId);
264 //! Update the connected state of a channel
265 /** \note This method is threadsafe
267 * \param user The Id of the networks owner
268 * \param networkId The Id of the network
269 * \param channel The name of the channel
270 * \param isJoined whether the channel is connected or not
272 static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
274 return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
278 //! Get a hash of buffers with their ciphers for a given network
279 /** The keys are channel names and values are ciphers (possibly empty)
280 * \note This method is threadsafe
282 * \param user The id of the networks owner
283 * \param networkId The Id of the network
285 static inline QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId)
287 return instance()->_storage->bufferCiphers(user, networkId);
291 //! Update the cipher of a buffer
292 /** \note This method is threadsafe
294 * \param user The Id of the networks owner
295 * \param networkId The Id of the network
296 * \param bufferName The Cname of the buffer
297 * \param cipher The cipher for the buffer
299 static inline void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher)
301 return instance()->_storage->setBufferCipher(user, networkId, bufferName, cipher);
305 //! Update the key of a channel
306 /** \note This method is threadsafe
308 * \param user The Id of the networks owner
309 * \param networkId The Id of the network
310 * \param channel The name of the channel
311 * \param key The key of the channel (possibly empty)
313 static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
315 return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
319 //! retrieve last known away message for session restore
320 /** \note This method is threadsafe
322 * \param user The Id of the networks owner
323 * \param networkId The Id of the network
325 static inline QString awayMessage(UserId user, NetworkId networkId)
327 return instance()->_storage->awayMessage(user, networkId);
331 //! Make away message persistent for session restore
332 /** \note This method is threadsafe
334 * \param user The Id of the networks owner
335 * \param networkId The Id of the network
336 * \param awayMsg The current away message of own user
338 static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
340 return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
344 //! retrieve last known user mode for session restore
345 /** \note This method is threadsafe
347 * \param user The Id of the networks owner
348 * \param networkId The Id of the network
350 static inline QString userModes(UserId user, NetworkId networkId)
352 return instance()->_storage->userModes(user, networkId);
356 //! Make our user modes persistent for session restore
357 /** \note This method is threadsafe
359 * \param user The Id of the networks owner
360 * \param networkId The Id of the network
361 * \param userModes The current user modes of own user
363 static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
365 return instance()->_storage->setUserModes(user, networkId, userModes);
369 //! Get the unique BufferInfo for the given combination of network and buffername for a user.
370 /** \note This method is threadsafe.
372 * \param user The core user who owns this buffername
373 * \param networkId The network id
374 * \param type The type of the buffer (StatusBuffer, Channel, etc.)
375 * \param buffer The buffer name (if empty, the net's status buffer is returned)
376 * \param create Whether or not the buffer should be created if it doesnt exist
377 * \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
379 static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
381 return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
385 //! Get the unique BufferInfo for a bufferId
386 /** \note This method is threadsafe
387 * \param user The core user who owns this buffername
388 * \param bufferId The id of the buffer
389 * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
391 static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
393 return instance()->_storage->getBufferInfo(user, bufferId);
397 //! Store a Message in the storage backend and set it's unique Id.
398 /** \note This method is threadsafe.
400 * \param message The message object to be stored
401 * \return true on success
403 static inline bool storeMessage(Message &message)
405 return instance()->_storage->logMessage(message);
409 //! Store a list of Messages in the storage backend and set their unique Id.
410 /** \note This method is threadsafe.
412 * \param messages The list message objects to be stored
413 * \return true on success
415 static inline bool storeMessages(MessageList &messages)
417 return instance()->_storage->logMessages(messages);
421 //! Request a certain number messages stored in a given buffer.
422 /** \param buffer The buffer we request messages from
423 * \param first if != -1 return only messages with a MsgId >= first
424 * \param last if != -1 return only messages with a MsgId < last
425 * \param limit if != -1 limit the returned list to a max of \limit entries
426 * \return The requested list of messages
428 static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
430 return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
434 //! Request a certain number messages stored in a given buffer, matching certain filters
435 /** \param buffer The buffer we request messages from
436 * \param first if != -1 return only messages with a MsgId >= first
437 * \param last if != -1 return only messages with a MsgId < last
438 * \param limit if != -1 limit the returned list to a max of \limit entries
439 * \param type The Message::Types that should be returned
440 * \return The requested list of messages
442 static inline QList<Message> requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1,
443 int limit = -1, Message::Types type = Message::Types{-1},
444 Message::Flags flags = Message::Flags{-1})
446 return instance()->_storage->requestMsgsFiltered(user, bufferId, first, last, limit, type, flags);
450 //! Request a certain number of messages across all buffers
451 /** \param first if != -1 return only messages with a MsgId >= first
452 * \param last if != -1 return only messages with a MsgId < last
453 * \param limit Max amount of messages
454 * \return The requested list of messages
456 static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
458 return instance()->_storage->requestAllMsgs(user, first, last, limit);
462 //! Request a certain number of messages across all buffers, matching certain filters
463 /** \param first if != -1 return only messages with a MsgId >= first
464 * \param last if != -1 return only messages with a MsgId < last
465 * \param limit Max amount of messages
466 * \param type The Message::Types that should be returned
467 * \return The requested list of messages
469 static inline QList<Message> requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1,
470 Message::Types type = Message::Types{-1},
471 Message::Flags flags = Message::Flags{-1})
473 return instance()->_storage->requestAllMsgsFiltered(user, first, last, limit, type, flags);
477 //! Request a list of all buffers known to a user.
478 /** This method is used to get a list of all buffers we have stored a backlog from.
479 * \note This method is threadsafe.
481 * \param user The user whose buffers we request
482 * \return A list of the BufferInfos for all buffers as requested
484 static inline QList<BufferInfo> requestBuffers(UserId user)
486 return instance()->_storage->requestBuffers(user);
490 //! Request a list of BufferIds for a given NetworkId
491 /** \note This method is threadsafe.
493 * \param user The user whose buffers we request
494 * \param networkId The NetworkId of the network in question
495 * \return List of BufferIds belonging to the Network
497 static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
499 return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
503 //! Remove permanently a buffer and it's content from the storage backend
504 /** This call cannot be reverted!
505 * \note This method is threadsafe.
507 * \param user The user who is the owner of the buffer
508 * \param bufferId The bufferId
509 * \return true if successfull
511 static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
513 return instance()->_storage->removeBuffer(user, bufferId);
518 /** \note This method is threadsafe.
519 * \param user The id of the buffer owner
520 * \param bufferId The bufferId
521 * \param newName The new name of the buffer
522 * \return true if successfull
524 static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
526 return instance()->_storage->renameBuffer(user, bufferId, newName);
530 //! Merge the content of two Buffers permanently. This cannot be reversed!
531 /** \note This method is threadsafe.
532 * \param user The id of the buffer owner
533 * \param bufferId1 The bufferId of the remaining buffer
534 * \param bufferId2 The buffer that is about to be removed
535 * \return true if successfulln
537 static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
539 return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
543 //! Update the LastSeenDate for a Buffer
544 /** This Method is used to make the LastSeenDate of a Buffer persistent
545 * \note This method is threadsafe.
547 * \param user The Owner of that Buffer
548 * \param bufferId The buffer id
549 * \param MsgId The Message id of the message that has been just seen
551 static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
553 return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
556 //! Get the auth username associated with a userId
557 /** \param user The user to retrieve the username for
558 * \return The username for the user
560 static inline QString getAuthUserName(UserId user) {
561 return instance()->_storage->getAuthUserName(user);
564 //! Get a usable sysident for the given user in oidentd-strict mode
565 /** \param user The user to retrieve the sysident for
566 * \return The authusername
568 QString strictSysIdent(UserId user) const;
571 //! Get a Hash of all last seen message ids
572 /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
573 * \note This method is threadsafe.
575 * \param user The Owner of the buffers
577 static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
579 return instance()->_storage->bufferLastSeenMsgIds(user);
583 //! Update the MarkerLineMsgId for a Buffer
584 /** This Method is used to make the marker line position of a Buffer persistent
585 * \note This method is threadsafe.
587 * \param user The Owner of that Buffer
588 * \param bufferId The buffer id
589 * \param MsgId The Message id where the marker line should be placed
591 static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
593 return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
597 //! Get a Hash of all marker line message ids
598 /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
599 * \note This method is threadsafe.
601 * \param user The Owner of the buffers
603 static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
605 return instance()->_storage->bufferMarkerLineMsgIds(user);
608 //! Update the BufferActivity for a Buffer
609 /** This Method is used to make the activity state of a Buffer persistent
610 * \note This method is threadsafe.
612 * \param user The Owner of that Buffer
613 * \param bufferId The buffer id
614 * \param MsgId The Message id where the marker line should be placed
616 static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity) {
617 return instance()->_storage->setBufferActivity(user, bufferId, activity);
621 //! Get a Hash of all buffer activity states
622 /** This Method is called when the Quassel Core is started to restore the BufferActivity
623 * \note This method is threadsafe.
625 * \param user The Owner of the buffers
627 static inline QHash<BufferId, Message::Types> bufferActivities(UserId user) {
628 return instance()->_storage->bufferActivities(user);
631 //! Get the bitset of buffer activity states for a buffer
632 /** This method is used to load the activity state 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 Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) {
639 return instance()->_storage->bufferActivity(bufferId, lastSeenMsgId);
642 //! Update the highlight count for a Buffer
643 /** This Method is used to make the highlight count state of a Buffer persistent
644 * \note This method is threadsafe.
646 * \param user The Owner of that Buffer
647 * \param bufferId The buffer id
648 * \param MsgId The Message id where the marker line should be placed
650 static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount) {
651 return instance()->_storage->setHighlightCount(user, bufferId, highlightCount);
655 //! Get a Hash of all highlight count states
656 /** This Method is called when the Quassel Core is started to restore the highlight count
657 * \note This method is threadsafe.
659 * \param user The Owner of the buffers
661 static inline QHash<BufferId, int> highlightCounts(UserId user) {
662 return instance()->_storage->highlightCounts(user);
664 //! Get the highlight count states for a buffer
665 /** This method is used to load the highlight count of a buffer when its last seen message changes.
666 * \note This method is threadsafe.
668 * \param bufferId The buffer
669 * \param lastSeenMsgId The last seen message
671 static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) {
672 return instance()->_storage->highlightCount(bufferId, lastSeenMsgId);
675 static inline QDateTime startTime() { return instance()->_startTime; }
676 static inline bool isConfigured() { return instance()->_configured; }
679 * Whether or not strict ident mode is enabled, locking users' idents to Quassel username
681 * @return True if strict mode enabled, otherwise false
683 static inline bool strictIdentEnabled() { return instance()->_strictIdentEnabled; }
685 static bool sslSupported();
687 static QVariantList backendInfo();
688 static QVariantList authenticatorInfo();
690 static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
692 static inline QTimer *syncTimer() { return &instance()->_storageSyncTimer; }
694 inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
696 static const int AddClientEventId;
699 //! Sent when a BufferInfo is updated in storage.
700 void bufferInfoUpdated(UserId user, const BufferInfo &info);
702 //! Relay from CoreSession::sessionState(). Used for internal connection only
703 void sessionState(const Protocol::SessionState &sessionState);
705 //! Emitted when database schema upgrade starts or ends
706 void dbUpgradeInProgress(bool inProgress);
713 * @note This method is threadsafe.
718 * Reload SSL certificates used for connection with clients.
720 * @return True if certificates reloaded successfully, otherwise false.
724 void cacheSysIdent();
726 QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
728 void connectInternalPeer(QPointer<InternalPeer> peer);
731 void customEvent(QEvent *event) override;
734 bool startListening();
735 void stopListening(const QString &msg = QString());
736 void incomingConnection();
737 void clientDisconnected();
739 bool initStorage(const QString &backend, const QVariantMap &settings,
740 const QProcessEnvironment &environment, bool loadFromEnvironment,
742 bool initAuthenticator(const QString &backend, const QVariantMap &settings,
743 const QProcessEnvironment &environment, bool loadFromEnvironment,
746 void socketError(QAbstractSocket::SocketError err, const QString &errorString);
747 void setupClientSession(RemotePeer *, UserId);
749 bool changeUserPass(const QString &username);
752 SessionThread *sessionForUser(UserId userId, bool restoreState = false);
753 void addClientHelper(RemotePeer *peer, UserId uid);
754 //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
755 QString setupCoreForInternalUsage();
756 void setupInternalClientSession(QPointer<InternalPeer> peer);
760 template<typename Storage>
761 void registerStorageBackend();
763 template<typename Authenticator>
764 void registerAuthenticator();
766 void registerStorageBackends();
767 void registerAuthenticators();
769 DeferredSharedPtr<Storage> storageBackend(const QString& backendId) const;
770 DeferredSharedPtr<Authenticator> authenticator(const QString& authenticatorId) const;
772 bool selectBackend(const QString &backend);
773 bool selectAuthenticator(const QString &backend);
775 bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
776 void saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings);
781 template<typename Backend>
782 QVariantMap promptForSettings(const Backend *backend);
785 static Core *_instance;
786 QSet<CoreAuthHandler *> _connectingClients;
787 QHash<UserId, SessionThread *> _sessions;
788 DeferredSharedPtr<Storage> _storage; ///< Active storage backend
789 DeferredSharedPtr<Authenticator> _authenticator; ///< Active authenticator
790 QMap<UserId, QString> _authUserNames;
792 QTimer _storageSyncTimer;
795 SslServer _server, _v6server;
797 QTcpServer _server, _v6server;
800 OidentdConfigGenerator *_oidentdConfigGenerator {nullptr};
802 std::vector<DeferredSharedPtr<Storage>> _registeredStorageBackends;
803 std::vector<DeferredSharedPtr<Authenticator>> _registeredAuthenticators;
805 QDateTime _startTime;
807 bool _initialized{false};
808 bool _configured{false};
810 QPointer<InternalPeer> _pendingInternalConnection;
812 /// Whether or not strict ident mode is enabled, locking users' idents to Quassel username
813 bool _strictIdentEnabled;
815 static std::unique_ptr<AbstractSqlMigrationReader> getMigrationReader(Storage *storage);
816 static std::unique_ptr<AbstractSqlMigrationWriter> getMigrationWriter(Storage *storage);
817 static void stdInEcho(bool on);
818 static inline void enableStdInEcho() { stdInEcho(true); }
819 static inline void disableStdInEcho() { stdInEcho(false); }