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