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"
43 #include "identserver.h"
45 #include "oidentdconfiggenerator.h"
46 #include "sessionthread.h"
50 class CoreAuthHandler;
58 class AbstractSqlMigrationReader;
59 class AbstractSqlMigrationWriter;
61 class Core : public QObject
66 static Core *instance();
73 /*** Storage access ***/
74 // These methods are threadsafe.
78 * \param userName The user's login name
79 * \param password The user's uncrypted password
80 * \return The user's ID if valid; 0 otherwise
82 static inline UserId validateUser(const QString &userName, const QString &password) {
83 return instance()->_storage->validateUser(userName, password);
86 //! Authenticate user against auth backend
88 * \param userName The user's login name
89 * \param password The user's uncrypted password
90 * \return The user's ID if valid; 0 otherwise
92 static inline UserId authenticateUser(const QString &userName, const QString &password) {
93 return instance()->_authenticator->validateUser(userName, password);
96 //! Add a new user, exposed so auth providers can call this without being the storage.
98 * \param userName The user's login name
99 * \param password The user's uncrypted password
100 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
101 * \return The user's ID if valid; 0 otherwise
103 static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") {
104 return instance()->_storage->addUser(userName, password, authenticator);
107 //! Does a comparison test against the authenticator in the database and the authenticator currently in use for a UserID.
109 * \param userid The user's ID (note: not login name).
110 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
111 * \return True if the userid was configured with the passed authenticator, false otherwise.
113 static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) {
114 return instance()->_storage->getUserAuthenticator(userid) == authenticator;
117 //! Change a user's password
119 * \param userId The user's ID
120 * \param password The user's unencrypted new password
121 * \return true, if the password change was successful
123 static bool changeUserPassword(UserId userId, const QString &password);
125 //! Check if we can change a user password.
127 * \param userID The user's ID
128 * \return true, if we can change their password, false otherwise
130 static bool canChangeUserPassword(UserId userId);
132 //! Store a user setting persistently
134 * \param userId The users Id
135 * \param settingName The Name of the Setting
136 * \param data The Value
138 static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
140 instance()->_storage->setUserSetting(userId, settingName, data);
144 //! Retrieve a persistent user setting
146 * \param userId The users Id
147 * \param settingName The Name of the Setting
148 * \param defaultValue Value to return in case it's unset.
149 * \return the Value of the Setting or the default value if it is unset.
151 static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
153 return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
157 /* Identity handling */
158 static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
160 return instance()->_storage->createIdentity(user, identity);
164 static bool updateIdentity(UserId user, const CoreIdentity &identity)
166 return instance()->_storage->updateIdentity(user, identity);
170 static void removeIdentity(UserId user, IdentityId identityId)
172 instance()->_storage->removeIdentity(user, identityId);
176 static QList<CoreIdentity> identities(UserId user)
178 return instance()->_storage->identities(user);
182 //! Create a Network in the Storage and store it's Id in the given NetworkInfo
183 /** \note This method is thredsafe.
185 * \param user The core user
186 * \param networkInfo a NetworkInfo definition to store the newly created ID in
187 * \return true if successfull.
189 static bool createNetwork(UserId user, NetworkInfo &info);
191 //! Apply the changes to NetworkInfo info to the storage engine
192 /** \note This method is thredsafe.
194 * \param user The core user
195 * \param networkInfo The Updated NetworkInfo
196 * \return true if successfull.
198 static inline bool updateNetwork(UserId user, const NetworkInfo &info)
200 return instance()->_storage->updateNetwork(user, info);
204 //! Permanently remove a Network and all the data associated with it.
205 /** \note This method is thredsafe.
207 * \param user The core user
208 * \param networkId The network to delete
209 * \return true if successfull.
211 static inline bool removeNetwork(UserId user, const NetworkId &networkId)
213 return instance()->_storage->removeNetwork(user, networkId);
217 //! Returns a list of all NetworkInfos for the given UserId user
218 /** \note This method is thredsafe.
220 * \param user The core user
221 * \return QList<NetworkInfo>.
223 static inline QList<NetworkInfo> networks(UserId user)
225 return instance()->_storage->networks(user);
229 //! Get a list of Networks to restore
230 /** Return a list of networks the user was connected at the time of core shutdown
231 * \note This method is threadsafe.
233 * \param user The User Id in question
235 static inline QList<NetworkId> connectedNetworks(UserId user)
237 return instance()->_storage->connectedNetworks(user);
241 //! Update the connected state of a network
242 /** \note This method is threadsafe
244 * \param user The Id of the networks owner
245 * \param networkId The Id of the network
246 * \param isConnected whether the network is connected or not
248 static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
250 return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
254 //! Get a hash of channels with their channel keys for a given network
255 /** The keys are channel names and values are passwords (possibly empty)
256 * \note This method is threadsafe
258 * \param user The id of the networks owner
259 * \param networkId The Id of the network
261 static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
263 return instance()->_storage->persistentChannels(user, networkId);
267 //! Update the connected state of a channel
268 /** \note This method is threadsafe
270 * \param user The Id of the networks owner
271 * \param networkId The Id of the network
272 * \param channel The name of the channel
273 * \param isJoined whether the channel is connected or not
275 static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
277 return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
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
285 * \param user The id of the networks owner
286 * \param networkId The Id of the network
288 static inline QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId)
290 return instance()->_storage->bufferCiphers(user, networkId);
294 //! Update the cipher of a buffer
295 /** \note This method is threadsafe
297 * \param user The Id of the networks owner
298 * \param networkId The Id of the network
299 * \param bufferName The Cname of the buffer
300 * \param cipher The cipher for the buffer
302 static inline void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher)
304 return instance()->_storage->setBufferCipher(user, networkId, bufferName, cipher);
308 //! Update the key of a channel
309 /** \note This method is threadsafe
311 * \param user The Id of the networks owner
312 * \param networkId The Id of the network
313 * \param channel The name of the channel
314 * \param key The key of the channel (possibly empty)
316 static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
318 return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
322 //! retrieve last known away message for session restore
323 /** \note This method is threadsafe
325 * \param user The Id of the networks owner
326 * \param networkId The Id of the network
328 static inline QString awayMessage(UserId user, NetworkId networkId)
330 return instance()->_storage->awayMessage(user, networkId);
334 //! Make away message persistent for session restore
335 /** \note This method is threadsafe
337 * \param user The Id of the networks owner
338 * \param networkId The Id of the network
339 * \param awayMsg The current away message of own user
341 static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
343 return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
347 //! retrieve last known user mode for session restore
348 /** \note This method is threadsafe
350 * \param user The Id of the networks owner
351 * \param networkId The Id of the network
353 static inline QString userModes(UserId user, NetworkId networkId)
355 return instance()->_storage->userModes(user, networkId);
359 //! Make our user modes persistent for session restore
360 /** \note This method is threadsafe
362 * \param user The Id of the networks owner
363 * \param networkId The Id of the network
364 * \param userModes The current user modes of own user
366 static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
368 return instance()->_storage->setUserModes(user, networkId, userModes);
372 //! Get the unique BufferInfo for the given combination of network and buffername for a user.
373 /** \note This method is threadsafe.
375 * \param user The core user who owns this buffername
376 * \param networkId The network id
377 * \param type The type of the buffer (StatusBuffer, Channel, etc.)
378 * \param buffer The buffer name (if empty, the net's status buffer is returned)
379 * \param create Whether or not the buffer should be created if it doesnt exist
380 * \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
382 static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
384 return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
388 //! Get the unique BufferInfo for a bufferId
389 /** \note This method is threadsafe
390 * \param user The core user who owns this buffername
391 * \param bufferId The id of the buffer
392 * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
394 static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
396 return instance()->_storage->getBufferInfo(user, bufferId);
400 //! Store a Message in the storage backend and set it's unique Id.
401 /** \note This method is threadsafe.
403 * \param message The message object to be stored
404 * \return true on success
406 static inline bool storeMessage(Message &message)
408 return instance()->_storage->logMessage(message);
412 //! Store a list of Messages in the storage backend and set their unique Id.
413 /** \note This method is threadsafe.
415 * \param messages The list message objects to be stored
416 * \return true on success
418 static inline bool storeMessages(MessageList &messages)
420 return instance()->_storage->logMessages(messages);
424 //! Request a certain number messages stored in a given buffer.
425 /** \param buffer The buffer we request messages from
426 * \param first if != -1 return only messages with a MsgId >= first
427 * \param last if != -1 return only messages with a MsgId < last
428 * \param limit if != -1 limit the returned list to a max of \limit entries
429 * \return The requested list of messages
431 static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
433 return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
437 //! Request a certain number messages stored in a given buffer, matching certain filters
438 /** \param buffer The buffer we request messages from
439 * \param first if != -1 return only messages with a MsgId >= first
440 * \param last if != -1 return only messages with a MsgId < last
441 * \param limit if != -1 limit the returned list to a max of \limit entries
442 * \param type The Message::Types that should be returned
443 * \return The requested list of messages
445 static inline QList<Message> requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1,
446 int limit = -1, Message::Types type = Message::Types{-1},
447 Message::Flags flags = Message::Flags{-1})
449 return instance()->_storage->requestMsgsFiltered(user, bufferId, first, last, limit, type, flags);
453 //! Request a certain number of messages across all buffers
454 /** \param first if != -1 return only messages with a MsgId >= first
455 * \param last if != -1 return only messages with a MsgId < last
456 * \param limit Max amount of messages
457 * \return The requested list of messages
459 static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
461 return instance()->_storage->requestAllMsgs(user, first, last, limit);
465 //! Request a certain number of messages across all buffers, matching certain filters
466 /** \param first if != -1 return only messages with a MsgId >= first
467 * \param last if != -1 return only messages with a MsgId < last
468 * \param limit Max amount of messages
469 * \param type The Message::Types that should be returned
470 * \return The requested list of messages
472 static inline QList<Message> requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1,
473 Message::Types type = Message::Types{-1},
474 Message::Flags flags = Message::Flags{-1})
476 return instance()->_storage->requestAllMsgsFiltered(user, first, last, limit, type, flags);
480 //! Request a list of all buffers known to a user.
481 /** This method is used to get a list of all buffers we have stored a backlog from.
482 * \note This method is threadsafe.
484 * \param user The user whose buffers we request
485 * \return A list of the BufferInfos for all buffers as requested
487 static inline QList<BufferInfo> requestBuffers(UserId user)
489 return instance()->_storage->requestBuffers(user);
493 //! Request a list of BufferIds for a given NetworkId
494 /** \note This method is threadsafe.
496 * \param user The user whose buffers we request
497 * \param networkId The NetworkId of the network in question
498 * \return List of BufferIds belonging to the Network
500 static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
502 return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
506 //! Remove permanently a buffer and it's content from the storage backend
507 /** This call cannot be reverted!
508 * \note This method is threadsafe.
510 * \param user The user who is the owner of the buffer
511 * \param bufferId The bufferId
512 * \return true if successfull
514 static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
516 return instance()->_storage->removeBuffer(user, bufferId);
521 /** \note This method is threadsafe.
522 * \param user The id of the buffer owner
523 * \param bufferId The bufferId
524 * \param newName The new name of the buffer
525 * \return true if successfull
527 static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
529 return instance()->_storage->renameBuffer(user, bufferId, newName);
533 //! Merge the content of two Buffers permanently. This cannot be reversed!
534 /** \note This method is threadsafe.
535 * \param user The id of the buffer owner
536 * \param bufferId1 The bufferId of the remaining buffer
537 * \param bufferId2 The buffer that is about to be removed
538 * \return true if successfulln
540 static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
542 return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
546 //! Update the LastSeenDate for a Buffer
547 /** This Method is used to make the LastSeenDate of a Buffer persistent
548 * \note This method is threadsafe.
550 * \param user The Owner of that Buffer
551 * \param bufferId The buffer id
552 * \param MsgId The Message id of the message that has been just seen
554 static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
556 return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
560 //! Get a usable sysident for the given user in oidentd-strict mode
561 /** \param user The user to retrieve the sysident for
562 * \return The authusername
564 QString strictSysIdent(UserId user) const;
567 //! Get a Hash of all last seen message ids
568 /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
569 * \note This method is threadsafe.
571 * \param user The Owner of the buffers
573 static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
575 return instance()->_storage->bufferLastSeenMsgIds(user);
579 //! Update the MarkerLineMsgId for a Buffer
580 /** This Method is used to make the marker line position of a Buffer persistent
581 * \note This method is threadsafe.
583 * \param user The Owner of that Buffer
584 * \param bufferId The buffer id
585 * \param MsgId The Message id where the marker line should be placed
587 static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
589 return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
593 //! Get a Hash of all marker line message ids
594 /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
595 * \note This method is threadsafe.
597 * \param user The Owner of the buffers
599 static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
601 return instance()->_storage->bufferMarkerLineMsgIds(user);
604 //! Update the BufferActivity for a Buffer
605 /** This Method is used to make the activity state of a Buffer persistent
606 * \note This method is threadsafe.
608 * \param user The Owner of that Buffer
609 * \param bufferId The buffer id
610 * \param MsgId The Message id where the marker line should be placed
612 static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity) {
613 return instance()->_storage->setBufferActivity(user, bufferId, activity);
617 //! Get a Hash of all buffer activity states
618 /** This Method is called when the Quassel Core is started to restore the BufferActivity
619 * \note This method is threadsafe.
621 * \param user The Owner of the buffers
623 static inline QHash<BufferId, Message::Types> bufferActivities(UserId user) {
624 return instance()->_storage->bufferActivities(user);
627 //! Get the bitset of buffer activity states for a buffer
628 /** This method is used to load the activity state of a buffer when its last seen message changes.
629 * \note This method is threadsafe.
631 * \param bufferId The buffer
632 * \param lastSeenMsgId The last seen message
634 static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) {
635 return instance()->_storage->bufferActivity(bufferId, lastSeenMsgId);
638 //! Update the highlight count for a Buffer
639 /** This Method is used to make the highlight count state of a Buffer persistent
640 * \note This method is threadsafe.
642 * \param user The Owner of that Buffer
643 * \param bufferId The buffer id
644 * \param MsgId The Message id where the marker line should be placed
646 static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount) {
647 return instance()->_storage->setHighlightCount(user, bufferId, highlightCount);
651 //! Get a Hash of all highlight count states
652 /** This Method is called when the Quassel Core is started to restore the highlight count
653 * \note This method is threadsafe.
655 * \param user The Owner of the buffers
657 static inline QHash<BufferId, int> highlightCounts(UserId user) {
658 return instance()->_storage->highlightCounts(user);
660 //! Get the highlight count states for a buffer
661 /** This method is used to load the highlight count of a buffer when its last seen message changes.
662 * \note This method is threadsafe.
664 * \param bufferId The buffer
665 * \param lastSeenMsgId The last seen message
667 static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) {
668 return instance()->_storage->highlightCount(bufferId, lastSeenMsgId);
671 static inline QDateTime startTime() { return instance()->_startTime; }
672 static inline bool isConfigured() { return instance()->_configured; }
675 * Whether or not strict ident mode is enabled, locking users' idents to Quassel username
677 * @return True if strict mode enabled, otherwise false
679 static inline bool strictIdentEnabled() { return instance()->_strictIdentEnabled; }
681 static bool sslSupported();
683 static QVariantList backendInfo();
684 static QVariantList authenticatorInfo();
686 static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
688 static inline QTimer *syncTimer() { return &instance()->_storageSyncTimer; }
690 inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
691 inline IdentServer *identServer() const { return _identServer; }
693 static const int AddClientEventId;
696 //! Sent when a BufferInfo is updated in storage.
697 void bufferInfoUpdated(UserId user, const BufferInfo &info);
699 //! Relay from CoreSession::sessionState(). Used for internal connection only
700 void sessionState(const Protocol::SessionState &sessionState);
702 //! Emitted when database schema upgrade starts or ends
703 void dbUpgradeInProgress(bool inProgress);
705 //! Emitted when a fatal error was encountered during async initialization
706 void exitRequested(int exitCode, const QString &reason);
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 IdentServer *_identServer {nullptr};
809 bool _initialized{false};
810 bool _configured{false};
812 QPointer<InternalPeer> _pendingInternalConnection;
814 /// Whether or not strict ident mode is enabled, locking users' idents to Quassel username
815 bool _strictIdentEnabled;
817 static std::unique_ptr<AbstractSqlMigrationReader> getMigrationReader(Storage *storage);
818 static std::unique_ptr<AbstractSqlMigrationWriter> getMigrationWriter(Storage *storage);
819 static void stdInEcho(bool on);
820 static inline void enableStdInEcho() { stdInEcho(true); }
821 static inline void disableStdInEcho() { stdInEcho(false); }