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