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 //! Store a user setting persistently
119 * \param userId The users Id
120 * \param settingName The Name of the Setting
121 * \param data The Value
123 static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
125 instance()->_storage->setUserSetting(userId, settingName, data);
129 //! Retrieve a persistent user setting
131 * \param userId The users Id
132 * \param settingName The Name of the Setting
133 * \param defaultValue Value to return in case it's unset.
134 * \return the Value of the Setting or the default value if it is unset.
136 static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
138 return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
142 /* Identity handling */
143 static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
145 return instance()->_storage->createIdentity(user, identity);
149 static bool updateIdentity(UserId user, const CoreIdentity &identity)
151 return instance()->_storage->updateIdentity(user, identity);
155 static void removeIdentity(UserId user, IdentityId identityId)
157 instance()->_storage->removeIdentity(user, identityId);
161 static QList<CoreIdentity> identities(UserId user)
163 return instance()->_storage->identities(user);
167 //! Create a Network in the Storage and store it's Id in the given NetworkInfo
168 /** \note This method is thredsafe.
170 * \param user The core user
171 * \param networkInfo a NetworkInfo definition to store the newly created ID in
172 * \return true if successfull.
174 static bool createNetwork(UserId user, NetworkInfo &info);
176 //! Apply the changes to NetworkInfo info to the storage engine
177 /** \note This method is thredsafe.
179 * \param user The core user
180 * \param networkInfo The Updated NetworkInfo
181 * \return true if successfull.
183 static inline bool updateNetwork(UserId user, const NetworkInfo &info)
185 return instance()->_storage->updateNetwork(user, info);
189 //! Permanently remove a Network and all the data associated with it.
190 /** \note This method is thredsafe.
192 * \param user The core user
193 * \param networkId The network to delete
194 * \return true if successfull.
196 static inline bool removeNetwork(UserId user, const NetworkId &networkId)
198 return instance()->_storage->removeNetwork(user, networkId);
202 //! Returns a list of all NetworkInfos for the given UserId user
203 /** \note This method is thredsafe.
205 * \param user The core user
206 * \return QList<NetworkInfo>.
208 static inline QList<NetworkInfo> networks(UserId user)
210 return instance()->_storage->networks(user);
214 //! Get a list of Networks to restore
215 /** Return a list of networks the user was connected at the time of core shutdown
216 * \note This method is threadsafe.
218 * \param user The User Id in question
220 static inline QList<NetworkId> connectedNetworks(UserId user)
222 return instance()->_storage->connectedNetworks(user);
226 //! Update the connected state of a network
227 /** \note This method is threadsafe
229 * \param user The Id of the networks owner
230 * \param networkId The Id of the network
231 * \param isConnected whether the network is connected or not
233 static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
235 return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
239 //! Get a hash of channels with their channel keys for a given network
240 /** The keys are channel names and values are passwords (possibly empty)
241 * \note This method is threadsafe
243 * \param user The id of the networks owner
244 * \param networkId The Id of the network
246 static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
248 return instance()->_storage->persistentChannels(user, networkId);
252 //! Update the connected state of a channel
253 /** \note This method is threadsafe
255 * \param user The Id of the networks owner
256 * \param networkId The Id of the network
257 * \param channel The name of the channel
258 * \param isJoined whether the channel is connected or not
260 static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
262 return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
266 //! Update the key of a channel
267 /** \note This method is threadsafe
269 * \param user The Id of the networks owner
270 * \param networkId The Id of the network
271 * \param channel The name of the channel
272 * \param key The key of the channel (possibly empty)
274 static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
276 return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
280 //! retrieve last known away message for session restore
281 /** \note This method is threadsafe
283 * \param user The Id of the networks owner
284 * \param networkId The Id of the network
286 static inline QString awayMessage(UserId user, NetworkId networkId)
288 return instance()->_storage->awayMessage(user, networkId);
292 //! Make away message persistent for session restore
293 /** \note This method is threadsafe
295 * \param user The Id of the networks owner
296 * \param networkId The Id of the network
297 * \param awayMsg The current away message of own user
299 static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
301 return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
305 //! retrieve last known user mode for session restore
306 /** \note This method is threadsafe
308 * \param user The Id of the networks owner
309 * \param networkId The Id of the network
311 static inline QString userModes(UserId user, NetworkId networkId)
313 return instance()->_storage->userModes(user, networkId);
317 //! Make our user modes persistent for session restore
318 /** \note This method is threadsafe
320 * \param user The Id of the networks owner
321 * \param networkId The Id of the network
322 * \param userModes The current user modes of own user
324 static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
326 return instance()->_storage->setUserModes(user, networkId, userModes);
330 //! Get the unique BufferInfo for the given combination of network and buffername for a user.
331 /** \note This method is threadsafe.
333 * \param user The core user who owns this buffername
334 * \param networkId The network id
335 * \param type The type of the buffer (StatusBuffer, Channel, etc.)
336 * \param buffer The buffer name (if empty, the net's status buffer is returned)
337 * \param create Whether or not the buffer should be created if it doesnt exist
338 * \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
340 static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
342 return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
346 //! Get the unique BufferInfo for a bufferId
347 /** \note This method is threadsafe
348 * \param user The core user who owns this buffername
349 * \param bufferId The id of the buffer
350 * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
352 static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
354 return instance()->_storage->getBufferInfo(user, bufferId);
358 //! Store a Message in the storage backend and set it's unique Id.
359 /** \note This method is threadsafe.
361 * \param message The message object to be stored
362 * \return true on success
364 static inline bool storeMessage(Message &message)
366 return instance()->_storage->logMessage(message);
370 //! Store a list of Messages in the storage backend and set their unique Id.
371 /** \note This method is threadsafe.
373 * \param messages The list message objects to be stored
374 * \return true on success
376 static inline bool storeMessages(MessageList &messages)
378 return instance()->_storage->logMessages(messages);
382 //! Request a certain number messages stored in a given buffer.
383 /** \param buffer The buffer we request messages from
384 * \param first if != -1 return only messages with a MsgId >= first
385 * \param last if != -1 return only messages with a MsgId < last
386 * \param limit if != -1 limit the returned list to a max of \limit entries
387 * \return The requested list of messages
389 static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
391 return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
395 //! Request a certain number of messages across all buffers
396 /** \param first if != -1 return only messages with a MsgId >= first
397 * \param last if != -1 return only messages with a MsgId < last
398 * \param limit Max amount of messages
399 * \return The requested list of messages
401 static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
403 return instance()->_storage->requestAllMsgs(user, first, last, limit);
407 //! Request a list of all buffers known to a user.
408 /** This method is used to get a list of all buffers we have stored a backlog from.
409 * \note This method is threadsafe.
411 * \param user The user whose buffers we request
412 * \return A list of the BufferInfos for all buffers as requested
414 static inline QList<BufferInfo> requestBuffers(UserId user)
416 return instance()->_storage->requestBuffers(user);
420 //! Request a list of BufferIds for a given NetworkId
421 /** \note This method is threadsafe.
423 * \param user The user whose buffers we request
424 * \param networkId The NetworkId of the network in question
425 * \return List of BufferIds belonging to the Network
427 static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
429 return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
433 //! Remove permanently a buffer and it's content from the storage backend
434 /** This call cannot be reverted!
435 * \note This method is threadsafe.
437 * \param user The user who is the owner of the buffer
438 * \param bufferId The bufferId
439 * \return true if successfull
441 static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
443 return instance()->_storage->removeBuffer(user, bufferId);
448 /** \note This method is threadsafe.
449 * \param user The id of the buffer owner
450 * \param bufferId The bufferId
451 * \param newName The new name of the buffer
452 * \return true if successfull
454 static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
456 return instance()->_storage->renameBuffer(user, bufferId, newName);
460 //! Merge the content of two Buffers permanently. This cannot be reversed!
461 /** \note This method is threadsafe.
462 * \param user The id of the buffer owner
463 * \param bufferId1 The bufferId of the remaining buffer
464 * \param bufferId2 The buffer that is about to be removed
465 * \return true if successfulln
467 static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
469 return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
473 //! Update the LastSeenDate for a Buffer
474 /** This Method is used to make the LastSeenDate of a Buffer persistent
475 * \note This method is threadsafe.
477 * \param user The Owner of that Buffer
478 * \param bufferId The buffer id
479 * \param MsgId The Message id of the message that has been just seen
481 static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
483 return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
487 //! Get a Hash of all last seen message ids
488 /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
489 * \note This method is threadsafe.
491 * \param user The Owner of the buffers
493 static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
495 return instance()->_storage->bufferLastSeenMsgIds(user);
499 //! Update the MarkerLineMsgId for a Buffer
500 /** This Method is used to make the marker line position of a Buffer persistent
501 * \note This method is threadsafe.
503 * \param user The Owner of that Buffer
504 * \param bufferId The buffer id
505 * \param MsgId The Message id where the marker line should be placed
507 static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
509 return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
513 //! Get a Hash of all marker line message ids
514 /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
515 * \note This method is threadsafe.
517 * \param user The Owner of the buffers
519 static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
521 return instance()->_storage->bufferMarkerLineMsgIds(user);
525 static inline QDateTime startTime() { return instance()->_startTime; }
526 static inline bool isConfigured() { return instance()->_configured; }
527 static bool sslSupported();
530 * Reloads SSL certificates used for connection with clients
532 * @return True if certificates reloaded successfully, otherwise false.
534 static bool reloadCerts();
536 static QVariantList backendInfo();
537 static QVariantList authenticatorInfo();
540 * Checks if a storage backend is the default storage backend. This
541 * hardcodes this information into the core (not the client).
543 * \param backend The backend to check.
545 * @return True if storage backend is default, false otherwise.
547 static inline bool isStorageBackendDefault(const Storage *backend)
549 return (backend->displayName() == "SQLite") ? true : false;
552 static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupMap);
554 static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
556 inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
558 static const int AddClientEventId;
561 //! Make storage data persistent
562 /** \note This method is threadsafe.
565 void setupInternalClientSession(InternalPeer *clientConnection);
566 QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupMap);
569 //! Sent when a BufferInfo is updated in storage.
570 void bufferInfoUpdated(UserId user, const BufferInfo &info);
572 //! Relay from CoreSession::sessionState(). Used for internal connection only
573 void sessionState(const Protocol::SessionState &sessionState);
576 virtual void customEvent(QEvent *event);
579 bool startListening();
580 void stopListening(const QString &msg = QString());
581 void incomingConnection();
582 void clientDisconnected();
584 bool initStorage(const QString &backend, const QVariantMap &settings, bool setup = false);
585 bool initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup = false);
587 void socketError(QAbstractSocket::SocketError err, const QString &errorString);
588 void setupClientSession(RemotePeer *, UserId);
590 bool changeUserPass(const QString &username);
596 static Core *instanceptr;
598 SessionThread *sessionForUser(UserId userId, bool restoreState = false);
599 void addClientHelper(RemotePeer *peer, UserId uid);
600 //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
601 QString setupCoreForInternalUsage();
603 void registerStorageBackends();
604 bool registerStorageBackend(Storage *);
605 void unregisterStorageBackends();
606 void unregisterStorageBackend(Storage *);
608 void registerAuthenticatorBackends();
609 bool registerAuthenticatorBackend(Authenticator *);
610 void unregisterAuthenticatorBackends();
611 void unregisterAuthenticatorBackend(Authenticator *);
613 bool selectBackend(const QString &backend);
615 bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
616 void saveAuthBackendSettings(const QString &backend, const QVariantMap &settings);
617 QVariantMap promptForSettings(const Storage *storage);
620 QSet<CoreAuthHandler *> _connectingClients;
621 QHash<UserId, SessionThread *> _sessions;
623 // Have both a storage backend and an authenticator backend.
625 Authenticator *_authenticator;
626 QTimer _storageSyncTimer;
629 SslServer _server, _v6server;
631 QTcpServer _server, _v6server;
634 OidentdConfigGenerator *_oidentdConfigGenerator;
636 QHash<QString, Storage *> _storageBackends;
637 QHash<QString, Authenticator *> _authenticatorBackends;
639 QDateTime _startTime;
643 static AbstractSqlMigrationReader *getMigrationReader(Storage *storage);
644 static AbstractSqlMigrationWriter *getMigrationWriter(Storage *storage);
645 static void stdInEcho(bool on);
646 static inline void enableStdInEcho() { stdInEcho(true); }
647 static inline void disableStdInEcho() { stdInEcho(false); }