Add strict-oidentd mode
[quassel.git] / src / core / core.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 #pragma once
22
23 #include <memory>
24 #include <vector>
25
26 #include <QDateTime>
27 #include <QString>
28 #include <QVariant>
29 #include <QTimer>
30
31 #ifdef HAVE_SSL
32 #  include <QSslSocket>
33 #  include "sslserver.h"
34 #else
35 #  include <QTcpSocket>
36 #  include <QTcpServer>
37 #endif
38
39 #include "authenticator.h"
40 #include "bufferinfo.h"
41 #include "deferredptr.h"
42 #include "message.h"
43 #include "oidentdconfiggenerator.h"
44 #include "sessionthread.h"
45 #include "storage.h"
46 #include "types.h"
47
48 class CoreAuthHandler;
49 class CoreSession;
50 struct NetworkInfo;
51 class SessionThread;
52 class SignalProxy;
53
54 class AbstractSqlMigrationReader;
55 class AbstractSqlMigrationWriter;
56
57 class Core : public QObject
58 {
59     Q_OBJECT
60
61 public:
62     static Core *instance();
63     static void destroy();
64
65     static void saveState();
66     static void restoreState();
67
68     /*** Storage access ***/
69     // These methods are threadsafe.
70
71     //! Validate user
72     /**
73      * \param userName The user's login name
74      * \param password The user's uncrypted password
75      * \return The user's ID if valid; 0 otherwise
76      */
77     static inline UserId validateUser(const QString &userName, const QString &password) {
78         return instance()->_storage->validateUser(userName, password);
79     }
80
81     //! Authenticate user against auth backend
82     /**
83      * \param userName The user's login name
84      * \param password The user's uncrypted password
85      * \return The user's ID if valid; 0 otherwise
86      */
87     static inline UserId authenticateUser(const QString &userName, const QString &password) {
88         return instance()->_authenticator->validateUser(userName, password);
89     }
90
91     //! Add a new user, exposed so auth providers can call this without being the storage.
92     /**
93      * \param userName The user's login name
94      * \param password The user's uncrypted password
95      * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
96      * \return The user's ID if valid; 0 otherwise
97      */
98     static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") {
99         return instance()->_storage->addUser(userName, password, authenticator);
100     }
101
102     //! Does a comparison test against the authenticator in the database and the authenticator currently in use for a UserID.
103     /**
104      * \param userid The user's ID (note: not login name).
105      * \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
106      * \return True if the userid was configured with the passed authenticator, false otherwise.
107      */
108     static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) {
109         return instance()->_storage->getUserAuthenticator(userid) == authenticator;
110     }
111
112     //! Change a user's password
113     /**
114      * \param userId     The user's ID
115      * \param password   The user's unencrypted new password
116      * \return true, if the password change was successful
117      */
118     static bool changeUserPassword(UserId userId, const QString &password);
119
120     //! Check if we can change a user password.
121     /**
122      * \param userID     The user's ID
123      * \return true, if we can change their password, false otherwise
124      */
125     static bool canChangeUserPassword(UserId userId);
126
127     //! Store a user setting persistently
128     /**
129      * \param userId       The users Id
130      * \param settingName  The Name of the Setting
131      * \param data         The Value
132      */
133     static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
134     {
135         instance()->_storage->setUserSetting(userId, settingName, data);
136     }
137
138
139     //! Retrieve a persistent user setting
140     /**
141      * \param userId       The users Id
142      * \param settingName  The Name of the Setting
143      * \param defaultValue Value to return in case it's unset.
144      * \return the Value of the Setting or the default value if it is unset.
145      */
146     static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
147     {
148         return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
149     }
150
151
152     /* Identity handling */
153     static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
154     {
155         return instance()->_storage->createIdentity(user, identity);
156     }
157
158
159     static bool updateIdentity(UserId user, const CoreIdentity &identity)
160     {
161         return instance()->_storage->updateIdentity(user, identity);
162     }
163
164
165     static void removeIdentity(UserId user, IdentityId identityId)
166     {
167         instance()->_storage->removeIdentity(user, identityId);
168     }
169
170
171     static QList<CoreIdentity> identities(UserId user)
172     {
173         return instance()->_storage->identities(user);
174     }
175
176
177     //! Create a Network in the Storage and store it's Id in the given NetworkInfo
178     /** \note This method is thredsafe.
179      *
180      *  \param user        The core user
181      *  \param networkInfo a NetworkInfo definition to store the newly created ID in
182      *  \return true if successfull.
183      */
184     static bool createNetwork(UserId user, NetworkInfo &info);
185
186     //! Apply the changes to NetworkInfo info to the storage engine
187     /** \note This method is thredsafe.
188      *
189      *  \param user        The core user
190      *  \param networkInfo The Updated NetworkInfo
191      *  \return true if successfull.
192      */
193     static inline bool updateNetwork(UserId user, const NetworkInfo &info)
194     {
195         return instance()->_storage->updateNetwork(user, info);
196     }
197
198
199     //! Permanently remove a Network and all the data associated with it.
200     /** \note This method is thredsafe.
201      *
202      *  \param user        The core user
203      *  \param networkId   The network to delete
204      *  \return true if successfull.
205      */
206     static inline bool removeNetwork(UserId user, const NetworkId &networkId)
207     {
208         return instance()->_storage->removeNetwork(user, networkId);
209     }
210
211
212     //! Returns a list of all NetworkInfos for the given UserId user
213     /** \note This method is thredsafe.
214      *
215      *  \param user        The core user
216      *  \return QList<NetworkInfo>.
217      */
218     static inline QList<NetworkInfo> networks(UserId user)
219     {
220         return instance()->_storage->networks(user);
221     }
222
223
224     //! Get a list of Networks to restore
225     /** Return a list of networks the user was connected at the time of core shutdown
226      *  \note This method is threadsafe.
227      *
228      *  \param user  The User Id in question
229      */
230     static inline QList<NetworkId> connectedNetworks(UserId user)
231     {
232         return instance()->_storage->connectedNetworks(user);
233     }
234
235
236     //! Update the connected state of a network
237     /** \note This method is threadsafe
238      *
239      *  \param user        The Id of the networks owner
240      *  \param networkId   The Id of the network
241      *  \param isConnected whether the network is connected or not
242      */
243     static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
244     {
245         return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
246     }
247
248
249     //! Get a hash of channels with their channel keys for a given network
250     /** The keys are channel names and values are passwords (possibly empty)
251      *  \note This method is threadsafe
252      *
253      *  \param user       The id of the networks owner
254      *  \param networkId  The Id of the network
255      */
256     static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
257     {
258         return instance()->_storage->persistentChannels(user, networkId);
259     }
260
261
262     //! Update the connected state of a channel
263     /** \note This method is threadsafe
264      *
265      *  \param user       The Id of the networks owner
266      *  \param networkId  The Id of the network
267      *  \param channel    The name of the channel
268      *  \param isJoined   whether the channel is connected or not
269      */
270     static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
271     {
272         return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
273     }
274
275
276     //! Update the key of a channel
277     /** \note This method is threadsafe
278      *
279      *  \param user       The Id of the networks owner
280      *  \param networkId  The Id of the network
281      *  \param channel    The name of the channel
282      *  \param key        The key of the channel (possibly empty)
283      */
284     static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
285     {
286         return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
287     }
288
289
290     //! retrieve last known away message for session restore
291     /** \note This method is threadsafe
292      *
293      *  \param user       The Id of the networks owner
294      *  \param networkId  The Id of the network
295      */
296     static inline QString awayMessage(UserId user, NetworkId networkId)
297     {
298         return instance()->_storage->awayMessage(user, networkId);
299     }
300
301
302     //! Make away message persistent for session restore
303     /** \note This method is threadsafe
304      *
305      *  \param user       The Id of the networks owner
306      *  \param networkId  The Id of the network
307      *  \param awayMsg    The current away message of own user
308      */
309     static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
310     {
311         return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
312     }
313
314
315     //! retrieve last known user mode for session restore
316     /** \note This method is threadsafe
317      *
318      *  \param user       The Id of the networks owner
319      *  \param networkId  The Id of the network
320      */
321     static inline QString userModes(UserId user, NetworkId networkId)
322     {
323         return instance()->_storage->userModes(user, networkId);
324     }
325
326
327     //! Make our user modes persistent for session restore
328     /** \note This method is threadsafe
329      *
330      *  \param user       The Id of the networks owner
331      *  \param networkId  The Id of the network
332      *  \param userModes  The current user modes of own user
333      */
334     static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
335     {
336         return instance()->_storage->setUserModes(user, networkId, userModes);
337     }
338
339
340     //! Get the unique BufferInfo for the given combination of network and buffername for a user.
341     /** \note This method is threadsafe.
342      *
343      *  \param user      The core user who owns this buffername
344      *  \param networkId The network id
345      *  \param type      The type of the buffer (StatusBuffer, Channel, etc.)
346      *  \param buffer    The buffer name (if empty, the net's status buffer is returned)
347      *  \param create    Whether or not the buffer should be created if it doesnt exist
348      *  \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
349      */
350     static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
351     {
352         return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
353     }
354
355
356     //! Get the unique BufferInfo for a bufferId
357     /** \note This method is threadsafe
358      *  \param user      The core user who owns this buffername
359      *  \param bufferId  The id of the buffer
360      *  \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
361      */
362     static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
363     {
364         return instance()->_storage->getBufferInfo(user, bufferId);
365     }
366
367
368     //! Store a Message in the storage backend and set it's unique Id.
369     /** \note This method is threadsafe.
370      *
371      *  \param message The message object to be stored
372      *  \return true on success
373      */
374     static inline bool storeMessage(Message &message)
375     {
376         return instance()->_storage->logMessage(message);
377     }
378
379
380     //! Store a list of Messages in the storage backend and set their unique Id.
381     /** \note This method is threadsafe.
382      *
383      *  \param messages The list message objects to be stored
384      *  \return true on success
385      */
386     static inline bool storeMessages(MessageList &messages)
387     {
388         return instance()->_storage->logMessages(messages);
389     }
390
391
392     //! Request a certain number messages stored in a given buffer.
393     /** \param buffer   The buffer we request messages from
394      *  \param first    if != -1 return only messages with a MsgId >= first
395      *  \param last     if != -1 return only messages with a MsgId < last
396      *  \param limit    if != -1 limit the returned list to a max of \limit entries
397      *  \return The requested list of messages
398      */
399     static inline QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1)
400     {
401         return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
402     }
403
404
405     //! Request a certain number of messages across all buffers
406     /** \param first    if != -1 return only messages with a MsgId >= first
407      *  \param last     if != -1 return only messages with a MsgId < last
408      *  \param limit    Max amount of messages
409      *  \return The requested list of messages
410      */
411     static inline QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1)
412     {
413         return instance()->_storage->requestAllMsgs(user, first, last, limit);
414     }
415
416
417     //! Request a list of all buffers known to a user.
418     /** This method is used to get a list of all buffers we have stored a backlog from.
419      *  \note This method is threadsafe.
420      *
421      *  \param user  The user whose buffers we request
422      *  \return A list of the BufferInfos for all buffers as requested
423      */
424     static inline QList<BufferInfo> requestBuffers(UserId user)
425     {
426         return instance()->_storage->requestBuffers(user);
427     }
428
429
430     //! Request a list of BufferIds for a given NetworkId
431     /** \note This method is threadsafe.
432      *
433      *  \param user  The user whose buffers we request
434      *  \param networkId  The NetworkId of the network in question
435      *  \return List of BufferIds belonging to the Network
436      */
437     static inline QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId)
438     {
439         return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
440     }
441
442
443     //! Remove permanently a buffer and it's content from the storage backend
444     /** This call cannot be reverted!
445      *  \note This method is threadsafe.
446      *
447      *  \param user      The user who is the owner of the buffer
448      *  \param bufferId  The bufferId
449      *  \return true if successfull
450      */
451     static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
452     {
453         return instance()->_storage->removeBuffer(user, bufferId);
454     }
455
456
457     //! Rename a Buffer
458     /** \note This method is threadsafe.
459      *  \param user      The id of the buffer owner
460      *  \param bufferId  The bufferId
461      *  \param newName   The new name of the buffer
462      *  \return true if successfull
463      */
464     static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
465     {
466         return instance()->_storage->renameBuffer(user, bufferId, newName);
467     }
468
469
470     //! Merge the content of two Buffers permanently. This cannot be reversed!
471     /** \note This method is threadsafe.
472      *  \param user      The id of the buffer owner
473      *  \param bufferId1 The bufferId of the remaining buffer
474      *  \param bufferId2 The buffer that is about to be removed
475      *  \return true if successfulln
476      */
477     static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
478     {
479         return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
480     }
481
482
483     //! Update the LastSeenDate for a Buffer
484     /** This Method is used to make the LastSeenDate of a Buffer persistent
485      *  \note This method is threadsafe.
486      *
487      * \param user      The Owner of that Buffer
488      * \param bufferId  The buffer id
489      * \param MsgId     The Message id of the message that has been just seen
490      */
491     static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
492     {
493         return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
494     }
495
496     //! Get the auth username associated with a userId
497     /** \param user  The user to retrieve the username for
498      *  \return      The username for the user
499      */
500     static inline const QString getAuthusername(UserId user) {
501         return instance()->_storage->getAuthusername(user);
502     }
503
504
505     //! Get a Hash of all last seen message ids
506     /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
507      *  \note This method is threadsafe.
508      *
509      * \param user      The Owner of the buffers
510      */
511     static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
512     {
513         return instance()->_storage->bufferLastSeenMsgIds(user);
514     }
515
516
517     //! Update the MarkerLineMsgId for a Buffer
518     /** This Method is used to make the marker line position of a Buffer persistent
519      *  \note This method is threadsafe.
520      *
521      * \param user      The Owner of that Buffer
522      * \param bufferId  The buffer id
523      * \param MsgId     The Message id where the marker line should be placed
524      */
525     static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
526     {
527         return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
528     }
529
530
531     //! Get a Hash of all marker line message ids
532     /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
533      *  \note This method is threadsafe.
534      *
535      * \param user      The Owner of the buffers
536      */
537     static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
538     {
539         return instance()->_storage->bufferMarkerLineMsgIds(user);
540     }
541
542     //! Update the BufferActivity for a Buffer
543     /** This Method is used to make the activity state of a Buffer persistent
544      *  \note This method is threadsafe.
545      *
546      * \param user      The Owner of that Buffer
547      * \param bufferId  The buffer id
548      * \param MsgId     The Message id where the marker line should be placed
549      */
550     static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity) {
551         return instance()->_storage->setBufferActivity(user, bufferId, activity);
552     }
553
554
555     //! Get a Hash of all buffer activity states
556     /** This Method is called when the Quassel Core is started to restore the BufferActivity
557      *  \note This method is threadsafe.
558      *
559      * \param user      The Owner of the buffers
560      */
561     static inline QHash<BufferId, Message::Types> bufferActivities(UserId user) {
562         return instance()->_storage->bufferActivities(user);
563     }
564
565     //! Get the bitset of buffer activity states for a buffer
566     /** This method is used to load the activity state of a buffer when its last seen message changes.
567      *  \note This method is threadsafe.
568      *
569      * \param bufferId The buffer
570      * \param lastSeenMsgId     The last seen message
571      */
572     static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) {
573         return instance()->_storage->bufferActivity(bufferId, lastSeenMsgId);
574     }
575
576     static inline QDateTime startTime() { return instance()->_startTime; }
577     static inline bool isConfigured() { return instance()->_configured; }
578     static bool sslSupported();
579
580     /**
581      * Reloads SSL certificates used for connection with clients
582      *
583      * @return True if certificates reloaded successfully, otherwise false.
584      */
585     static bool reloadCerts();
586
587     static QVariantList backendInfo();
588     static QVariantList authenticatorInfo();
589
590     static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
591
592     static inline QTimer &syncTimer() { return instance()->_storageSyncTimer; }
593
594     inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
595
596     static const int AddClientEventId;
597
598 public slots:
599     //! Make storage data persistent
600     /** \note This method is threadsafe.
601      */
602     void syncStorage();
603     void setupInternalClientSession(InternalPeer *clientConnection);
604     QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
605
606 signals:
607     //! Sent when a BufferInfo is updated in storage.
608     void bufferInfoUpdated(UserId user, const BufferInfo &info);
609
610     //! Relay from CoreSession::sessionState(). Used for internal connection only
611     void sessionState(const Protocol::SessionState &sessionState);
612
613 protected:
614     virtual void customEvent(QEvent *event);
615
616 private slots:
617     bool startListening();
618     void stopListening(const QString &msg = QString());
619     void incomingConnection();
620     void clientDisconnected();
621
622     bool initStorage(const QString &backend, const QVariantMap &settings, bool setup = false);
623     bool initAuthenticator(const QString &backend, const QVariantMap &settings, bool setup = false);
624
625     void socketError(QAbstractSocket::SocketError err, const QString &errorString);
626     void setupClientSession(RemotePeer *, UserId);
627
628     bool changeUserPass(const QString &username);
629
630 private:
631     Core();
632     ~Core();
633     void init();
634     static Core *instanceptr;
635
636     SessionThread *sessionForUser(UserId userId, bool restoreState = false);
637     void addClientHelper(RemotePeer *peer, UserId uid);
638     //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
639     QString setupCoreForInternalUsage();
640
641     bool createUser();
642
643     template<typename Storage>
644     void registerStorageBackend();
645
646     template<typename Authenticator>
647     void registerAuthenticator();
648
649     void registerStorageBackends();
650     void registerAuthenticators();
651
652     DeferredSharedPtr<Storage>       storageBackend(const QString& backendId) const;
653     DeferredSharedPtr<Authenticator> authenticator(const QString& authenticatorId) const;
654
655     bool selectBackend(const QString &backend);
656     bool selectAuthenticator(const QString &backend);
657
658     bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
659     void saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings);
660
661     template<typename Backend>
662     QVariantMap promptForSettings(const Backend *backend);
663
664 private:
665     QSet<CoreAuthHandler *> _connectingClients;
666     QHash<UserId, SessionThread *> _sessions;
667     DeferredSharedPtr<Storage>       _storage;        ///< Active storage backend
668     DeferredSharedPtr<Authenticator> _authenticator;  ///< Active authenticator
669     QTimer _storageSyncTimer;
670
671 #ifdef HAVE_SSL
672     SslServer _server, _v6server;
673 #else
674     QTcpServer _server, _v6server;
675 #endif
676
677     OidentdConfigGenerator *_oidentdConfigGenerator {nullptr};
678
679     std::vector<DeferredSharedPtr<Storage>>       _registeredStorageBackends;
680     std::vector<DeferredSharedPtr<Authenticator>> _registeredAuthenticators;
681
682     QDateTime _startTime;
683
684     bool _configured;
685
686     static std::unique_ptr<AbstractSqlMigrationReader> getMigrationReader(Storage *storage);
687     static std::unique_ptr<AbstractSqlMigrationWriter> getMigrationWriter(Storage *storage);
688     static void stdInEcho(bool on);
689     static inline void enableStdInEcho() { stdInEcho(true); }
690     static inline void disableStdInEcho() { stdInEcho(false); }
691 };