Implement authenticator class used for logging in users
[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     //! Change a user's password
89     /**
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
93      */
94     static bool changeUserPassword(UserId userId, const QString &password);
95
96     //! Store a user setting persistently
97     /**
98      * \param userId       The users Id
99      * \param settingName  The Name of the Setting
100      * \param data         The Value
101      */
102     static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
103     {
104         instance()->_storage->setUserSetting(userId, settingName, data);
105     }
106
107
108     //! Retrieve a persistent user setting
109     /**
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.
114      */
115     static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
116     {
117         return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
118     }
119
120
121     /* Identity handling */
122     static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
123     {
124         return instance()->_storage->createIdentity(user, identity);
125     }
126
127
128     static bool updateIdentity(UserId user, const CoreIdentity &identity)
129     {
130         return instance()->_storage->updateIdentity(user, identity);
131     }
132
133
134     static void removeIdentity(UserId user, IdentityId identityId)
135     {
136         instance()->_storage->removeIdentity(user, identityId);
137     }
138
139
140     static QList<CoreIdentity> identities(UserId user)
141     {
142         return instance()->_storage->identities(user);
143     }
144
145
146     //! Create a Network in the Storage and store it's Id in the given NetworkInfo
147     /** \note This method is thredsafe.
148      *
149      *  \param user        The core user
150      *  \param networkInfo a NetworkInfo definition to store the newly created ID in
151      *  \return true if successfull.
152      */
153     static bool createNetwork(UserId user, NetworkInfo &info);
154
155     //! Apply the changes to NetworkInfo info to the storage engine
156     /** \note This method is thredsafe.
157      *
158      *  \param user        The core user
159      *  \param networkInfo The Updated NetworkInfo
160      *  \return true if successfull.
161      */
162     static inline bool updateNetwork(UserId user, const NetworkInfo &info)
163     {
164         return instance()->_storage->updateNetwork(user, info);
165     }
166
167
168     //! Permanently remove a Network and all the data associated with it.
169     /** \note This method is thredsafe.
170      *
171      *  \param user        The core user
172      *  \param networkId   The network to delete
173      *  \return true if successfull.
174      */
175     static inline bool removeNetwork(UserId user, const NetworkId &networkId)
176     {
177         return instance()->_storage->removeNetwork(user, networkId);
178     }
179
180
181     //! Returns a list of all NetworkInfos for the given UserId user
182     /** \note This method is thredsafe.
183      *
184      *  \param user        The core user
185      *  \return QList<NetworkInfo>.
186      */
187     static inline QList<NetworkInfo> networks(UserId user)
188     {
189         return instance()->_storage->networks(user);
190     }
191
192
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.
196      *
197      *  \param user  The User Id in question
198      */
199     static inline QList<NetworkId> connectedNetworks(UserId user)
200     {
201         return instance()->_storage->connectedNetworks(user);
202     }
203
204
205     //! Update the connected state of a network
206     /** \note This method is threadsafe
207      *
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
211      */
212     static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
213     {
214         return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
215     }
216
217
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
221      *
222      *  \param user       The id of the networks owner
223      *  \param networkId  The Id of the network
224      */
225     static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
226     {
227         return instance()->_storage->persistentChannels(user, networkId);
228     }
229
230
231     //! Update the connected state of a channel
232     /** \note This method is threadsafe
233      *
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
238      */
239     static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
240     {
241         return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
242     }
243
244
245     //! Update the key of a channel
246     /** \note This method is threadsafe
247      *
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)
252      */
253     static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
254     {
255         return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
256     }
257
258
259     //! retrieve last known away message for session restore
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      */
265     static inline QString awayMessage(UserId user, NetworkId networkId)
266     {
267         return instance()->_storage->awayMessage(user, networkId);
268     }
269
270
271     //! Make away message persistent for session restore
272     /** \note This method is threadsafe
273      *
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
277      */
278     static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
279     {
280         return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
281     }
282
283
284     //! retrieve last known user mode for session restore
285     /** \note This method is threadsafe
286      *
287      *  \param user       The Id of the networks owner
288      *  \param networkId  The Id of the network
289      */
290     static inline QString userModes(UserId user, NetworkId networkId)
291     {
292         return instance()->_storage->userModes(user, networkId);
293     }
294
295
296     //! Make our user modes persistent for session restore
297     /** \note This method is threadsafe
298      *
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
302      */
303     static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
304     {
305         return instance()->_storage->setUserModes(user, networkId, userModes);
306     }
307
308
309     //! Get the unique BufferInfo for the given combination of network and buffername for a user.
310     /** \note This method is threadsafe.
311      *
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
318      */
319     static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
320     {
321         return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
322     }
323
324
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.
330      */
331     static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
332     {
333         return instance()->_storage->getBufferInfo(user, bufferId);
334     }
335
336
337     //! Store a Message in the storage backend and set it's unique Id.
338     /** \note This method is threadsafe.
339      *
340      *  \param message The message object to be stored
341      *  \return true on success
342      */
343     static inline bool storeMessage(Message &message)
344     {
345         return instance()->_storage->logMessage(message);
346     }
347
348
349     //! Store a list of Messages in the storage backend and set their unique Id.
350     /** \note This method is threadsafe.
351      *
352      *  \param messages The list message objects to be stored
353      *  \return true on success
354      */
355     static inline bool storeMessages(MessageList &messages)
356     {
357         return instance()->_storage->logMessages(messages);
358     }
359
360
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
367      */
368     static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
369     {
370         return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
371     }
372
373
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
379      */
380     static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
381     {
382         return instance()->_storage->requestAllMsgs(user, first, last, limit);
383     }
384
385
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.
389      *
390      *  \param user  The user whose buffers we request
391      *  \return A list of the BufferInfos for all buffers as requested
392      */
393     static inline QList<BufferInfo> requestBuffers(UserId user)
394     {
395         return instance()->_storage->requestBuffers(user);
396     }
397
398
399     //! Request a list of BufferIds for a given NetworkId
400     /** \note This method is threadsafe.
401      *
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
405      */
406     static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
407     {
408         return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
409     }
410
411
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.
415      *
416      *  \param user      The user who is the owner of the buffer
417      *  \param bufferId  The bufferId
418      *  \return true if successfull
419      */
420     static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
421     {
422         return instance()->_storage->removeBuffer(user, bufferId);
423     }
424
425
426     //! Rename a Buffer
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
432      */
433     static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
434     {
435         return instance()->_storage->renameBuffer(user, bufferId, newName);
436     }
437
438
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
445      */
446     static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
447     {
448         return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
449     }
450
451
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.
455      *
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
459      */
460     static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
461     {
462         return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
463     }
464
465
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.
469      *
470      * \param user      The Owner of the buffers
471      */
472     static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
473     {
474         return instance()->_storage->bufferLastSeenMsgIds(user);
475     }
476
477
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.
481      *
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
485      */
486     static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
487     {
488         return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
489     }
490
491
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.
495      *
496      * \param user      The Owner of the buffers
497      */
498     static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
499     {
500         return instance()->_storage->bufferMarkerLineMsgIds(user);
501     }
502
503
504     static inline QDateTime startTime() { return instance()->_startTime; }
505     static inline bool isConfigured() { return instance()->_configured; }
506     static bool sslSupported();
507
508     /**
509      * Reloads SSL certificates used for connection with clients
510      *
511      * @return True if certificates reloaded successfully, otherwise false.
512      */
513     static bool reloadCerts();
514
515     static QVariantList backendInfo();
516     static QVariantList authenticatorInfo();
517
518     /**
519      * Checks if a storage backend is the default storage backend. This
520      * hardcodes this information into the core (not the client).
521      *
522      * \param backend    The backend to check.
523      *
524      * @return True if storage backend is default, false otherwise.
525      */
526     static inline bool isStorageBackendDefault(const Storage *backend)
527     {
528         return (backend->displayName() == "SQLite") ? true : false;
529     }
530
531     static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authBackend, const QVariantMap &authSetupMap);
532
533     static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
534
535     inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
536
537     static const int AddClientEventId;
538
539 public slots:
540     //! Make storage data persistent
541     /** \note This method is threadsafe.
542      */
543     void syncStorage();
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);
546
547 signals:
548     //! Sent when a BufferInfo is updated in storage.
549     void bufferInfoUpdated(UserId user, const BufferInfo &info);
550
551     //! Relay from CoreSession::sessionState(). Used for internal connection only
552     void sessionState(const Protocol::SessionState &sessionState);
553
554 protected:
555     virtual void customEvent(QEvent *event);
556
557 private slots:
558     bool startListening();
559     void stopListening(const QString &msg = QString());
560     void incomingConnection();
561     void clientDisconnected();
562
563     bool initStorage(const QString &backend, const QVariantMap &settings, bool setup = false);
564     bool initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup = false);
565     
566     void socketError(QAbstractSocket::SocketError err, const QString &errorString);
567     void setupClientSession(RemotePeer *, UserId);
568
569     bool changeUserPass(const QString &username);
570
571 private:
572     Core();
573     ~Core();
574     void init();
575     static Core *instanceptr;
576
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();
581
582     void registerStorageBackends();
583     bool registerStorageBackend(Storage *);
584     void unregisterStorageBackends();
585     void unregisterStorageBackend(Storage *);
586     
587     void registerAuthenticatorBackends();
588     bool registerAuthenticatorBackend(Authenticator *);
589     void unregisterAuthenticatorBackends();
590     void unregisterAuthenticatorBackend(Authenticator *);
591     
592     bool selectBackend(const QString &backend);
593     bool createUser();
594     bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
595     void saveAuthBackendSettings(const QString &backend, const QVariantMap &settings);
596     QVariantMap promptForSettings(const Storage *storage);
597
598 private:
599     QSet<CoreAuthHandler *> _connectingClients;
600     QHash<UserId, SessionThread *> _sessions;
601
602     // Have both a storage backend and an authenticator backend.
603     Storage *_storage;
604     Authenticator *_authenticator;
605     QTimer _storageSyncTimer;
606
607 #ifdef HAVE_SSL
608     SslServer _server, _v6server;
609 #else
610     QTcpServer _server, _v6server;
611 #endif
612
613     OidentdConfigGenerator *_oidentdConfigGenerator;
614
615     QHash<QString, Storage *> _storageBackends;
616     QHash<QString, Authenticator *> _authenticatorBackends;
617
618     QDateTime _startTime;
619
620     bool _configured;
621
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); }
627 };
628
629
630 #endif