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