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 //! Change a user's password
90 * \param userId The user's ID
91 * \param password The user's unencrypted new password
92 * \return true, if the password change was successful
94 static bool changeUserPassword(UserId userId, const QString &password);
96 //! Store a user setting persistently
98 * \param userId The users Id
99 * \param settingName The Name of the Setting
100 * \param data The Value
102 static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
104 instance()->_storage->setUserSetting(userId, settingName, data);
108 //! Retrieve a persistent user setting
110 * \param userId The users Id
111 * \param settingName The Name of the Setting
112 * \param defaultValue Value to return in case it's unset.
113 * \return the Value of the Setting or the default value if it is unset.
115 static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
117 return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
121 /* Identity handling */
122 static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
124 return instance()->_storage->createIdentity(user, identity);
128 static bool updateIdentity(UserId user, const CoreIdentity &identity)
130 return instance()->_storage->updateIdentity(user, identity);
134 static void removeIdentity(UserId user, IdentityId identityId)
136 instance()->_storage->removeIdentity(user, identityId);
140 static QList<CoreIdentity> identities(UserId user)
142 return instance()->_storage->identities(user);
146 //! Create a Network in the Storage and store it's Id in the given NetworkInfo
147 /** \note This method is thredsafe.
149 * \param user The core user
150 * \param networkInfo a NetworkInfo definition to store the newly created ID in
151 * \return true if successfull.
153 static bool createNetwork(UserId user, NetworkInfo &info);
155 //! Apply the changes to NetworkInfo info to the storage engine
156 /** \note This method is thredsafe.
158 * \param user The core user
159 * \param networkInfo The Updated NetworkInfo
160 * \return true if successfull.
162 static inline bool updateNetwork(UserId user, const NetworkInfo &info)
164 return instance()->_storage->updateNetwork(user, info);
168 //! Permanently remove a Network and all the data associated with it.
169 /** \note This method is thredsafe.
171 * \param user The core user
172 * \param networkId The network to delete
173 * \return true if successfull.
175 static inline bool removeNetwork(UserId user, const NetworkId &networkId)
177 return instance()->_storage->removeNetwork(user, networkId);
181 //! Returns a list of all NetworkInfos for the given UserId user
182 /** \note This method is thredsafe.
184 * \param user The core user
185 * \return QList<NetworkInfo>.
187 static inline QList<NetworkInfo> networks(UserId user)
189 return instance()->_storage->networks(user);
193 //! Get a list of Networks to restore
194 /** Return a list of networks the user was connected at the time of core shutdown
195 * \note This method is threadsafe.
197 * \param user The User Id in question
199 static inline QList<NetworkId> connectedNetworks(UserId user)
201 return instance()->_storage->connectedNetworks(user);
205 //! Update the connected state of a network
206 /** \note This method is threadsafe
208 * \param user The Id of the networks owner
209 * \param networkId The Id of the network
210 * \param isConnected whether the network is connected or not
212 static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
214 return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
218 //! Get a hash of channels with their channel keys for a given network
219 /** The keys are channel names and values are passwords (possibly empty)
220 * \note This method is threadsafe
222 * \param user The id of the networks owner
223 * \param networkId The Id of the network
225 static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
227 return instance()->_storage->persistentChannels(user, networkId);
231 //! Update the connected state of a channel
232 /** \note This method is threadsafe
234 * \param user The Id of the networks owner
235 * \param networkId The Id of the network
236 * \param channel The name of the channel
237 * \param isJoined whether the channel is connected or not
239 static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
241 return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
245 //! Update the key of a channel
246 /** \note This method is threadsafe
248 * \param user The Id of the networks owner
249 * \param networkId The Id of the network
250 * \param channel The name of the channel
251 * \param key The key of the channel (possibly empty)
253 static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
255 return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
259 //! retrieve last known away message for session restore
260 /** \note This method is threadsafe
262 * \param user The Id of the networks owner
263 * \param networkId The Id of the network
265 static inline QString awayMessage(UserId user, NetworkId networkId)
267 return instance()->_storage->awayMessage(user, networkId);
271 //! Make away message persistent for session restore
272 /** \note This method is threadsafe
274 * \param user The Id of the networks owner
275 * \param networkId The Id of the network
276 * \param awayMsg The current away message of own user
278 static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
280 return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
284 //! retrieve last known user mode for session restore
285 /** \note This method is threadsafe
287 * \param user The Id of the networks owner
288 * \param networkId The Id of the network
290 static inline QString userModes(UserId user, NetworkId networkId)
292 return instance()->_storage->userModes(user, networkId);
296 //! Make our user modes persistent for session restore
297 /** \note This method is threadsafe
299 * \param user The Id of the networks owner
300 * \param networkId The Id of the network
301 * \param userModes The current user modes of own user
303 static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
305 return instance()->_storage->setUserModes(user, networkId, userModes);
309 //! Get the unique BufferInfo for the given combination of network and buffername for a user.
310 /** \note This method is threadsafe.
312 * \param user The core user who owns this buffername
313 * \param networkId The network id
314 * \param type The type of the buffer (StatusBuffer, Channel, etc.)
315 * \param buffer The buffer name (if empty, the net's status buffer is returned)
316 * \param create Whether or not the buffer should be created if it doesnt exist
317 * \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
319 static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
321 return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
325 //! Get the unique BufferInfo for a bufferId
326 /** \note This method is threadsafe
327 * \param user The core user who owns this buffername
328 * \param bufferId The id of the buffer
329 * \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
331 static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
333 return instance()->_storage->getBufferInfo(user, bufferId);
337 //! Store a Message in the storage backend and set it's unique Id.
338 /** \note This method is threadsafe.
340 * \param message The message object to be stored
341 * \return true on success
343 static inline bool storeMessage(Message &message)
345 return instance()->_storage->logMessage(message);
349 //! Store a list of Messages in the storage backend and set their unique Id.
350 /** \note This method is threadsafe.
352 * \param messages The list message objects to be stored
353 * \return true on success
355 static inline bool storeMessages(MessageList &messages)
357 return instance()->_storage->logMessages(messages);
361 //! Request a certain number messages stored in a given buffer.
362 /** \param buffer The buffer we request messages from
363 * \param first if != -1 return only messages with a MsgId >= first
364 * \param last if != -1 return only messages with a MsgId < last
365 * \param limit if != -1 limit the returned list to a max of \limit entries
366 * \return The requested list of messages
368 static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
370 return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
374 //! Request a certain number of messages across all buffers
375 /** \param first if != -1 return only messages with a MsgId >= first
376 * \param last if != -1 return only messages with a MsgId < last
377 * \param limit Max amount of messages
378 * \return The requested list of messages
380 static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
382 return instance()->_storage->requestAllMsgs(user, first, last, limit);
386 //! Request a list of all buffers known to a user.
387 /** This method is used to get a list of all buffers we have stored a backlog from.
388 * \note This method is threadsafe.
390 * \param user The user whose buffers we request
391 * \return A list of the BufferInfos for all buffers as requested
393 static inline QList<BufferInfo> requestBuffers(UserId user)
395 return instance()->_storage->requestBuffers(user);
399 //! Request a list of BufferIds for a given NetworkId
400 /** \note This method is threadsafe.
402 * \param user The user whose buffers we request
403 * \param networkId The NetworkId of the network in question
404 * \return List of BufferIds belonging to the Network
406 static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
408 return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
412 //! Remove permanently a buffer and it's content from the storage backend
413 /** This call cannot be reverted!
414 * \note This method is threadsafe.
416 * \param user The user who is the owner of the buffer
417 * \param bufferId The bufferId
418 * \return true if successfull
420 static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
422 return instance()->_storage->removeBuffer(user, bufferId);
427 /** \note This method is threadsafe.
428 * \param user The id of the buffer owner
429 * \param bufferId The bufferId
430 * \param newName The new name of the buffer
431 * \return true if successfull
433 static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
435 return instance()->_storage->renameBuffer(user, bufferId, newName);
439 //! Merge the content of two Buffers permanently. This cannot be reversed!
440 /** \note This method is threadsafe.
441 * \param user The id of the buffer owner
442 * \param bufferId1 The bufferId of the remaining buffer
443 * \param bufferId2 The buffer that is about to be removed
444 * \return true if successfulln
446 static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
448 return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
452 //! Update the LastSeenDate for a Buffer
453 /** This Method is used to make the LastSeenDate of a Buffer persistent
454 * \note This method is threadsafe.
456 * \param user The Owner of that Buffer
457 * \param bufferId The buffer id
458 * \param MsgId The Message id of the message that has been just seen
460 static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
462 return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
466 //! Get a Hash of all last seen message ids
467 /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
468 * \note This method is threadsafe.
470 * \param user The Owner of the buffers
472 static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
474 return instance()->_storage->bufferLastSeenMsgIds(user);
478 //! Update the MarkerLineMsgId for a Buffer
479 /** This Method is used to make the marker line position of a Buffer persistent
480 * \note This method is threadsafe.
482 * \param user The Owner of that Buffer
483 * \param bufferId The buffer id
484 * \param MsgId The Message id where the marker line should be placed
486 static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
488 return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
492 //! Get a Hash of all marker line message ids
493 /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
494 * \note This method is threadsafe.
496 * \param user The Owner of the buffers
498 static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
500 return instance()->_storage->bufferMarkerLineMsgIds(user);
504 static inline QDateTime startTime() { return instance()->_startTime; }
505 static inline bool isConfigured() { return instance()->_configured; }
506 static bool sslSupported();
509 * Reloads SSL certificates used for connection with clients
511 * @return True if certificates reloaded successfully, otherwise false.
513 static bool reloadCerts();
515 static QVariantList backendInfo();
516 static QVariantList authenticatorInfo();
519 * Checks if a storage backend is the default storage backend. This
520 * hardcodes this information into the core (not the client).
522 * \param backend The backend to check.
524 * @return True if storage backend is default, false otherwise.
526 static inline bool isStorageBackendDefault(const Storage *backend)
528 return (backend->displayName() == "SQLite") ? true : false;
531 static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupMap);
533 static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
535 inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
537 static const int AddClientEventId;
540 //! Make storage data persistent
541 /** \note This method is threadsafe.
544 void setupInternalClientSession(InternalPeer *clientConnection);
545 QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupMap);
548 //! Sent when a BufferInfo is updated in storage.
549 void bufferInfoUpdated(UserId user, const BufferInfo &info);
551 //! Relay from CoreSession::sessionState(). Used for internal connection only
552 void sessionState(const Protocol::SessionState &sessionState);
555 virtual void customEvent(QEvent *event);
558 bool startListening();
559 void stopListening(const QString &msg = QString());
560 void incomingConnection();
561 void clientDisconnected();
563 bool initStorage(const QString &backend, const QVariantMap &settings, bool setup = false);
564 bool initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup = false);
566 void socketError(QAbstractSocket::SocketError err, const QString &errorString);
567 void setupClientSession(RemotePeer *, UserId);
569 bool changeUserPass(const QString &username);
575 static Core *instanceptr;
577 SessionThread *sessionForUser(UserId userId, bool restoreState = false);
578 void addClientHelper(RemotePeer *peer, UserId uid);
579 //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
580 QString setupCoreForInternalUsage();
582 void registerStorageBackends();
583 bool registerStorageBackend(Storage *);
584 void unregisterStorageBackends();
585 void unregisterStorageBackend(Storage *);
587 void registerAuthenticatorBackends();
588 bool registerAuthenticatorBackend(Authenticator *);
589 void unregisterAuthenticatorBackends();
590 void unregisterAuthenticatorBackend(Authenticator *);
592 bool selectBackend(const QString &backend);
594 bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
595 void saveAuthBackendSettings(const QString &backend, const QVariantMap &settings);
596 QVariantMap promptForSettings(const Storage *storage);
599 QSet<CoreAuthHandler *> _connectingClients;
600 QHash<UserId, SessionThread *> _sessions;
602 // Have both a storage backend and an authenticator backend.
604 Authenticator *_authenticator;
605 QTimer _storageSyncTimer;
608 SslServer _server, _v6server;
610 QTcpServer _server, _v6server;
613 OidentdConfigGenerator *_oidentdConfigGenerator;
615 QHash<QString, Storage *> _storageBackends;
616 QHash<QString, Authenticator *> _authenticatorBackends;
618 QDateTime _startTime;
622 static AbstractSqlMigrationReader *getMigrationReader(Storage *storage);
623 static AbstractSqlMigrationWriter *getMigrationWriter(Storage *storage);
624 static void stdInEcho(bool on);
625 static inline void enableStdInEcho() { stdInEcho(true); }
626 static inline void disableStdInEcho() { stdInEcho(false); }