modernize: Use '= default' instead of empty ctor/dtor bodies
[quassel.git] / src / core / storage.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 #ifndef STORAGE_H
22 #define STORAGE_H
23
24 #include <QtCore>
25
26 #include "types.h"
27 #include "coreidentity.h"
28 #include "message.h"
29 #include "network.h"
30
31 class Storage : public QObject
32 {
33     Q_OBJECT
34
35 public:
36     Storage(QObject *parent = nullptr);
37
38     enum State {
39         IsReady,    // ready to go
40         NeedsSetup, // need basic setup (ask the user for input)
41         NotAvailable // remove the storage backend from the list of avaliable backends
42     };
43
44     enum HashVersion {
45         Sha1,
46         Sha2_512,
47         Latest=Sha2_512
48
49     };
50
51 public slots:
52     /* General */
53
54     //! Check if the storage type is available.
55     /** A storage subclass should return true if it can be successfully used, i.e. if all
56      *  prerequisites are in place (e.g. we have an appropriate DB driver etc.).
57      * \return True if and only if the storage class can be successfully used.
58      */
59     virtual bool isAvailable() const = 0;
60
61     //! Returns the identifier of the authenticator backend
62     /** \return A string that can be used by the client to identify the authenticator backend */
63     virtual QString backendId() const = 0;
64
65     //! Returns the display name of the storage backend
66     /** \return A string that can be used by the client to name the storage backend */
67     virtual QString displayName() const = 0;
68
69     //! Returns a description of this storage backend
70     /** \return A string that can be displayed by the client to describe the storage backend */
71     virtual QString description() const = 0;
72
73     //! Returns data required to configure the authenticator backend
74     /**
75      * A list of flattened triples for each field: {key, translated field name, default value}
76      * The default value's type determines the kind of input widget to be shown
77      * (int -> QSpinBox; QString -> QLineEdit)
78      * \return A list of triples defining the data to be shown in the configuration dialog
79      */
80     virtual QVariantList setupData() const = 0;
81
82     //! Setup the storage provider.
83     /** This prepares the storage provider (e.g. create tables, etc.) for use within Quassel.
84      *  \param settings   Hostname, port, username, password, ...
85      *  \return True if and only if the storage provider was initialized successfully.
86      */
87     virtual bool setup(const QVariantMap &settings = QVariantMap(),
88                        const QProcessEnvironment &environment = {},
89                        bool loadFromEnvironment = false) = 0;
90
91     //! Initialize the storage provider
92     /** \param settings   Hostname, port, username, password, ...
93      *  \return the State the storage backend is now in (see Storage::State)
94      */
95     virtual State init(const QVariantMap &settings = QVariantMap(),
96                        const QProcessEnvironment &environment = {},
97                        bool loadFromEnvironment = false) = 0;
98
99     //! Makes temp data persistent
100     /** This Method is periodically called by the Quassel Core to make temporary
101      *  data persistant. This reduces the data loss drastically in the
102      *  unlikely case of a Core crash.
103      */
104     virtual void sync() = 0;
105
106     // TODO: Add functions for configuring the backlog handling, i.e. defining auto-cleanup settings etc
107
108     /* User handling */
109
110     //! Add a new core user to the storage.
111     /** \param user     The username of the new user
112      *  \param password The cleartext password for the new user
113      *  \return The new user's UserId
114      */
115     virtual UserId addUser(const QString &user, const QString &password, const QString &authenticator = "Database") = 0;
116
117     //! Update a core user's password.
118     /** \param user     The user's id
119      *  \param password The user's new password
120      *  \return true on success.
121      */
122     virtual bool updateUser(UserId user, const QString &password) = 0;
123
124     //! Rename a user
125     /** \param user     The user's id
126      *  \param newName  The user's new name
127      */
128     virtual void renameUser(UserId user, const QString &newName) = 0;
129
130     //! Validate a username with a given password.
131     /** \param user     The username to validate
132      *  \param password The user's alleged password
133      *  \return A valid UserId if the password matches the username; 0 else
134      */
135     virtual UserId validateUser(const QString &user, const QString &password) = 0;
136
137     //! Check if a user with given username exists. Do not use for login purposes!
138     /** \param username  The username to validate
139      *  \return A valid UserId if the user exists; 0 else
140      */
141     virtual UserId getUserId(const QString &username) = 0;
142
143     //! Get the authentication provider for a given user.
144     /** \param username  The username to validate
145      *  \return The name of the auth provider if the UserId exists, "" otherwise.
146      */
147     virtual QString getUserAuthenticator(const UserId userid) = 0;
148
149
150     //! Determine the UserId of the internal user
151     /** \return A valid UserId if the password matches the username; 0 else
152      */
153     virtual UserId internalUser() = 0;
154
155     //! Remove a core user from storage.
156     /** \param user     The userid to delete
157      */
158     virtual void delUser(UserId user) = 0;
159
160     //! Store a user setting persistently
161     /**
162      * \param userId       The users Id
163      * \param settingName  The Name of the Setting
164      * \param data         The Value
165      */
166     virtual void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) = 0;
167
168     //! Retrieve a persistent user setting
169     /**
170      * \param userId       The users Id
171      * \param settingName  The Name of the Setting
172      * \param default      Value to return in case it's unset.
173      * \return the Value of the Setting or the default value if it is unset.
174      */
175     virtual QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &data = QVariant()) = 0;
176
177     //! Store core state
178     /**
179      * \param data         Active Sessions
180      */
181     virtual void setCoreState(const QVariantList &data) = 0;
182
183     //! Retrieve core state
184     /**
185      * \param default      Value to return in case it's unset.
186      * \return Active Sessions
187      */
188     virtual QVariantList getCoreState(const QVariantList &data = QVariantList()) = 0;
189
190     /* Identity handling */
191     virtual IdentityId createIdentity(UserId user, CoreIdentity &identity) = 0;
192     virtual bool updateIdentity(UserId user, const CoreIdentity &identity) = 0;
193     virtual void removeIdentity(UserId user, IdentityId identityId) = 0;
194     virtual QList<CoreIdentity> identities(UserId user) = 0;
195
196     /* Network handling */
197
198     //! Create a new Network in the storage backend and return it unique Id
199     /** \param user        The core user who owns this network
200      *  \param networkInfo The networkInfo holding the network definition
201      *  \return the NetworkId of the newly created Network. Possibly invalid.
202      */
203     virtual NetworkId createNetwork(UserId user, const NetworkInfo &info) = 0;
204
205     //! Apply the changes to NetworkInfo info to the storage engine
206     /**
207      *  \param user        The core user
208      *  \param networkInfo The Updated NetworkInfo
209      *  \return true if successfull.
210      */
211     virtual bool updateNetwork(UserId user, const NetworkInfo &info) = 0;
212
213     //! Permanently remove a Network and all the data associated with it.
214     /** \note This method is thredsafe.
215      *
216      *  \param user        The core user
217      *  \param networkId   The network to delete
218      *  \return true if successfull.
219      */
220     virtual bool removeNetwork(UserId user, const NetworkId &networkId) = 0;
221
222     //! Returns a list of all NetworkInfos for the given UserId user
223     /** \note This method is thredsafe.
224      *
225      *  \param user        The core user
226      *  \return QList<NetworkInfo>.
227      */
228     virtual QList<NetworkInfo> networks(UserId user) = 0;
229
230     //! Get a list of Networks to restore
231     /** Return a list of networks the user was connected at the time of core shutdown
232      *  \note This method is threadsafe.
233      *
234      *  \param user  The User Id in question
235      */
236     virtual QList<NetworkId> connectedNetworks(UserId user) = 0;
237
238     //! Update the connected state of a network
239     /** \note This method is threadsafe
240      *
241      *  \param user        The Id of the networks owner
242      *  \param networkId   The Id of the network
243      *  \param isConnected whether the network is connected or not
244      */
245     virtual void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) = 0;
246
247     //! Get a hash of channels with their channel keys for a given network
248     /** The keys are channel names and values are passwords (possibly empty)
249      *  \note This method is threadsafe
250      *
251      *  \param user       The id of the networks owner
252      *  \param networkId  The Id of the network
253      */
254     virtual QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId) = 0;
255
256     //! Update the connected state of a channel
257     /** \note This method is threadsafe
258      *
259      *  \param user       The Id of the networks owner
260      *  \param networkId  The Id of the network
261      *  \param channel    The name of the channel
262      *  \param isJoined   whether the channel is connected or not
263      */
264     virtual void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) = 0;
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     virtual void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) = 0;
275
276     //! retrieve last known away message for session restore
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      */
282     virtual QString awayMessage(UserId user, NetworkId networkId) = 0;
283
284     //! Make away message persistent 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      *  \param awayMsg    The current away message of own user
290      */
291     virtual void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) = 0;
292
293     //! retrieve last known user mode for session restore
294     /** \note This method is threadsafe
295      *
296      *  \param user       The Id of the networks owner
297      *  \param networkId  The Id of the network
298      */
299     virtual QString userModes(UserId user, NetworkId networkId) = 0;
300
301     //! Make our user modes persistent for session restore
302     /** \note This method is threadsafe
303      *
304      *  \param user       The Id of the networks owner
305      *  \param networkId  The Id of the network
306      *  \param userModes  The current user modes of own user
307      */
308     virtual void setUserModes(UserId user, NetworkId networkId, const QString &userModes) = 0;
309
310     /* Buffer handling */
311
312     //! Get the unique BufferInfo for the given combination of network and buffername for a user.
313     /** \param user      The core user who owns this buffername
314      *  \param networkId The network id
315      *  \param type      The type of the buffer (StatusBuffer, Channel, etc.)
316      *  \param buffer  The buffer name (if empty, the net's status buffer is returned)
317      *  \param create    Whether or not the buffer should be created if it doesnt exist
318      *  \return The BufferInfo corresponding to the given network and buffer name, or an invalid BufferInfo if not found
319      */
320     virtual BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) = 0;
321
322     //! Get the unique BufferInfo for a bufferId
323     /** \param user      The core user who owns this buffername
324      *  \param bufferId  The id of the buffer
325      *  \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
326      */
327     virtual BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) = 0;
328
329     //! Request a list of all buffers known to a user.
330     /** This method is used to get a list of all buffers we have stored a backlog from.
331      *  \param user  The user whose buffers we request
332      *  \return A list of the BufferInfos for all buffers as requested
333      */
334     virtual QList<BufferInfo> requestBuffers(UserId user) = 0;
335
336     //! Request a list of BufferIds for a given NetworkId
337     /** \note This method is threadsafe.
338      *
339      *  \param user  The user whose buffers we request
340      *  \param networkId  The NetworkId of the network in question
341      *  \return List of BufferIds belonging to the Network
342      */
343     virtual QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId) = 0;
344
345     //! Remove permanently a buffer and it's content from the storage backend
346     /** This call cannot be reverted!
347      *  \param user      The user who is the owner of the buffer
348      *  \param bufferId  The bufferId
349      *  \return true if successfull
350      */
351     virtual bool removeBuffer(const UserId &user, const BufferId &bufferId) = 0;
352
353     //! Rename a Buffer
354     /** \note This method is threadsafe.
355      *  \param user      The id of the buffer owner
356      *  \param bufferId  The bufferId
357      *  \param newName   The new name of the buffer
358      *  \return true if successfull
359      */
360     virtual bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) = 0;
361
362     //! Merge the content of two Buffers permanently. This cannot be reversed!
363     /** \note This method is threadsafe.
364      *  \param user      The id of the buffer owner
365      *  \param bufferId1 The bufferId of the remaining buffer
366      *  \param bufferId2 The buffer that is about to be removed
367      *  \return true if successfull
368      */
369     virtual bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) = 0;
370
371     //! Update the LastSeenDate for a Buffer
372     /** This Method is used to make the LastSeenDate of a Buffer persistent
373      * \param user      The Owner of that Buffer
374      * \param bufferId  The buffer id
375      * \param MsgId     The Message id of the message that has been just seen
376      */
377     virtual void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) = 0;
378
379     //! Get a Hash of all last seen message ids
380     /** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
381      * \param user      The Owner of the buffers
382      */
383     virtual QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user) = 0;
384
385     //! Update the MarkerLineMsgId for a Buffer
386     /** This Method is used to make the marker line position of a Buffer persistent
387      *  \note This method is threadsafe.
388      *
389      * \param user      The Owner of that Buffer
390      * \param bufferId  The buffer id
391      * \param MsgId     The Message id where the marker line should be placed
392      */
393     virtual void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) = 0;
394
395     //! Get a Hash of all marker line message ids
396     /** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
397      *  \note This method is threadsafe.
398      *
399      * \param user      The Owner of the buffers
400      */
401     virtual QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user) = 0;
402
403     //! Update the BufferActivity for a Buffer
404     /** This Method is used to make the activity state of a Buffer persistent
405      *  \note This method is threadsafe.
406      *
407      * \param user      The Owner of that Buffer
408      * \param bufferId  The buffer id
409      * \param MsgId     The Message id where the marker line should be placed
410      */
411     virtual void setBufferActivity(UserId id, BufferId bufferId, Message::Types type) = 0;
412
413     //! Get a Hash of all buffer activity states
414     /** This Method is called when the Quassel Core is started to restore the BufferActivities
415      *  \note This method is threadsafe.
416      *
417      * \param user      The Owner of the buffers
418      */
419     virtual QHash<BufferId, Message::Types> bufferActivities(UserId id) = 0;
420
421     //! Get the bitset of buffer activity states for a buffer
422     /** This method is used to load the activity state of a buffer when its last seen message changes.
423      *  \note This method is threadsafe.
424      *
425      * \param bufferId The buffer
426      * \param lastSeenMsgId     The last seen message
427      */
428     virtual Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) = 0;
429
430     //! Get a hash of buffers with their ciphers for a given network
431     /** The keys are channel names and values are ciphers (possibly empty)
432      *  \note This method is threadsafe
433      *
434      *  \param user       The id of the networks owner
435      *  \param networkId  The Id of the network
436      */
437     virtual QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId) = 0;
438
439     //! Update the cipher of a buffer
440     /** \note This method is threadsafe
441      *
442      *  \param user        The Id of the networks owner
443      *  \param networkId   The Id of the network
444      *  \param bufferName The Cname of the buffer
445      *  \param cipher      The cipher for the buffer
446      */
447     virtual void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) = 0;
448
449     //! Update the highlight count for a Buffer
450     /** This Method is used to make the activity state of a Buffer persistent
451      *  \note This method is threadsafe.
452      *
453      * \param user      The Owner of that Buffer
454      * \param bufferId  The buffer id
455      * \param MsgId     The Message id where the marker line should be placed
456      */
457     virtual void setHighlightCount(UserId id, BufferId bufferId, int count) = 0;
458
459     //! Get a Hash of all highlight count states
460     /** This Method is called when the Quassel Core is started to restore the HighlightCounts
461      *  \note This method is threadsafe.
462      *
463      * \param user      The Owner of the buffers
464      */
465     virtual QHash<BufferId, int> highlightCounts(UserId id) = 0;
466
467     //! Get the highlight count states for a buffer
468     /** This method is used to load the activity state of a buffer when its last seen message changes.
469      *  \note This method is threadsafe.
470      *
471      * \param bufferId The buffer
472      * \param lastSeenMsgId     The last seen message
473      */
474     virtual int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) = 0;
475
476     /* Message handling */
477
478     //! Store a Message in the storage backend and set its unique Id.
479     /** \param msg  The message object to be stored
480      *  \return true on success
481      */
482     virtual bool logMessage(Message &msg) = 0;
483
484     //! Store a list of Messages in the storage backend and set their unique Id.
485     /** \param msgs The list message objects to be stored
486      *  \return true on success
487      */
488     virtual bool logMessages(MessageList &msgs) = 0;
489
490     //! Request a certain number messages stored in a given buffer.
491     /** \param buffer   The buffer we request messages from
492      *  \param first    if != -1 return only messages with a MsgId >= first
493      *  \param last     if != -1 return only messages with a MsgId < last
494      *  \param limit    if != -1 limit the returned list to a max of \limit entries
495      *  \return The requested list of messages
496      */
497     virtual QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1) = 0;
498
499     //! Request a certain number messages stored in a given buffer, matching certain filters
500     /** \param buffer   The buffer we request messages from
501      *  \param first    if != -1 return only messages with a MsgId >= first
502      *  \param last     if != -1 return only messages with a MsgId < last
503      *  \param limit    if != -1 limit the returned list to a max of \limit entries
504      *  \param type     The Message::Types that should be returned
505      *  \return The requested list of messages
506      */
507     virtual QList<Message> requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1,
508                                                int limit = -1, Message::Types type = Message::Types{-1},
509                                                Message::Flags flags = Message::Flags{-1}) = 0;
510
511     //! Request a certain number of messages across all buffers
512     /** \param first    if != -1 return only messages with a MsgId >= first
513      *  \param last     if != -1 return only messages with a MsgId < last
514      *  \param limit    Max amount of messages
515      *  \return The requested list of messages
516      */
517     virtual QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1) = 0;
518
519     //! Request a certain number of messages across all buffers, matching certain filters
520     /** \param first    if != -1 return only messages with a MsgId >= first
521      *  \param last     if != -1 return only messages with a MsgId < last
522      *  \param limit    Max amount of messages
523      *  \param type     The Message::Types that should be returned
524      *  \return The requested list of messages
525      */
526     virtual QList<Message> requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1,
527                                                   Message::Types type = Message::Types{-1},
528                                                   Message::Flags flags = Message::Flags{-1}) = 0;
529
530     //! Fetch all authusernames
531     /** \return      Map of all current UserIds to permitted idents
532      */
533     virtual QMap<UserId, QString> getAllAuthUserNames() = 0;
534
535 signals:
536     //! Sent when a new BufferInfo is created, or an existing one changed somehow.
537     void bufferInfoUpdated(UserId user, const BufferInfo &);
538     //! Sent when a Buffer was renamed
539     void bufferRenamed(const QString &newName, const QString &oldName);
540     //! Sent when a new user has been added
541     void userAdded(UserId, const QString &username);
542     //! Sent when a user has been renamed
543     void userRenamed(UserId, const QString &newname);
544     //! Sent when a user has been removed
545     void userRemoved(UserId);
546
547     //! Emitted when database schema upgrade starts or ends
548     void dbUpgradeInProgress(bool inProgress);
549
550 protected:
551     QString hashPassword(const QString &password);
552     bool checkHashedPassword(const UserId user, const QString &password, const QString &hashedPassword, const Storage::HashVersion version);
553
554 private:
555     QString hashPasswordSha1(const QString &password);
556     bool checkHashedPasswordSha1(const QString &password, const QString &hashedPassword);
557
558     QString hashPasswordSha2_512(const QString &password);
559     bool checkHashedPasswordSha2_512(const QString &password, const QString &hashedPassword);
560     QString sha2_512(const QString &input);
561 };
562
563
564 #endif