1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 ***************************************************************************/
30 # include <QSslSocket>
31 # include "sslserver.h"
33 # include <QTcpSocket>
34 # include <QTcpServer>
37 #include "authenticator.h"
38 #include "bufferinfo.h"
40 #include "oidentdconfiggenerator.h"
41 #include "sessionthread.h"
45 class CoreAuthHandler;
51 class AbstractSqlMigrationReader;
52 class AbstractSqlMigrationWriter;
54 class Core : public QObject
59 static Core *instance();
60 static void destroy();
62 static void saveState();
63 static void restoreState();
65 /*** Storage access ***/
66 // These methods are threadsafe.
70 * \param userName The user's login name
71 * \param password The user's uncrypted password
72 * \return The user's ID if valid; 0 otherwise
74 static inline UserId validateUser(const QString &userName, const QString &password) {
75 return instance()->_storage->validateUser(userName, password);
78 //! Authenticate user against auth backend
80 * \param userName The user's login name
81 * \param password The user's uncrypted password
82 * \return The user's ID if valid; 0 otherwise
84 static inline UserId authenticateUser(const QString &userName, const QString &password) {
85 return instance()->_authenticator->validateUser(userName, password);
88 //! Add a new user, exposed so auth providers can call this without being the storage.
90 * \param userName The user's login name
91 * \param password The user's uncrypted password
92 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
93 * \return The user's ID if valid; 0 otherwise
95 static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") {
96 return instance()->_storage->addUser(userName, password, authenticator);
99 //! Does a comparison test against the authenticator in the database and the authenticator currently in use for a UserID.
101 * \param userid The user's ID (note: not login name).
102 * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
103 * \return True if the userid was configured with the passed authenticator, false otherwise.
105 static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) {
106 return instance()->_storage->getUserAuthenticator(userid) == authenticator;
109 //! Change a user's password
111 * \param userId The user's ID
112 * \param password The user's unencrypted new password
113 * \return true, if the password change was successful
115 static bool changeUserPassword(UserId userId, const QString &password);
117 //! Check if we can change a user password.
119 * \param userID The user's ID
120 * \return true, if we can change their password, false otherwise
122 static bool canChangeUserPassword(UserId userId);
124 //! Store a user setting persistently
126 * \param userId The users Id
127 * \param settingName The Name of the Setting
128 * \param data The Value
130 static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
132 instance()->_storage->setUserSetting(userId, settingName, data);
136 //! Retrieve a persistent user setting
138 * \param userId The users Id
139 * \param settingName The Name of the Setting
140 * \param defaultValue Value to return in case it's unset.
141 * \return the Value of the Setting or the default value if it is unset.
143 static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
145 return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
149 /* Identity handling */
150 static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
152 return instance()->_storage->createIdentity(user, identity);
156 static bool updateIdentity(UserId user, const CoreIdentity &identity)
158 return instance()->_storage->updateIdentity(user, identity);
162 static void removeIdentity(UserId user, IdentityId identityId)
164 instance()->_storage->removeIdentity(user, identityId);
168 static QList<CoreIdentity> identities(UserId user)
170 return instance()->_storage->identities(user);
174 //! Create a Network in the Storage and store it's Id in the given NetworkInfo
175 /** \note This method is thredsafe.
177 * \param user The core user
178 * \param networkInfo a NetworkInfo definition to store the newly created ID in
179 * \return true if successfull.
181 static bool createNetwork(UserId user, NetworkInfo &info);
183 //! Apply the changes to NetworkInfo info to the storage engine
184 /** \note This method is thredsafe.
186 * \param user The core user
187 * \param networkInfo The Updated NetworkInfo
188 * \return true if successfull.
190 static inline bool updateNetwork(UserId user, const NetworkInfo &info)
192 return instance()->_storage->updateNetwork(user, info);
196 //! Permanently remove a Network and all the data associated with it.
197 /** \note This method is thredsafe.
199 * \param user The core user
200 * \param networkId The network to delete
201 * \return true if successfull.
203 static inline bool removeNetwork(UserId user, const NetworkId &networkId)
205 return instance()->_storage->removeNetwork(user, networkId);
209 //! Returns a list of all NetworkInfos for the given UserId user
210 /** \note This method is thredsafe.
212 * \param user The core user
213 * \return QList<NetworkInfo>.
215 static inline QList<NetworkInfo> networks(UserId user)
217 return instance()->_storage->networks(user);
221 //! Get a list of Networks to restore
222 /** Return a list of networks the user was connected at the time of core shutdown
223 * \note This method is threadsafe.
225 * \param user The User Id in question
227 static inline QList<NetworkId> connectedNetworks(UserId user)
229 return instance()->_storage->connectedNetworks(user);
233 //! Update the connected state of a network
234 /** \note This method is threadsafe
236 * \param user The Id of the networks owner
237 * \param networkId The Id of the network
238 * \param isConnected whether the network is connected or not
240 static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
242 return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
246 //! Get a hash of channels with their channel keys for a given network
247 /** The keys are channel names and values are passwords (possibly empty)
248 * \note This method is threadsafe
250 * \param user The id of the networks owner
251 * \param networkId The Id of the network
253 static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
255 return instance()->_storage->persistentChannels(user, networkId);
259 //! Update the connected state of a channel
260 /** \note This method is threadsafe
262 * \param user The Id of the networks owner
263 * \param networkId The Id of the network
264 * \param channel The name of the channel
265 * \param isJoined whether the channel is connected or not
267 static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
269 return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
273 //! Update the key of a channel
274 /** \note This method is threadsafe
276 * \param user The Id of the networks owner
277 * \param networkId The Id of the network
278 * \param channel The name of the channel
279 * \param key The key of the channel (possibly empty)
281 static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
283 return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
287 //! retrieve last known away message for session restore
288 /** \note This method is threadsafe
290 * \param user The Id of the networks owner
291 * \param networkId The Id of the network
293 static inline QString awayMessage(UserId user, NetworkId networkId)
295 return instance()->_storage->awayMessage(user, networkId);
299 //! Make away message persistent for session restore
300 /** \note This method is threadsafe
302 * \param user The Id of the networks owner
303 * \param networkId The Id of the network
304 * \param awayMsg The current away message of own user
306 static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
308 return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
312 //! retrieve last known user mode for session restore
313 /** \note This method is threadsafe
315 * \param user The Id of the networks owner
316 * \param networkId The Id of the network
318 static inline QString userModes(UserId user, NetworkId networkId)
320 return instance()->_storage->userModes(user, networkId);
324 //! Make our user modes persistent for session restore
325 /** \note This method is threadsafe
327 * \param user The Id of the networks owner
328 * \param networkId The Id of the network
329 * \param userModes The current user modes of own user
331 static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
333 return instance()->_storage->setUserModes(user, networkId, userModes);
337 //! Get the unique BufferInfo for the given combination of network and buffername for a user.
338 /** \note This method is threadsafe.
340 * \param user The core user who owns this buffername
341 * \param networkId The network id
342 * \param type The type of the buffer (StatusBuffer, Channel, etc.)
343 * \param buffer The buffer name (if empty, the net's status buffer is returned)
344 * \param create Whether or not the buffer should be created if it doesnt exist
345 * \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
347 static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
349 return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
353 //! Get the unique BufferInfo for a bufferId
354 /** \note This method is threadsafe
355 * \param user The core user who owns this buffername
356 * \param bufferId The id of the buffer
357 * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
359 static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
361 return instance()->_storage->getBufferInfo(user, bufferId);
365 //! Store a Message in the storage backend and set it's unique Id.
366 /** \note This method is threadsafe.
368 * \param message The message object to be stored
369 * \return true on success
371 static inline bool storeMessage(Message &message)
373 return instance()->_storage->logMessage(message);
377 //! Store a list of Messages in the storage backend and set their unique Id.
378 /** \note This method is threadsafe.
380 * \param messages The list message objects to be stored
381 * \return true on success
383 static inline bool storeMessages(MessageList &messages)
385 return instance()->_storage->logMessages(messages);
389 //! Request a certain number messages stored in a given buffer.
390 /** \param buffer The buffer we request messages from
391 * \param first if != -1 return only messages with a MsgId >= first
392 * \param last if != -1 return only messages with a MsgId < last
393 * \param limit if != -1 limit the returned list to a max of \limit entries
394 * \return The requested list of messages
396 static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
398 return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
402 //! Request a certain number of messages across all buffers
403 /** \param first if != -1 return only messages with a MsgId >= first
404 * \param last if != -1 return only messages with a MsgId < last
405 * \param limit Max amount of messages
406 * \return The requested list of messages
408 static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
410 return instance()->_storage->requestAllMsgs(user, first, last, limit);
414 //! Request a list of all buffers known to a user.
415 /** This method is used to get a list of all buffers we have stored a backlog from.
416 * \note This method is threadsafe.
418 * \param user The user whose buffers we request
419 * \return A list of the BufferInfos for all buffers as requested
421 static inline QList<BufferInfo> requestBuffers(UserId user)
423 return instance()->_storage->requestBuffers(user);
427 //! Request a list of BufferIds for a given NetworkId
428 /** \note This method is threadsafe.
430 * \param user The user whose buffers we request
431 * \param networkId The NetworkId of the network in question
432 * \return List of BufferIds belonging to the Network
434 static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
436 return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
440 //! Remove permanently a buffer and it's content from the storage backend
441 /** This call cannot be reverted!
442 * \note This method is threadsafe.
444 * \param user The user who is the owner of the buffer
445 * \param bufferId The bufferId
446 * \return true if successfull
448 static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
450 return instance()->_storage->removeBuffer(user, bufferId);
455 /** \note This method is threadsafe.
456 * \param user The id of the buffer owner
457 * \param bufferId The bufferId
458 * \param newName The new name of the buffer
459 * \return true if successfull
461 static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
463 return instance()->_storage->renameBuffer(user, bufferId, newName);
467 //! Merge the content of two Buffers permanently. This cannot be reversed!
468 /** \note This method is threadsafe.
469 * \param user The id of the buffer owner
470 * \param bufferId1 The bufferId of the remaining buffer
471 * \param bufferId2 The buffer that is about to be removed
472 * \return true if successfulln
474 static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
476 return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
480 //! Update the LastSeenDate for a Buffer
481 /** This Method is used to make the LastSeenDate of a Buffer persistent
482 * \note This method is threadsafe.
484 * \param user The Owner of that Buffer
485 * \param bufferId The buffer id
486 * \param MsgId The Message id of the message that has been just seen
488 static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
490 return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
494 //! Get a Hash of all last seen message ids
495 /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
496 * \note This method is threadsafe.
498 * \param user The Owner of the buffers
500 static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
502 return instance()->_storage->bufferLastSeenMsgIds(user);
506 //! Update the MarkerLineMsgId for a Buffer
507 /** This Method is used to make the marker line position of a Buffer persistent
508 * \note This method is threadsafe.
510 * \param user The Owner of that Buffer
511 * \param bufferId The buffer id
512 * \param MsgId The Message id where the marker line should be placed
514 static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
516 return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
520 //! Get a Hash of all marker line message ids
521 /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
522 * \note This method is threadsafe.
524 * \param user The Owner of the buffers
526 static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
528 return instance()->_storage->bufferMarkerLineMsgIds(user);
532 static inline QDateTime startTime() { return instance()->_startTime; }
533 static inline bool isConfigured() { return instance()->_configured; }
534 static bool sslSupported();
537 * Reloads SSL certificates used for connection with clients
539 * @return True if certificates reloaded successfully, otherwise false.
541 static bool reloadCerts();
543 static QVariantList backendInfo();
544 static QVariantList authenticatorInfo();
547 * Checks if a storage backend is the default storage backend. This
548 * hardcodes this information into the core (not the client).
550 * \param backend The backend to check.
552 * @return True if storage backend is default, false otherwise.
554 static inline bool isStorageBackendDefault(const Storage *backend)
556 return (backend->displayName() == "SQLite") ? true : false;
559 static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
561 static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
563 inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
565 static const int AddClientEventId;
568 //! Make storage data persistent
569 /** \note This method is threadsafe.
572 void setupInternalClientSession(InternalPeer *clientConnection);
573 QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
576 //! Sent when a BufferInfo is updated in storage.
577 void bufferInfoUpdated(UserId user, const BufferInfo &info);
579 //! Relay from CoreSession::sessionState(). Used for internal connection only
580 void sessionState(const Protocol::SessionState &sessionState);
583 virtual void customEvent(QEvent *event);
586 bool startListening();
587 void stopListening(const QString &msg = QString());
588 void incomingConnection();
589 void clientDisconnected();
591 bool initStorage(const QString &backend, const QVariantMap &settings, bool setup = false);
592 bool initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup = false);
594 void socketError(QAbstractSocket::SocketError err, const QString &errorString);
595 void setupClientSession(RemotePeer *, UserId);
597 bool changeUserPass(const QString &username);
603 static Core *instanceptr;
605 SessionThread *sessionForUser(UserId userId, bool restoreState = false);
606 void addClientHelper(RemotePeer *peer, UserId uid);
607 //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
608 QString setupCoreForInternalUsage();
610 void registerStorageBackends();
611 bool registerStorageBackend(Storage *);
612 void unregisterStorageBackends();
613 void unregisterStorageBackend(Storage *);
615 void registerAuthenticators();
616 bool registerAuthenticator(Authenticator *);
617 void unregisterAuthenticators();
618 void unregisterAuthenticator(Authenticator *);
620 bool selectBackend(const QString &backend);
621 bool selectAuthenticator(const QString &backend);
624 bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
625 void saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings);
627 QVariantMap promptForSettings(const Storage *storage);
628 QVariantMap promptForSettings(const Authenticator *authenticator);
629 QVariantMap promptForSettings(QStringList keys, QVariantMap defaults);
632 QSet<CoreAuthHandler *> _connectingClients;
633 QHash<UserId, SessionThread *> _sessions;
635 // Have both a storage backend and an authenticator backend.
637 Authenticator *_authenticator;
638 QTimer _storageSyncTimer;
641 SslServer _server, _v6server;
643 QTcpServer _server, _v6server;
646 OidentdConfigGenerator *_oidentdConfigGenerator;
648 QHash<QString, Storage *> _storageBackends;
649 QHash<QString, Authenticator *> _authenticators;
651 QDateTime _startTime;
655 static AbstractSqlMigrationReader *getMigrationReader(Storage *storage);
656 static AbstractSqlMigrationWriter *getMigrationWriter(Storage *storage);
657 static void stdInEcho(bool on);
658 static inline void enableStdInEcho() { stdInEcho(true); }
659 static inline void disableStdInEcho() { stdInEcho(false); }