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();
67 /*** Storage access ***/
68 // These methods are threadsafe.
72 * \param userName The user's login name
73 * \param password The user's uncrypted password
74 * \return The user's ID if valid; 0 otherwise
76 static inline UserId validateUser(const QString &userName, const QString &password) {
77 return instance()->_storage->validateUser(userName, password);
80 //! Authenticate user against auth backend
82 * \param userName The user's login name
83 * \param password The user's uncrypted password
84 * \return The user's ID if valid; 0 otherwise
86 static inline UserId authenticateUser(const QString &userName, const QString &password) {
87 return instance()->_authenticator->validateUser(userName, password);
90 //! Add a new user, exposed so auth providers can call this without being the storage.
92 * \param userName The user's login name
93 * \param password The user's uncrypted password
94 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
95 * \return The user's ID if valid; 0 otherwise
97 static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") {
98 return instance()->_storage->addUser(userName, password, authenticator);
101 //! Does a comparison test against the authenticator in the database and the authenticator currently in use for a UserID.
103 * \param userid The user's ID (note: not login name).
104 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
105 * \return True if the userid was configured with the passed authenticator, false otherwise.
107 static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) {
108 return instance()->_storage->getUserAuthenticator(userid) == authenticator;
111 //! Change a user's password
113 * \param userId The user's ID
114 * \param password The user's unencrypted new password
115 * \return true, if the password change was successful
117 static bool changeUserPassword(UserId userId, const QString &password);
119 //! Check if we can change a user password.
121 * \param userID The user's ID
122 * \return true, if we can change their password, false otherwise
124 static bool canChangeUserPassword(UserId userId);
126 //! Store a user setting persistently
128 * \param userId The users Id
129 * \param settingName The Name of the Setting
130 * \param data The Value
132 static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
134 instance()->_storage->setUserSetting(userId, settingName, data);
138 //! Retrieve a persistent user setting
140 * \param userId The users Id
141 * \param settingName The Name of the Setting
142 * \param defaultValue Value to return in case it's unset.
143 * \return the Value of the Setting or the default value if it is unset.
145 static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
147 return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
151 /* Identity handling */
152 static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
154 return instance()->_storage->createIdentity(user, identity);
158 static bool updateIdentity(UserId user, const CoreIdentity &identity)
160 return instance()->_storage->updateIdentity(user, identity);
164 static void removeIdentity(UserId user, IdentityId identityId)
166 instance()->_storage->removeIdentity(user, identityId);
170 static QList<CoreIdentity> identities(UserId user)
172 return instance()->_storage->identities(user);
176 //! Create a Network in the Storage and store it's Id in the given NetworkInfo
177 /** \note This method is thredsafe.
179 * \param user The core user
180 * \param networkInfo a NetworkInfo definition to store the newly created ID in
181 * \return true if successfull.
183 static bool createNetwork(UserId user, NetworkInfo &info);
185 //! Apply the changes to NetworkInfo info to the storage engine
186 /** \note This method is thredsafe.
188 * \param user The core user
189 * \param networkInfo The Updated NetworkInfo
190 * \return true if successfull.
192 static inline bool updateNetwork(UserId user, const NetworkInfo &info)
194 return instance()->_storage->updateNetwork(user, info);
198 //! Permanently remove a Network and all the data associated with it.
199 /** \note This method is thredsafe.
201 * \param user The core user
202 * \param networkId The network to delete
203 * \return true if successfull.
205 static inline bool removeNetwork(UserId user, const NetworkId &networkId)
207 return instance()->_storage->removeNetwork(user, networkId);
211 //! Returns a list of all NetworkInfos for the given UserId user
212 /** \note This method is thredsafe.
214 * \param user The core user
215 * \return QList<NetworkInfo>.
217 static inline QList<NetworkInfo> networks(UserId user)
219 return instance()->_storage->networks(user);
223 //! Get a list of Networks to restore
224 /** Return a list of networks the user was connected at the time of core shutdown
225 * \note This method is threadsafe.
227 * \param user The User Id in question
229 static inline QList<NetworkId> connectedNetworks(UserId user)
231 return instance()->_storage->connectedNetworks(user);
235 //! Update the connected state of a network
236 /** \note This method is threadsafe
238 * \param user The Id of the networks owner
239 * \param networkId The Id of the network
240 * \param isConnected whether the network is connected or not
242 static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
244 return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
248 //! Get a hash of channels with their channel keys for a given network
249 /** The keys are channel names and values are passwords (possibly empty)
250 * \note This method is threadsafe
252 * \param user The id of the networks owner
253 * \param networkId The Id of the network
255 static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
257 return instance()->_storage->persistentChannels(user, networkId);
261 //! Update the connected state of a channel
262 /** \note This method is threadsafe
264 * \param user The Id of the networks owner
265 * \param networkId The Id of the network
266 * \param channel The name of the channel
267 * \param isJoined whether the channel is connected or not
269 static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
271 return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
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
279 * \param user The id of the networks owner
280 * \param networkId The Id of the network
282 static inline QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId)
284 return instance()->_storage->bufferCiphers(user, networkId);
288 //! Update the cipher of a buffer
289 /** \note This method is threadsafe
291 * \param user The Id of the networks owner
292 * \param networkId The Id of the network
293 * \param bufferName The Cname of the buffer
294 * \param cipher The cipher for the buffer
296 static inline void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher)
298 return instance()->_storage->setBufferCipher(user, networkId, bufferName, cipher);
302 //! Update the key of a channel
303 /** \note This method is threadsafe
305 * \param user The Id of the networks owner
306 * \param networkId The Id of the network
307 * \param channel The name of the channel
308 * \param key The key of the channel (possibly empty)
310 static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
312 return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
316 //! retrieve last known away message for session restore
317 /** \note This method is threadsafe
319 * \param user The Id of the networks owner
320 * \param networkId The Id of the network
322 static inline QString awayMessage(UserId user, NetworkId networkId)
324 return instance()->_storage->awayMessage(user, networkId);
328 //! Make away message persistent for session restore
329 /** \note This method is threadsafe
331 * \param user The Id of the networks owner
332 * \param networkId The Id of the network
333 * \param awayMsg The current away message of own user
335 static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
337 return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
341 //! retrieve last known user mode for session restore
342 /** \note This method is threadsafe
344 * \param user The Id of the networks owner
345 * \param networkId The Id of the network
347 static inline QString userModes(UserId user, NetworkId networkId)
349 return instance()->_storage->userModes(user, networkId);
353 //! Make our user modes persistent for session restore
354 /** \note This method is threadsafe
356 * \param user The Id of the networks owner
357 * \param networkId The Id of the network
358 * \param userModes The current user modes of own user
360 static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
362 return instance()->_storage->setUserModes(user, networkId, userModes);
366 //! Get the unique BufferInfo for the given combination of network and buffername for a user.
367 /** \note This method is threadsafe.
369 * \param user The core user who owns this buffername
370 * \param networkId The network id
371 * \param type The type of the buffer (StatusBuffer, Channel, etc.)
372 * \param buffer The buffer name (if empty, the net's status buffer is returned)
373 * \param create Whether or not the buffer should be created if it doesnt exist
374 * \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
376 static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
378 return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
382 //! Get the unique BufferInfo for a bufferId
383 /** \note This method is threadsafe
384 * \param user The core user who owns this buffername
385 * \param bufferId The id of the buffer
386 * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
388 static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
390 return instance()->_storage->getBufferInfo(user, bufferId);
394 //! Store a Message in the storage backend and set it's unique Id.
395 /** \note This method is threadsafe.
397 * \param message The message object to be stored
398 * \return true on success
400 static inline bool storeMessage(Message &message)
402 return instance()->_storage->logMessage(message);
406 //! Store a list of Messages in the storage backend and set their unique Id.
407 /** \note This method is threadsafe.
409 * \param messages The list message objects to be stored
410 * \return true on success
412 static inline bool storeMessages(MessageList &messages)
414 return instance()->_storage->logMessages(messages);
418 //! Request a certain number messages stored in a given buffer.
419 /** \param buffer The buffer we request messages from
420 * \param first if != -1 return only messages with a MsgId >= first
421 * \param last if != -1 return only messages with a MsgId < last
422 * \param limit if != -1 limit the returned list to a max of \limit entries
423 * \return The requested list of messages
425 static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
427 return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
431 //! Request a certain number messages stored in a given buffer, matching certain filters
432 /** \param buffer The buffer we request messages from
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 if != -1 limit the returned list to a max of \limit entries
436 * \param type The Message::Types that should be returned
437 * \return The requested list of messages
439 static inline QList<Message> requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1,
440 int limit = -1, Message::Types type = Message::Types{-1},
441 Message::Flags flags = Message::Flags{-1})
443 return instance()->_storage->requestMsgsFiltered(user, bufferId, first, last, limit, type, flags);
447 //! Request a certain number of messages across all buffers
448 /** \param first if != -1 return only messages with a MsgId >= first
449 * \param last if != -1 return only messages with a MsgId < last
450 * \param limit Max amount of messages
451 * \return The requested list of messages
453 static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
455 return instance()->_storage->requestAllMsgs(user, first, last, limit);
459 //! Request a certain number of messages across all buffers, matching certain filters
460 /** \param first if != -1 return only messages with a MsgId >= first
461 * \param last if != -1 return only messages with a MsgId < last
462 * \param limit Max amount of messages
463 * \param type The Message::Types that should be returned
464 * \return The requested list of messages
466 static inline QList<Message> requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1,
467 Message::Types type = Message::Types{-1},
468 Message::Flags flags = Message::Flags{-1})
470 return instance()->_storage->requestAllMsgsFiltered(user, first, last, limit, type, flags);
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.
478 * \param user The user whose buffers we request
479 * \return A list of the BufferInfos for all buffers as requested
481 static inline QList<BufferInfo> requestBuffers(UserId user)
483 return instance()->_storage->requestBuffers(user);
487 //! Request a list of BufferIds for a given NetworkId
488 /** \note This method is threadsafe.
490 * \param user The user whose buffers we request
491 * \param networkId The NetworkId of the network in question
492 * \return List of BufferIds belonging to the Network
494 static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
496 return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
500 //! Remove permanently a buffer and it's content from the storage backend
501 /** This call cannot be reverted!
502 * \note This method is threadsafe.
504 * \param user The user who is the owner of the buffer
505 * \param bufferId The bufferId
506 * \return true if successfull
508 static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
510 return instance()->_storage->removeBuffer(user, bufferId);
515 /** \note This method is threadsafe.
516 * \param user The id of the buffer owner
517 * \param bufferId The bufferId
518 * \param newName The new name of the buffer
519 * \return true if successfull
521 static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
523 return instance()->_storage->renameBuffer(user, bufferId, newName);
527 //! Merge the content of two Buffers permanently. This cannot be reversed!
528 /** \note This method is threadsafe.
529 * \param user The id of the buffer owner
530 * \param bufferId1 The bufferId of the remaining buffer
531 * \param bufferId2 The buffer that is about to be removed
532 * \return true if successfulln
534 static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
536 return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
540 //! Update the LastSeenDate for a Buffer
541 /** This Method is used to make the LastSeenDate of a Buffer persistent
542 * \note This method is threadsafe.
544 * \param user The Owner of that Buffer
545 * \param bufferId The buffer id
546 * \param MsgId The Message id of the message that has been just seen
548 static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
550 return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
553 //! Get the auth username associated with a userId
554 /** \param user The user to retrieve the username for
555 * \return The username for the user
557 static inline QString getAuthUserName(UserId user) {
558 return instance()->_storage->getAuthUserName(user);
561 //! Get a usable sysident for the given user in oidentd-strict mode
562 /** \param user The user to retrieve the sysident for
563 * \return The authusername
565 QString strictSysIdent(UserId user) const;
568 //! Get a Hash of all last seen message ids
569 /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
570 * \note This method is threadsafe.
572 * \param user The Owner of the buffers
574 static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
576 return instance()->_storage->bufferLastSeenMsgIds(user);
580 //! Update the MarkerLineMsgId for a Buffer
581 /** This Method is used to make the marker line position of a Buffer persistent
582 * \note This method is threadsafe.
584 * \param user The Owner of that Buffer
585 * \param bufferId The buffer id
586 * \param MsgId The Message id where the marker line should be placed
588 static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
590 return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
594 //! Get a Hash of all marker line message ids
595 /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
596 * \note This method is threadsafe.
598 * \param user The Owner of the buffers
600 static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
602 return instance()->_storage->bufferMarkerLineMsgIds(user);
605 //! Update the BufferActivity for a Buffer
606 /** This Method is used to make the activity state of a Buffer persistent
607 * \note This method is threadsafe.
609 * \param user The Owner of that Buffer
610 * \param bufferId The buffer id
611 * \param MsgId The Message id where the marker line should be placed
613 static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity) {
614 return instance()->_storage->setBufferActivity(user, bufferId, activity);
618 //! Get a Hash of all buffer activity states
619 /** This Method is called when the Quassel Core is started to restore the BufferActivity
620 * \note This method is threadsafe.
622 * \param user The Owner of the buffers
624 static inline QHash<BufferId, Message::Types> bufferActivities(UserId user) {
625 return instance()->_storage->bufferActivities(user);
628 //! Get the bitset of buffer activity states for a buffer
629 /** This method is used to load the activity state of a buffer when its last seen message changes.
630 * \note This method is threadsafe.
632 * \param bufferId The buffer
633 * \param lastSeenMsgId The last seen message
635 static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) {
636 return instance()->_storage->bufferActivity(bufferId, lastSeenMsgId);
639 //! Update the highlight count for a Buffer
640 /** This Method is used to make the highlight count state of a Buffer persistent
641 * \note This method is threadsafe.
643 * \param user The Owner of that Buffer
644 * \param bufferId The buffer id
645 * \param MsgId The Message id where the marker line should be placed
647 static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount) {
648 return instance()->_storage->setHighlightCount(user, bufferId, highlightCount);
652 //! Get a Hash of all highlight count states
653 /** This Method is called when the Quassel Core is started to restore the highlight count
654 * \note This method is threadsafe.
656 * \param user The Owner of the buffers
658 static inline QHash<BufferId, int> highlightCounts(UserId user) {
659 return instance()->_storage->highlightCounts(user);
661 //! Get the highlight count states for a buffer
662 /** This method is used to load the highlight count of a buffer when its last seen message changes.
663 * \note This method is threadsafe.
665 * \param bufferId The buffer
666 * \param lastSeenMsgId The last seen message
668 static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) {
669 return instance()->_storage->highlightCount(bufferId, lastSeenMsgId);
672 static inline QDateTime startTime() { return instance()->_startTime; }
673 static inline bool isConfigured() { return instance()->_configured; }
676 * Whether or not strict ident mode is enabled, locking users' idents to Quassel username
678 * @return True if strict mode enabled, otherwise false
680 static inline bool strictIdentEnabled() { return instance()->_strictIdentEnabled; }
682 static bool sslSupported();
684 static QVariantList backendInfo();
685 static QVariantList authenticatorInfo();
687 static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
689 static inline QTimer *syncTimer() { return &instance()->_storageSyncTimer; }
691 inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
693 static const int AddClientEventId;
700 * @note This method is threadsafe.
705 * Reload SSL certificates used for connection with clients.
707 * @return True if certificates reloaded successfully, otherwise false.
711 void cacheSysIdent();
713 void setupInternalClientSession(InternalPeer *clientConnection);
714 QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
717 //! Sent when a BufferInfo is updated in storage.
718 void bufferInfoUpdated(UserId user, const BufferInfo &info);
720 //! Relay from CoreSession::sessionState(). Used for internal connection only
721 void sessionState(const Protocol::SessionState &sessionState);
724 void customEvent(QEvent *event) override;
727 bool startListening();
728 void stopListening(const QString &msg = QString());
729 void incomingConnection();
730 void clientDisconnected();
732 bool initStorage(const QString &backend, const QVariantMap &settings,
733 const QProcessEnvironment &environment, bool loadFromEnvironment,
735 bool initAuthenticator(const QString &backend, const QVariantMap &settings,
736 const QProcessEnvironment &environment, bool loadFromEnvironment,
739 void socketError(QAbstractSocket::SocketError err, const QString &errorString);
740 void setupClientSession(RemotePeer *, UserId);
742 bool changeUserPass(const QString &username);
745 SessionThread *sessionForUser(UserId userId, bool restoreState = false);
746 void addClientHelper(RemotePeer *peer, UserId uid);
747 //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
748 QString setupCoreForInternalUsage();
752 template<typename Storage>
753 void registerStorageBackend();
755 template<typename Authenticator>
756 void registerAuthenticator();
758 void registerStorageBackends();
759 void registerAuthenticators();
761 DeferredSharedPtr<Storage> storageBackend(const QString& backendId) const;
762 DeferredSharedPtr<Authenticator> authenticator(const QString& authenticatorId) const;
764 bool selectBackend(const QString &backend);
765 bool selectAuthenticator(const QString &backend);
767 bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
768 void saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings);
773 template<typename Backend>
774 QVariantMap promptForSettings(const Backend *backend);
777 static Core *_instance;
778 QSet<CoreAuthHandler *> _connectingClients;
779 QHash<UserId, SessionThread *> _sessions;
780 DeferredSharedPtr<Storage> _storage; ///< Active storage backend
781 DeferredSharedPtr<Authenticator> _authenticator; ///< Active authenticator
782 QMap<UserId, QString> _authUserNames;
784 QTimer _storageSyncTimer;
787 SslServer _server, _v6server;
789 QTcpServer _server, _v6server;
792 OidentdConfigGenerator *_oidentdConfigGenerator {nullptr};
794 std::vector<DeferredSharedPtr<Storage>> _registeredStorageBackends;
795 std::vector<DeferredSharedPtr<Authenticator>> _registeredAuthenticators;
797 QDateTime _startTime;
801 /// Whether or not strict ident mode is enabled, locking users' idents to Quassel username
802 bool _strictIdentEnabled;
804 static std::unique_ptr<AbstractSqlMigrationReader> getMigrationReader(Storage *storage);
805 static std::unique_ptr<AbstractSqlMigrationWriter> getMigrationWriter(Storage *storage);
806 static void stdInEcho(bool on);
807 static inline void enableStdInEcho() { stdInEcho(true); }
808 static inline void disableStdInEcho() { stdInEcho(false); }