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