66fc50b01759a06e67fc9bec8f59388ada5be79c
[quassel.git] / src / core / core.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #ifndef CORE_H
22 #define CORE_H
23
24 #include <QDateTime>
25 #include <QString>
26 #include <QVariant>
27 #include <QTimer>
28
29 #ifdef HAVE_SSL
30 #  include <QSslSocket>
31 #  include "sslserver.h"
32 #else
33 #  include <QTcpSocket>
34 #  include <QTcpServer>
35 #endif
36
37 #include "authenticator.h"
38 #include "bufferinfo.h"
39 #include "message.h"
40 #include "oidentdconfiggenerator.h"
41 #include "sessionthread.h"
42 #include "storage.h"
43 #include "types.h"
44
45 class CoreAuthHandler;
46 class CoreSession;
47 struct NetworkInfo;
48 class SessionThread;
49 class SignalProxy;
50
51 class AbstractSqlMigrationReader;
52 class AbstractSqlMigrationWriter;
53
54 class Core : public QObject
55 {
56     Q_OBJECT
57
58 public:
59     static Core *instance();
60     static void destroy();
61
62     static void saveState();
63     static void restoreState();
64
65     /*** Storage access ***/
66     // These methods are threadsafe.
67
68     //! Validate user
69     /**
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
73      */
74     static inline UserId validateUser(const QString &userName, const QString &password) {
75         return instance()->_storage->validateUser(userName, password);
76     }
77
78     //! Authenticate user against auth backend
79     /**
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
83      */
84     static inline UserId authenticateUser(const QString &userName, const QString &password) {
85         return instance()->_authenticator->validateUser(userName, password);
86     }
87
88     //! Add a new user, exposed so auth providers can call this without being the storage.
89     /**
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
94      */
95     static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") {
96         return instance()->_storage->addUser(userName, password, authenticator);
97     }
98
99     //! Does a comparison test against the authenticator in the database and the authenticator currently in use for a UserID.
100     /**
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.
104      */
105     static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) {
106         return instance()->_storage->getUserAuthenticator(userid) == authenticator;
107     }
108
109     //! Change a user's password
110     /**
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
114      */
115     static bool changeUserPassword(UserId userId, const QString &password);
116
117     //! Check if we can change a user password.
118     /**
119      * \param userID     The user's ID
120      * \return true, if we can change their password, false otherwise
121      */
122     static bool canChangeUserPassword(UserId userId);
123
124     //! Store a user setting persistently
125     /**
126      * \param userId       The users Id
127      * \param settingName  The Name of the Setting
128      * \param data         The Value
129      */
130     static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
131     {
132         instance()->_storage->setUserSetting(userId, settingName, data);
133     }
134
135
136     //! Retrieve a persistent user setting
137     /**
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.
142      */
143     static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
144     {
145         return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
146     }
147
148
149     /* Identity handling */
150     static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
151     {
152         return instance()->_storage->createIdentity(user, identity);
153     }
154
155
156     static bool updateIdentity(UserId user, const CoreIdentity &identity)
157     {
158         return instance()->_storage->updateIdentity(user, identity);
159     }
160
161
162     static void removeIdentity(UserId user, IdentityId identityId)
163     {
164         instance()->_storage->removeIdentity(user, identityId);
165     }
166
167
168     static QList<CoreIdentity> identities(UserId user)
169     {
170         return instance()->_storage->identities(user);
171     }
172
173
174     //! Create a Network in the Storage and store it's Id in the given NetworkInfo
175     /** \note This method is thredsafe.
176      *
177      *  \param user        The core user
178      *  \param networkInfo a NetworkInfo definition to store the newly created ID in
179      *  \return true if successfull.
180      */
181     static bool createNetwork(UserId user, NetworkInfo &info);
182
183     //! Apply the changes to NetworkInfo info to the storage engine
184     /** \note This method is thredsafe.
185      *
186      *  \param user        The core user
187      *  \param networkInfo The Updated NetworkInfo
188      *  \return true if successfull.
189      */
190     static inline bool updateNetwork(UserId user, const NetworkInfo &info)
191     {
192         return instance()->_storage->updateNetwork(user, info);
193     }
194
195
196     //! Permanently remove a Network and all the data associated with it.
197     /** \note This method is thredsafe.
198      *
199      *  \param user        The core user
200      *  \param networkId   The network to delete
201      *  \return true if successfull.
202      */
203     static inline bool removeNetwork(UserId user, const NetworkId &networkId)
204     {
205         return instance()->_storage->removeNetwork(user, networkId);
206     }
207
208
209     //! Returns a list of all NetworkInfos for the given UserId user
210     /** \note This method is thredsafe.
211      *
212      *  \param user        The core user
213      *  \return QList<NetworkInfo>.
214      */
215     static inline QList<NetworkInfo> networks(UserId user)
216     {
217         return instance()->_storage->networks(user);
218     }
219
220
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.
224      *
225      *  \param user  The User Id in question
226      */
227     static inline QList<NetworkId> connectedNetworks(UserId user)
228     {
229         return instance()->_storage->connectedNetworks(user);
230     }
231
232
233     //! Update the connected state of a network
234     /** \note This method is threadsafe
235      *
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
239      */
240     static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
241     {
242         return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
243     }
244
245
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
249      *
250      *  \param user       The id of the networks owner
251      *  \param networkId  The Id of the network
252      */
253     static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
254     {
255         return instance()->_storage->persistentChannels(user, networkId);
256     }
257
258
259     //! Update the connected state of a channel
260     /** \note This method is threadsafe
261      *
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
266      */
267     static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
268     {
269         return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
270     }
271
272
273     //! Update the key of a channel
274     /** \note This method is threadsafe
275      *
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)
280      */
281     static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
282     {
283         return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
284     }
285
286
287     //! retrieve last known away message for session restore
288     /** \note This method is threadsafe
289      *
290      *  \param user       The Id of the networks owner
291      *  \param networkId  The Id of the network
292      */
293     static inline QString awayMessage(UserId user, NetworkId networkId)
294     {
295         return instance()->_storage->awayMessage(user, networkId);
296     }
297
298
299     //! Make away message persistent for session restore
300     /** \note This method is threadsafe
301      *
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
305      */
306     static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
307     {
308         return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
309     }
310
311
312     //! retrieve last known user mode for session restore
313     /** \note This method is threadsafe
314      *
315      *  \param user       The Id of the networks owner
316      *  \param networkId  The Id of the network
317      */
318     static inline QString userModes(UserId user, NetworkId networkId)
319     {
320         return instance()->_storage->userModes(user, networkId);
321     }
322
323
324     //! Make our user modes persistent for session restore
325     /** \note This method is threadsafe
326      *
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
330      */
331     static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
332     {
333         return instance()->_storage->setUserModes(user, networkId, userModes);
334     }
335
336
337     //! Get the unique BufferInfo for the given combination of network and buffername for a user.
338     /** \note This method is threadsafe.
339      *
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
346      */
347     static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
348     {
349         return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
350     }
351
352
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.
358      */
359     static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
360     {
361         return instance()->_storage->getBufferInfo(user, bufferId);
362     }
363
364
365     //! Store a Message in the storage backend and set it's unique Id.
366     /** \note This method is threadsafe.
367      *
368      *  \param message The message object to be stored
369      *  \return true on success
370      */
371     static inline bool storeMessage(Message &message)
372     {
373         return instance()->_storage->logMessage(message);
374     }
375
376
377     //! Store a list of Messages in the storage backend and set their unique Id.
378     /** \note This method is threadsafe.
379      *
380      *  \param messages The list message objects to be stored
381      *  \return true on success
382      */
383     static inline bool storeMessages(MessageList &messages)
384     {
385         return instance()->_storage->logMessages(messages);
386     }
387
388
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
395      */
396     static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
397     {
398         return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
399     }
400
401
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
407      */
408     static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
409     {
410         return instance()->_storage->requestAllMsgs(user, first, last, limit);
411     }
412
413
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.
417      *
418      *  \param user  The user whose buffers we request
419      *  \return A list of the BufferInfos for all buffers as requested
420      */
421     static inline QList<BufferInfo> requestBuffers(UserId user)
422     {
423         return instance()->_storage->requestBuffers(user);
424     }
425
426
427     //! Request a list of BufferIds for a given NetworkId
428     /** \note This method is threadsafe.
429      *
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
433      */
434     static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
435     {
436         return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
437     }
438
439
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.
443      *
444      *  \param user      The user who is the owner of the buffer
445      *  \param bufferId  The bufferId
446      *  \return true if successfull
447      */
448     static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
449     {
450         return instance()->_storage->removeBuffer(user, bufferId);
451     }
452
453
454     //! Rename a Buffer
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
460      */
461     static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
462     {
463         return instance()->_storage->renameBuffer(user, bufferId, newName);
464     }
465
466
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
473      */
474     static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
475     {
476         return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
477     }
478
479
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.
483      *
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
487      */
488     static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
489     {
490         return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
491     }
492
493
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.
497      *
498      * \param user      The Owner of the buffers
499      */
500     static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
501     {
502         return instance()->_storage->bufferLastSeenMsgIds(user);
503     }
504
505
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.
509      *
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
513      */
514     static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
515     {
516         return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
517     }
518
519
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.
523      *
524      * \param user      The Owner of the buffers
525      */
526     static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
527     {
528         return instance()->_storage->bufferMarkerLineMsgIds(user);
529     }
530
531
532     static inline QDateTime startTime() { return instance()->_startTime; }
533     static inline bool isConfigured() { return instance()->_configured; }
534     static bool sslSupported();
535
536     /**
537      * Reloads SSL certificates used for connection with clients
538      *
539      * @return True if certificates reloaded successfully, otherwise false.
540      */
541     static bool reloadCerts();
542
543     static QVariantList backendInfo();
544     static QVariantList authenticatorInfo();
545
546     /**
547      * Checks if a storage backend is the default storage backend. This
548      * hardcodes this information into the core (not the client).
549      *
550      * \param backend    The backend to check.
551      *
552      * @return True if storage backend is default, false otherwise.
553      */
554     static inline bool isStorageBackendDefault(const Storage *backend)
555     {
556         return (backend->displayName() == "SQLite") ? true : false;
557     }
558
559     static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
560
561     static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
562
563     inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
564
565     static const int AddClientEventId;
566
567 public slots:
568     //! Make storage data persistent
569     /** \note This method is threadsafe.
570      */
571     void syncStorage();
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);
574
575 signals:
576     //! Sent when a BufferInfo is updated in storage.
577     void bufferInfoUpdated(UserId user, const BufferInfo &info);
578
579     //! Relay from CoreSession::sessionState(). Used for internal connection only
580     void sessionState(const Protocol::SessionState &sessionState);
581
582 protected:
583     virtual void customEvent(QEvent *event);
584
585 private slots:
586     bool startListening();
587     void stopListening(const QString &msg = QString());
588     void incomingConnection();
589     void clientDisconnected();
590
591     bool initStorage(const QString &backend, const QVariantMap &settings, bool setup = false);
592     bool initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup = false);
593
594     void socketError(QAbstractSocket::SocketError err, const QString &errorString);
595     void setupClientSession(RemotePeer *, UserId);
596
597     bool changeUserPass(const QString &username);
598
599 private:
600     Core();
601     ~Core();
602     void init();
603     static Core *instanceptr;
604
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();
609
610     void registerStorageBackends();
611     bool registerStorageBackend(Storage *);
612     void unregisterStorageBackends();
613     void unregisterStorageBackend(Storage *);
614
615     void registerAuthenticators();
616     bool registerAuthenticator(Authenticator *);
617     void unregisterAuthenticators();
618     void unregisterAuthenticator(Authenticator *);
619
620     bool selectBackend(const QString &backend);
621     bool selectAuthenticator(const QString &backend);
622     bool createUser();
623
624     bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
625     void saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings);
626
627     QVariantMap promptForSettings(const Storage *storage);
628     QVariantMap promptForSettings(const Authenticator *authenticator);
629     QVariantMap promptForSettings(QStringList keys, QVariantMap defaults);
630
631 private:
632     QSet<CoreAuthHandler *> _connectingClients;
633     QHash<UserId, SessionThread *> _sessions;
634
635     // Have both a storage backend and an authenticator backend.
636     Storage *_storage;
637     Authenticator *_authenticator;
638     QTimer _storageSyncTimer;
639
640 #ifdef HAVE_SSL
641     SslServer _server, _v6server;
642 #else
643     QTcpServer _server, _v6server;
644 #endif
645
646     OidentdConfigGenerator *_oidentdConfigGenerator;
647
648     QHash<QString, Storage *> _storageBackends;
649     QHash<QString, Authenticator *> _authenticators;
650
651     QDateTime _startTime;
652
653     bool _configured;
654
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); }
660 };
661
662
663 #endif