Batch request capabilities during negotiation
[quassel.git] / src / core / corenetwork.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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 CORENETWORK_H
22 #define CORENETWORK_H
23
24 #include "network.h"
25 #include "coreircchannel.h"
26 #include "coreircuser.h"
27
28 // IRCv3 capabilities
29 #include "irccap.h"
30
31 #include <QTimer>
32
33 #ifdef HAVE_SSL
34 # include <QSslSocket>
35 # include <QSslError>
36 #else
37 # include <QTcpSocket>
38 #endif
39
40 #ifdef HAVE_QCA2
41 #  include "cipher.h"
42 #endif
43
44 #include "coresession.h"
45
46 #include <functional>
47
48 class CoreIdentity;
49 class CoreUserInputHandler;
50 class CoreIgnoreListManager;
51 class Event;
52
53 class CoreNetwork : public Network
54 {
55     SYNCABLE_OBJECT
56         Q_OBJECT
57
58 public:
59     CoreNetwork(const NetworkId &networkid, CoreSession *session);
60     ~CoreNetwork();
61     inline virtual const QMetaObject *syncMetaObject() const { return &Network::staticMetaObject; }
62
63     inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); }
64     inline CoreSession *coreSession() const { return _coreSession; }
65     inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); }
66
67     inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; }
68     inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); }
69
70     //! Decode a string using the server (network) decoding.
71     inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); }
72
73     //! Decode a string using a channel-specific encoding if one is set (and use the standard encoding else).
74     QString channelDecode(const QString &channelName, const QByteArray &string) const;
75
76     //! Decode a string using an IrcUser-specific encoding, if one exists (using the standaed encoding else).
77     QString userDecode(const QString &userNick, const QByteArray &string) const;
78
79     //! Encode a string using the server (network) encoding.
80     inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); }
81
82     //! Encode a string using the channel-specific encoding, if set, and use the standard encoding else.
83     QByteArray channelEncode(const QString &channelName, const QString &string) const;
84
85     //! Encode a string using the user-specific encoding, if set, and use the standard encoding else.
86     QByteArray userEncode(const QString &userNick, const QString &string) const;
87
88     inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); }
89
90     inline QByteArray readChannelCipherKey(const QString &channel) const { return _cipherKeys.value(channel.toLower()); }
91     inline void storeChannelCipherKey(const QString &channel, const QByteArray &key) { _cipherKeys[channel.toLower()] = key; }
92
93     inline bool isAutoWhoInProgress(const QString &channel) const { return _autoWhoPending.value(channel.toLower(), 0); }
94
95     inline UserId userId() const { return _coreSession->user(); }
96
97     inline QAbstractSocket::SocketState socketState() const { return socket.state(); }
98     inline bool socketConnected() const { return socket.state() == QAbstractSocket::ConnectedState; }
99     inline QHostAddress localAddress() const { return socket.localAddress(); }
100     inline QHostAddress peerAddress() const { return socket.peerAddress(); }
101     inline quint16 localPort() const { return socket.localPort(); }
102     inline quint16 peerPort() const { return socket.peerPort(); }
103
104     QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator);
105
106     // IRCv3 capability negotiation
107
108     /**
109      * Checks if capability negotiation is currently ongoing.
110      *
111      * @returns True if in progress, otherwise false
112      */
113     inline bool capNegotiationInProgress() const { return (!_capsQueuedIndividual.empty() ||
114                                                            !_capsQueuedBundled.empty()); }
115
116     /**
117      * Queues a capability to be requested.
118      *
119      * Adds to the list of capabilities being requested.  If non-empty, CAP REQ messages are sent
120      * to the IRC server.  This may happen at login or if capabilities are announced via CAP NEW.
121      *
122      * @param[in] capability Name of the capability
123      */
124     void queueCap(const QString &capability);
125
126     /**
127      * Begins capability negotiation if capabilities are queued, otherwise returns.
128      *
129      * If any capabilities are queued, this will begin the cycle of taking each capability and
130      * requesting it.  When no capabilities remain, capability negotiation is suitably ended.
131      */
132     void beginCapNegotiation();
133
134     /**
135      * Ends capability negotiation.
136      *
137      * This won't have effect if other CAP commands are in the command queue before calling this
138      * command.  It should only be called when capability negotiation is complete.
139      */
140     void endCapNegotiation();
141
142     /**
143      * Queues the most recent capability set for retrying individually.
144      *
145      * Retries the most recent bundle of capabilities one at a time instead of as a group, working
146      * around the issue that IRC servers can deny a group of requested capabilities without
147      * indicating which capabilities failed.
148      *
149      * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
150      *
151      * This does NOT call CoreNetwork::sendNextCap().  Call that when ready afterwards.  Does
152      * nothing if the last capability tried was individual instead of a set.
153      */
154     void retryCapsIndividually();
155
156     /**
157      * List of capabilities requiring further core<->server messages to configure.
158      *
159      * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
160      * be immediately sent.
161      *
162      * Any capabilities in this list must call CoreNetwork::sendNextCap() on their own and they will
163      * not be batched together with other capabilities.
164      *
165      * See: http://ircv3.net/specs/extensions/sasl-3.2.html
166      */
167     const QStringList capsRequiringConfiguration = QStringList {
168         IrcCap::SASL
169     };
170
171 public slots:
172     virtual void setMyNick(const QString &mynick);
173
174     virtual void requestConnect() const;
175     virtual void requestDisconnect() const;
176     virtual void requestSetNetworkInfo(const NetworkInfo &info);
177
178     virtual void setUseAutoReconnect(bool);
179     virtual void setAutoReconnectInterval(quint32);
180     virtual void setAutoReconnectRetries(quint16);
181
182     void setPingInterval(int interval);
183
184     void connectToIrc(bool reconnecting = false);
185     /**
186      * Disconnect from the IRC server.
187      *
188      * Begin disconnecting from the IRC server, including optionally reconnecting.
189      *
190      * @param requested       If true, user requested this disconnect; don't try to reconnect
191      * @param reason          Reason for quitting, defaulting to the user-configured quit reason
192      * @param withReconnect   Reconnect to the network after disconnecting (e.g. ping timeout)
193      * @param forceImmediate  Immediately disconnect from network, skipping queue of other commands
194      */
195     void disconnectFromIrc(bool requested = true, const QString &reason = QString(),
196                            bool withReconnect = false, bool forceImmediate = false);
197
198     /**
199      * Forcibly close the IRC server socket, waiting for it to close.
200      *
201      * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
202      * be sure the network's disconencted (e.g. clean-up), call this.
203      *
204      * @param msecs  Maximum time to wait for socket to close, in milliseconds.
205      * @return True if socket closes successfully; false if error occurs or timeout reached
206      */
207     bool forceDisconnect(int msecs = 1000);
208
209     void userInput(BufferInfo bufferInfo, QString msg);
210
211     /**
212      * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
213      *
214      * @param[in] input   QByteArray of encoded characters
215      * @param[in] prepend
216      * @parmblock
217      * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
218      * end.  This should be used sparingly, for if either the core or the IRC server cannot maintain
219      * PING/PONG replies, the other side will close the connection.
220      * @endparmblock
221      */
222     void putRawLine(const QByteArray input, const bool prepend = false);
223
224     /**
225      * Sends the command with encoded parameters, with optional prefix or high priority.
226      *
227      * @param[in] cmd      Command to send, ignoring capitalization
228      * @param[in] params   Parameters for the command, encoded within a QByteArray
229      * @param[in] prefix   Optional command prefix
230      * @param[in] prepend
231      * @parmblock
232      * If true, the command is prepended into the start of the queue, otherwise, it's appended to
233      * the end.  This should be used sparingly, for if either the core or the IRC server cannot
234      * maintain PING/PONG replies, the other side will close the connection.
235      * @endparmblock
236      */
237     void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray(), const bool prepend = false);
238
239     /**
240      * Sends the command for each set of encoded parameters, with optional prefix or high priority.
241      *
242      * @param[in] cmd         Command to send, ignoring capitalization
243      * @param[in] params
244      * @parmblock
245      * List of parameter lists for the command, encoded within a QByteArray.  The command will be
246      * sent multiple times, once for each set of params stored within the outer list.
247      * @endparmblock
248      * @param[in] prefix      Optional command prefix
249      * @param[in] prependAll
250      * @parmblock
251      * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
252      * appended to the end.  This should be used sparingly, for if either the core or the IRC server
253      * cannot maintain PING/PONG replies, the other side will close the connection.
254      * @endparmblock
255      */
256     void putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix = QByteArray(), const bool prependAll = false);
257
258     void setChannelJoined(const QString &channel);
259     void setChannelParted(const QString &channel);
260     void addChannelKey(const QString &channel, const QString &key);
261     void removeChannelKey(const QString &channel);
262
263     // Blowfish stuff
264 #ifdef HAVE_QCA2
265     Cipher *cipher(const QString &recipient);
266     QByteArray cipherKey(const QString &recipient) const;
267     void setCipherKey(const QString &recipient, const QByteArray &key);
268     bool cipherUsesCBC(const QString &target);
269 #endif
270
271     // IRCv3 capability negotiation (can be connected to signals)
272
273     /**
274      * Indicates a capability is now available, with optional value in Network::capValue().
275      *
276      * @see Network::addCap()
277      *
278      * @param[in] capability Name of the capability
279      */
280     void serverCapAdded(const QString &capability);
281
282     /**
283      * Indicates a capability was acknowledged (enabled by the IRC server).
284      *
285      * @see Network::acknowledgeCap()
286      *
287      * @param[in] capability Name of the capability
288      */
289     void serverCapAcknowledged(const QString &capability);
290
291     /**
292      * Indicates a capability was removed from the list of available capabilities.
293      *
294      * @see Network::removeCap()
295      *
296      * @param[in] capability Name of the capability
297      */
298     void serverCapRemoved(const QString &capability);
299
300     /**
301      * Sends the next capability from the queue.
302      *
303      * During nick registration if any capabilities remain queued, this will take the next and
304      * request it.  When no capabilities remain, capability negotiation is ended.
305      */
306     void sendNextCap();
307
308     void setAutoWhoEnabled(bool enabled);
309     void setAutoWhoInterval(int interval);
310     void setAutoWhoDelay(int delay);
311
312     /**
313      * Appends the given channel/nick to the front of the AutoWho queue.
314      *
315      * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
316      * who-cycles are disabled as per IRCv3 specifications.
317      *
318      * @param[in] channelOrNick Channel or nickname to WHO
319      */
320     void queueAutoWhoOneshot(const QString &channelOrNick);
321
322     bool setAutoWhoDone(const QString &channel);
323
324     void updateIssuedModes(const QString &requestedModes);
325     void updatePersistentModes(QString addModes, QString removeModes);
326     void resetPersistentModes();
327
328     Server usedServer() const;
329
330     inline void resetPingTimeout() { _pingCount = 0; }
331
332     inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
333     {
334         emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
335     }
336
337
338 signals:
339     void recvRawServerMsg(QString);
340     void displayStatusMsg(QString);
341     void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
342     void disconnected(NetworkId networkId);
343     void connectionError(const QString &errorMsg);
344
345     void quitRequested(NetworkId networkId);
346     void sslErrors(const QVariant &errorData);
347
348     void newEvent(Event *event);
349     void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
350     void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
351
352 protected:
353     inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
354     inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
355
356 protected slots:
357     // TODO: remove cached cipher keys, when appropriate
358     //virtual void removeIrcUser(IrcUser *ircuser);
359     //virtual void removeIrcChannel(IrcChannel *ircChannel);
360     //virtual void removeChansAndUsers();
361
362 private slots:
363     void socketHasData();
364     void socketError(QAbstractSocket::SocketError);
365     void socketInitialized();
366     inline void socketCloseTimeout() { socket.abort(); }
367     void socketDisconnected();
368     void socketStateChanged(QAbstractSocket::SocketState);
369     void networkInitialized();
370
371     void sendPerform();
372     void restoreUserModes();
373     void doAutoReconnect();
374     void sendPing();
375     void enablePingTimeout(bool enable = true);
376     void disablePingTimeout();
377     void sendAutoWho();
378     void startAutoWhoCycle();
379
380 #ifdef HAVE_SSL
381     void sslErrors(const QList<QSslError> &errors);
382 #endif
383
384     void fillBucketAndProcessQueue();
385
386     void writeToSocket(const QByteArray &data);
387
388 private:
389     CoreSession *_coreSession;
390
391 #ifdef HAVE_SSL
392     QSslSocket socket;
393 #else
394     QTcpSocket socket;
395 #endif
396
397     CoreUserInputHandler *_userInputHandler;
398
399     QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
400
401     QTimer _autoReconnectTimer;
402     int _autoReconnectCount;
403
404     QTimer _socketCloseTimer;
405
406     /* this flag triggers quitRequested() once the socket is closed
407      * it is needed to determine whether or not the connection needs to be
408      * in the automatic session restore. */
409     bool _quitRequested;
410     QString _quitReason;
411
412     bool _disconnectExpected;  /// If true, connection is quitting, expect a socket close
413     // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
414     // specifying a permanent (saved to core session) disconnect.
415
416     bool _previousConnectionAttemptFailed;
417     int _lastUsedServerIndex;
418
419     QTimer _pingTimer;
420     uint _lastPingTime;
421     uint _pingCount;
422     bool _sendPings;
423
424     QStringList _autoWhoQueue;
425     QHash<QString, int> _autoWhoPending;
426     QTimer _autoWhoTimer, _autoWhoCycleTimer;
427
428     // Maintain a list of CAPs that are being checked; if empty, negotiation finished
429     // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
430     QStringList _capsQueuedIndividual;  /// Capabilities to check that require one at a time requests
431     QStringList _capsQueuedBundled;     /// Capabilities to check that can be grouped together
432     QStringList _capsQueuedLastBundle;  /// Most recent capability bundle requested (no individuals)
433     // Some capabilities, such as SASL, require follow-up messages to be fully enabled.  These
434     // capabilities should not be grouped with others to avoid requesting new capabilities while the
435     // previous capability is still being set up.
436     // Additionally, IRC servers can choose to send a 'NAK' to any set of requested capabilities.
437     // If this happens, we need a way to retry each capability individually in order to avoid having
438     // one failing capability (e.g. SASL) block all other capabilities.
439
440     bool _capNegotiationActive;         /// Whether or not full capability negotiation was started
441     // Avoid displaying repeat "negotiation finished" messages
442     bool _capInitialNegotiationEnded;   /// Whether or not initial capability negotiation finished
443     // Avoid sending repeat "CAP END" replies when registration is already ended
444
445     /**
446      * Gets the next set of capabilities to request, removing them from the queue.
447      *
448      * May return one or multiple space-separated capabilities, depending on queue.
449      *
450      * @returns Space-separated names of capabilities to request, or empty string if none remain
451      */
452     QString takeQueuedCaps();
453
454     /**
455      * Maximum length of a single 'CAP REQ' command.
456      *
457      * To be safe, 100 chars.  Higher numbers should be possible; this is following the conservative
458      * minimum number of characters that IRC servers must return in CAP NAK replies.  This also
459      * means CAP NAK replies will contain the full list of denied capabilities.
460      *
461      * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
462      */
463     const int maxCapRequestLength = 100;
464
465     QTimer _tokenBucketTimer;
466     int _messageDelay;      // token refill speed in ms
467     int _burstSize;         // size of the token bucket
468     int _tokenBucket;       // the virtual bucket that holds the tokens
469     QList<QByteArray> _msgQueue;
470
471     QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
472
473     // List of blowfish keys for channels
474     QHash<QString, QByteArray> _cipherKeys;
475 };
476
477
478 #endif //CORENETWORK_H