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