Add authenticator column to quasseluser table
[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     //! Store a user setting persistently
118     /**
119      * \param userId       The users Id
120      * \param settingName  The Name of the Setting
121      * \param data         The Value
122      */
123     static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
124     {
125         instance()->_storage->setUserSetting(userId, settingName, data);
126     }
127
128
129     //! Retrieve a persistent user setting
130     /**
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.
135      */
136     static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
137     {
138         return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
139     }
140
141
142     /* Identity handling */
143     static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
144     {
145         return instance()->_storage->createIdentity(user, identity);
146     }
147
148
149     static bool updateIdentity(UserId user, const CoreIdentity &identity)
150     {
151         return instance()->_storage->updateIdentity(user, identity);
152     }
153
154
155     static void removeIdentity(UserId user, IdentityId identityId)
156     {
157         instance()->_storage->removeIdentity(user, identityId);
158     }
159
160
161     static QList<CoreIdentity> identities(UserId user)
162     {
163         return instance()->_storage->identities(user);
164     }
165
166
167     //! Create a Network in the Storage and store it's Id in the given NetworkInfo
168     /** \note This method is thredsafe.
169      *
170      *  \param user        The core user
171      *  \param networkInfo a NetworkInfo definition to store the newly created ID in
172      *  \return true if successfull.
173      */
174     static bool createNetwork(UserId user, NetworkInfo &info);
175
176     //! Apply the changes to NetworkInfo info to the storage engine
177     /** \note This method is thredsafe.
178      *
179      *  \param user        The core user
180      *  \param networkInfo The Updated NetworkInfo
181      *  \return true if successfull.
182      */
183     static inline bool updateNetwork(UserId user, const NetworkInfo &info)
184     {
185         return instance()->_storage->updateNetwork(user, info);
186     }
187
188
189     //! Permanently remove a Network and all the data associated with it.
190     /** \note This method is thredsafe.
191      *
192      *  \param user        The core user
193      *  \param networkId   The network to delete
194      *  \return true if successfull.
195      */
196     static inline bool removeNetwork(UserId user, const NetworkId &networkId)
197     {
198         return instance()->_storage->removeNetwork(user, networkId);
199     }
200
201
202     //! Returns a list of all NetworkInfos for the given UserId user
203     /** \note This method is thredsafe.
204      *
205      *  \param user        The core user
206      *  \return QList<NetworkInfo>.
207      */
208     static inline QList<NetworkInfo> networks(UserId user)
209     {
210         return instance()->_storage->networks(user);
211     }
212
213
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.
217      *
218      *  \param user  The User Id in question
219      */
220     static inline QList<NetworkId> connectedNetworks(UserId user)
221     {
222         return instance()->_storage->connectedNetworks(user);
223     }
224
225
226     //! Update the connected state of a network
227     /** \note This method is threadsafe
228      *
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
232      */
233     static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
234     {
235         return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
236     }
237
238
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
242      *
243      *  \param user       The id of the networks owner
244      *  \param networkId  The Id of the network
245      */
246     static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
247     {
248         return instance()->_storage->persistentChannels(user, networkId);
249     }
250
251
252     //! Update the connected state of a channel
253     /** \note This method is threadsafe
254      *
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
259      */
260     static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
261     {
262         return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
263     }
264
265
266     //! Update the key of a channel
267     /** \note This method is threadsafe
268      *
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)
273      */
274     static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
275     {
276         return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
277     }
278
279
280     //! retrieve last known away message for session restore
281     /** \note This method is threadsafe
282      *
283      *  \param user       The Id of the networks owner
284      *  \param networkId  The Id of the network
285      */
286     static inline QString awayMessage(UserId user, NetworkId networkId)
287     {
288         return instance()->_storage->awayMessage(user, networkId);
289     }
290
291
292     //! Make away message persistent for session restore
293     /** \note This method is threadsafe
294      *
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
298      */
299     static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
300     {
301         return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
302     }
303
304
305     //! retrieve last known user mode for session restore
306     /** \note This method is threadsafe
307      *
308      *  \param user       The Id of the networks owner
309      *  \param networkId  The Id of the network
310      */
311     static inline QString userModes(UserId user, NetworkId networkId)
312     {
313         return instance()->_storage->userModes(user, networkId);
314     }
315
316
317     //! Make our user modes persistent for session restore
318     /** \note This method is threadsafe
319      *
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
323      */
324     static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
325     {
326         return instance()->_storage->setUserModes(user, networkId, userModes);
327     }
328
329
330     //! Get the unique BufferInfo for the given combination of network and buffername for a user.
331     /** \note This method is threadsafe.
332      *
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
339      */
340     static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
341     {
342         return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
343     }
344
345
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.
351      */
352     static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
353     {
354         return instance()->_storage->getBufferInfo(user, bufferId);
355     }
356
357
358     //! Store a Message in the storage backend and set it's unique Id.
359     /** \note This method is threadsafe.
360      *
361      *  \param message The message object to be stored
362      *  \return true on success
363      */
364     static inline bool storeMessage(Message &message)
365     {
366         return instance()->_storage->logMessage(message);
367     }
368
369
370     //! Store a list of Messages in the storage backend and set their unique Id.
371     /** \note This method is threadsafe.
372      *
373      *  \param messages The list message objects to be stored
374      *  \return true on success
375      */
376     static inline bool storeMessages(MessageList &messages)
377     {
378         return instance()->_storage->logMessages(messages);
379     }
380
381
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
388      */
389     static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
390     {
391         return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
392     }
393
394
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
400      */
401     static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
402     {
403         return instance()->_storage->requestAllMsgs(user, first, last, limit);
404     }
405
406
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.
410      *
411      *  \param user  The user whose buffers we request
412      *  \return A list of the BufferInfos for all buffers as requested
413      */
414     static inline QList<BufferInfo> requestBuffers(UserId user)
415     {
416         return instance()->_storage->requestBuffers(user);
417     }
418
419
420     //! Request a list of BufferIds for a given NetworkId
421     /** \note This method is threadsafe.
422      *
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
426      */
427     static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
428     {
429         return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
430     }
431
432
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.
436      *
437      *  \param user      The user who is the owner of the buffer
438      *  \param bufferId  The bufferId
439      *  \return true if successfull
440      */
441     static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
442     {
443         return instance()->_storage->removeBuffer(user, bufferId);
444     }
445
446
447     //! Rename a Buffer
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
453      */
454     static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
455     {
456         return instance()->_storage->renameBuffer(user, bufferId, newName);
457     }
458
459
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
466      */
467     static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
468     {
469         return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
470     }
471
472
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.
476      *
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
480      */
481     static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
482     {
483         return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
484     }
485
486
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.
490      *
491      * \param user      The Owner of the buffers
492      */
493     static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
494     {
495         return instance()->_storage->bufferLastSeenMsgIds(user);
496     }
497
498
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.
502      *
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
506      */
507     static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
508     {
509         return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
510     }
511
512
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.
516      *
517      * \param user      The Owner of the buffers
518      */
519     static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
520     {
521         return instance()->_storage->bufferMarkerLineMsgIds(user);
522     }
523
524
525     static inline QDateTime startTime() { return instance()->_startTime; }
526     static inline bool isConfigured() { return instance()->_configured; }
527     static bool sslSupported();
528
529     /**
530      * Reloads SSL certificates used for connection with clients
531      *
532      * @return True if certificates reloaded successfully, otherwise false.
533      */
534     static bool reloadCerts();
535
536     static QVariantList backendInfo();
537     static QVariantList authenticatorInfo();
538
539     /**
540      * Checks if a storage backend is the default storage backend. This
541      * hardcodes this information into the core (not the client).
542      *
543      * \param backend    The backend to check.
544      *
545      * @return True if storage backend is default, false otherwise.
546      */
547     static inline bool isStorageBackendDefault(const Storage *backend)
548     {
549         return (backend->displayName() == "SQLite") ? true : false;
550     }
551
552     static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupMap);
553
554     static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
555
556     inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
557
558     static const int AddClientEventId;
559
560 public slots:
561     //! Make storage data persistent
562     /** \note This method is threadsafe.
563      */
564     void syncStorage();
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);
567
568 signals:
569     //! Sent when a BufferInfo is updated in storage.
570     void bufferInfoUpdated(UserId user, const BufferInfo &info);
571
572     //! Relay from CoreSession::sessionState(). Used for internal connection only
573     void sessionState(const Protocol::SessionState &sessionState);
574
575 protected:
576     virtual void customEvent(QEvent *event);
577
578 private slots:
579     bool startListening();
580     void stopListening(const QString &msg = QString());
581     void incomingConnection();
582     void clientDisconnected();
583
584     bool initStorage(const QString &backend, const QVariantMap &settings, bool setup = false);
585     bool initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup = false);
586
587     void socketError(QAbstractSocket::SocketError err, const QString &errorString);
588     void setupClientSession(RemotePeer *, UserId);
589
590     bool changeUserPass(const QString &username);
591
592 private:
593     Core();
594     ~Core();
595     void init();
596     static Core *instanceptr;
597
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();
602
603     void registerStorageBackends();
604     bool registerStorageBackend(Storage *);
605     void unregisterStorageBackends();
606     void unregisterStorageBackend(Storage *);
607
608     void registerAuthenticatorBackends();
609     bool registerAuthenticatorBackend(Authenticator *);
610     void unregisterAuthenticatorBackends();
611     void unregisterAuthenticatorBackend(Authenticator *);
612
613     bool selectBackend(const QString &backend);
614     bool createUser();
615     bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
616     void saveAuthBackendSettings(const QString &backend, const QVariantMap &settings);
617     QVariantMap promptForSettings(const Storage *storage);
618
619 private:
620     QSet<CoreAuthHandler *> _connectingClients;
621     QHash<UserId, SessionThread *> _sessions;
622
623     // Have both a storage backend and an authenticator backend.
624     Storage *_storage;
625     Authenticator *_authenticator;
626     QTimer _storageSyncTimer;
627
628 #ifdef HAVE_SSL
629     SslServer _server, _v6server;
630 #else
631     QTcpServer _server, _v6server;
632 #endif
633
634     OidentdConfigGenerator *_oidentdConfigGenerator;
635
636     QHash<QString, Storage *> _storageBackends;
637     QHash<QString, Authenticator *> _authenticatorBackends;
638
639     QDateTime _startTime;
640
641     bool _configured;
642
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); }
648 };
649
650
651 #endif