Semi-yearly copyright bump
[quassel.git] / src / core / corenetwork.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 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     /**
105      * Gets whether or not a disconnect was expected.
106      *
107      * Distinguishes desired quits from unexpected disconnections such as socket errors or timeouts.
108      *
109      * @return True if disconnect was requested, otherwise false.
110      */
111     inline bool disconnectExpected() const { return _disconnectExpected; }
112
113     QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator);
114
115     // IRCv3 capability negotiation
116
117     /**
118      * Checks if capability negotiation is currently ongoing.
119      *
120      * @returns True if in progress, otherwise false
121      */
122     inline bool capNegotiationInProgress() const { return (!_capsQueuedIndividual.empty() ||
123                                                            !_capsQueuedBundled.empty()); }
124
125     /**
126      * Queues a capability to be requested.
127      *
128      * Adds to the list of capabilities being requested.  If non-empty, CAP REQ messages are sent
129      * to the IRC server.  This may happen at login or if capabilities are announced via CAP NEW.
130      *
131      * @param[in] capability Name of the capability
132      */
133     void queueCap(const QString &capability);
134
135     /**
136      * Begins capability negotiation if capabilities are queued, otherwise returns.
137      *
138      * If any capabilities are queued, this will begin the cycle of taking each capability and
139      * requesting it.  When no capabilities remain, capability negotiation is suitably ended.
140      */
141     void beginCapNegotiation();
142
143     /**
144      * Ends capability negotiation.
145      *
146      * This won't have effect if other CAP commands are in the command queue before calling this
147      * command.  It should only be called when capability negotiation is complete.
148      */
149     void endCapNegotiation();
150
151     /**
152      * Queues the most recent capability set for retrying individually.
153      *
154      * Retries the most recent bundle of capabilities one at a time instead of as a group, working
155      * around the issue that IRC servers can deny a group of requested capabilities without
156      * indicating which capabilities failed.
157      *
158      * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
159      *
160      * This does NOT call CoreNetwork::sendNextCap().  Call that when ready afterwards.  Does
161      * nothing if the last capability tried was individual instead of a set.
162      */
163     void retryCapsIndividually();
164
165     /**
166      * List of capabilities requiring further core<->server messages to configure.
167      *
168      * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
169      * be immediately sent.
170      *
171      * Any capabilities in this list must call CoreNetwork::sendNextCap() on their own and they will
172      * not be batched together with other capabilities.
173      *
174      * See: http://ircv3.net/specs/extensions/sasl-3.2.html
175      */
176     const QStringList capsRequiringConfiguration = QStringList {
177         IrcCap::SASL
178     };
179
180 public slots:
181     virtual void setMyNick(const QString &mynick);
182
183     virtual void requestConnect() const;
184     virtual void requestDisconnect() const;
185     virtual void requestSetNetworkInfo(const NetworkInfo &info);
186
187     virtual void setUseAutoReconnect(bool);
188     virtual void setAutoReconnectInterval(quint32);
189     virtual void setAutoReconnectRetries(quint16);
190
191     void setPingInterval(int interval);
192
193     void connectToIrc(bool reconnecting = false);
194     /**
195      * Disconnect from the IRC server.
196      *
197      * Begin disconnecting from the IRC server, including optionally reconnecting.
198      *
199      * @param requested       If true, user requested this disconnect; don't try to reconnect
200      * @param reason          Reason for quitting, defaulting to the user-configured quit reason
201      * @param withReconnect   Reconnect to the network after disconnecting (e.g. ping timeout)
202      * @param forceImmediate  Immediately disconnect from network, skipping queue of other commands
203      */
204     void disconnectFromIrc(bool requested = true, const QString &reason = QString(),
205                            bool withReconnect = false, bool forceImmediate = false);
206
207     /**
208      * Forcibly close the IRC server socket, waiting for it to close.
209      *
210      * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
211      * be sure the network's disconencted (e.g. clean-up), call this.
212      *
213      * @param msecs  Maximum time to wait for socket to close, in milliseconds.
214      * @return True if socket closes successfully; false if error occurs or timeout reached
215      */
216     bool forceDisconnect(int msecs = 1000);
217
218     void userInput(BufferInfo bufferInfo, QString msg);
219
220     /**
221      * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
222      *
223      * @param[in] input   QByteArray of encoded characters
224      * @param[in] prepend
225      * @parmblock
226      * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
227      * end.  This should be used sparingly, for if either the core or the IRC server cannot maintain
228      * PING/PONG replies, the other side will close the connection.
229      * @endparmblock
230      */
231     void putRawLine(const QByteArray input, const bool prepend = false);
232
233     /**
234      * Sends the command with encoded parameters, with optional prefix or high priority.
235      *
236      * @param[in] cmd      Command to send, ignoring capitalization
237      * @param[in] params   Parameters for the command, encoded within a QByteArray
238      * @param[in] prefix   Optional command prefix
239      * @param[in] prepend
240      * @parmblock
241      * If true, the command is prepended into the start of the queue, otherwise, it's appended to
242      * the end.  This should be used sparingly, for if either the core or the IRC server cannot
243      * maintain PING/PONG replies, the other side will close the connection.
244      * @endparmblock
245      */
246     void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray(), const bool prepend = false);
247
248     /**
249      * Sends the command for each set of encoded parameters, with optional prefix or high priority.
250      *
251      * @param[in] cmd         Command to send, ignoring capitalization
252      * @param[in] params
253      * @parmblock
254      * List of parameter lists for the command, encoded within a QByteArray.  The command will be
255      * sent multiple times, once for each set of params stored within the outer list.
256      * @endparmblock
257      * @param[in] prefix      Optional command prefix
258      * @param[in] prependAll
259      * @parmblock
260      * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
261      * appended to the end.  This should be used sparingly, for if either the core or the IRC server
262      * cannot maintain PING/PONG replies, the other side will close the connection.
263      * @endparmblock
264      */
265     void putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix = QByteArray(), const bool prependAll = false);
266
267     void setChannelJoined(const QString &channel);
268     void setChannelParted(const QString &channel);
269     void addChannelKey(const QString &channel, const QString &key);
270     void removeChannelKey(const QString &channel);
271
272     // Blowfish stuff
273 #ifdef HAVE_QCA2
274     Cipher *cipher(const QString &recipient);
275     QByteArray cipherKey(const QString &recipient) const;
276     void setCipherKey(const QString &recipient, const QByteArray &key);
277     bool cipherUsesCBC(const QString &target);
278 #endif
279
280     // Custom rate limiting (can be connected to signals)
281
282     /**
283      * Update rate limiting according to Network configuration
284      *
285      * Updates the token bucket and message queue timer according to the network configuration, such
286      * as on first load, or after changing settings.
287      *
288      * Calling this will reset any ongoing queue delays.  If messages exist in the queue when rate
289      * limiting is disabled, messages will be quickly sent (100 ms) with new messages queued to send
290      * until the queue is cleared.
291      *
292      * @see Network::useCustomMessageRate()
293      * @see Network::messageRateBurstSize()
294      * @see Network::messageRateDelay()
295      * @see Network::unlimitedMessageRate()
296      *
297      * @param[in] forceUnlimited
298      * @parmblock
299      * If true, override user settings to disable message rate limiting, otherwise apply rate limits
300      * set by the user.  Use with caution and remember to re-enable configured limits when done.
301      * @endparmblock
302      */
303     void updateRateLimiting(const bool forceUnlimited = false);
304
305     /**
306      * Resets the token bucket up to the maximum
307      *
308      * Call this if the connection's been reset after calling updateRateLimiting() if needed.
309      *
310      * @see CoreNetwork::updateRateLimiting()
311      */
312     void resetTokenBucket();
313
314     // IRCv3 capability negotiation (can be connected to signals)
315
316     /**
317      * Indicates a capability is now available, with optional value in Network::capValue().
318      *
319      * @see Network::addCap()
320      *
321      * @param[in] capability Name of the capability
322      */
323     void serverCapAdded(const QString &capability);
324
325     /**
326      * Indicates a capability was acknowledged (enabled by the IRC server).
327      *
328      * @see Network::acknowledgeCap()
329      *
330      * @param[in] capability Name of the capability
331      */
332     void serverCapAcknowledged(const QString &capability);
333
334     /**
335      * Indicates a capability was removed from the list of available capabilities.
336      *
337      * @see Network::removeCap()
338      *
339      * @param[in] capability Name of the capability
340      */
341     void serverCapRemoved(const QString &capability);
342
343     /**
344      * Sends the next capability from the queue.
345      *
346      * During nick registration if any capabilities remain queued, this will take the next and
347      * request it.  When no capabilities remain, capability negotiation is ended.
348      */
349     void sendNextCap();
350
351     void setAutoWhoEnabled(bool enabled);
352     void setAutoWhoInterval(int interval);
353     void setAutoWhoDelay(int delay);
354
355     /**
356      * Appends the given channel/nick to the front of the AutoWho queue.
357      *
358      * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
359      * who-cycles are disabled as per IRCv3 specifications.
360      *
361      * @param[in] channelOrNick Channel or nickname to WHO
362      */
363     void queueAutoWhoOneshot(const QString &channelOrNick);
364
365     bool setAutoWhoDone(const QString &channel);
366
367     void updateIssuedModes(const QString &requestedModes);
368     void updatePersistentModes(QString addModes, QString removeModes);
369     void resetPersistentModes();
370
371     Server usedServer() const;
372
373     inline void resetPingTimeout() { _pingCount = 0; }
374
375     inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
376     {
377         emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
378     }
379
380
381 signals:
382     void recvRawServerMsg(QString);
383     void displayStatusMsg(QString);
384     void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
385     void disconnected(NetworkId networkId);
386     void connectionError(const QString &errorMsg);
387
388     void quitRequested(NetworkId networkId);
389     void sslErrors(const QVariant &errorData);
390
391     void newEvent(Event *event);
392     void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
393     void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
394
395 protected:
396     inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
397     inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
398
399 protected slots:
400     // TODO: remove cached cipher keys, when appropriate
401     //virtual void removeIrcUser(IrcUser *ircuser);
402     //virtual void removeIrcChannel(IrcChannel *ircChannel);
403     //virtual void removeChansAndUsers();
404
405 private slots:
406     void socketHasData();
407     void socketError(QAbstractSocket::SocketError);
408     void socketInitialized();
409     inline void socketCloseTimeout() { socket.abort(); }
410     void socketDisconnected();
411     void socketStateChanged(QAbstractSocket::SocketState);
412     void networkInitialized();
413
414     void sendPerform();
415     void restoreUserModes();
416     void doAutoReconnect();
417     void sendPing();
418     void enablePingTimeout(bool enable = true);
419     void disablePingTimeout();
420     void sendAutoWho();
421     void startAutoWhoCycle();
422
423 #ifdef HAVE_SSL
424     void sslErrors(const QList<QSslError> &errors);
425 #endif
426
427     /**
428      * Check the message token bucket
429      *
430      * If rate limiting is disabled and the message queue is empty, this disables the token bucket
431      * timer.  Otherwise, a queued message will be sent.
432      *
433      * @see CoreNetwork::fillBucketAndProcessQueue()
434      */
435     void checkTokenBucket();
436
437     /**
438      * Top up token bucket and send as many queued messages as possible
439      *
440      * If there's any room for more tokens, add to the token bucket.  Separately, if there's any
441      * messages to send, send until there's no more tokens or the queue is empty, whichever comes
442      * first.
443      */
444     void fillBucketAndProcessQueue();
445
446     void writeToSocket(const QByteArray &data);
447
448 private:
449     CoreSession *_coreSession;
450
451 #ifdef HAVE_SSL
452     QSslSocket socket;
453 #else
454     QTcpSocket socket;
455 #endif
456
457     CoreUserInputHandler *_userInputHandler;
458
459     QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
460
461     QTimer _autoReconnectTimer;
462     int _autoReconnectCount;
463
464     QTimer _socketCloseTimer;
465
466     /* this flag triggers quitRequested() once the socket is closed
467      * it is needed to determine whether or not the connection needs to be
468      * in the automatic session restore. */
469     bool _quitRequested;
470     QString _quitReason;
471
472     bool _disconnectExpected;  /// If true, connection is quitting, expect a socket close
473     // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
474     // specifying a permanent (saved to core session) disconnect.
475
476     bool _previousConnectionAttemptFailed;
477     int _lastUsedServerIndex;
478
479     QTimer _pingTimer;
480     uint _lastPingTime;
481     uint _pingCount;
482     bool _sendPings;
483
484     QStringList _autoWhoQueue;
485     QHash<QString, int> _autoWhoPending;
486     QTimer _autoWhoTimer, _autoWhoCycleTimer;
487
488     // Maintain a list of CAPs that are being checked; if empty, negotiation finished
489     // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
490     QStringList _capsQueuedIndividual;  /// Capabilities to check that require one at a time requests
491     QStringList _capsQueuedBundled;     /// Capabilities to check that can be grouped together
492     QStringList _capsQueuedLastBundle;  /// Most recent capability bundle requested (no individuals)
493     // Some capabilities, such as SASL, require follow-up messages to be fully enabled.  These
494     // capabilities should not be grouped with others to avoid requesting new capabilities while the
495     // previous capability is still being set up.
496     // Additionally, IRC servers can choose to send a 'NAK' to any set of requested capabilities.
497     // If this happens, we need a way to retry each capability individually in order to avoid having
498     // one failing capability (e.g. SASL) block all other capabilities.
499
500     bool _capNegotiationActive;         /// Whether or not full capability negotiation was started
501     // Avoid displaying repeat "negotiation finished" messages
502     bool _capInitialNegotiationEnded;   /// Whether or not initial capability negotiation finished
503     // Avoid sending repeat "CAP END" replies when registration is already ended
504
505     /**
506      * Gets the next set of capabilities to request, removing them from the queue.
507      *
508      * May return one or multiple space-separated capabilities, depending on queue.
509      *
510      * @returns Space-separated names of capabilities to request, or empty string if none remain
511      */
512     QString takeQueuedCaps();
513
514     /**
515      * Maximum length of a single 'CAP REQ' command.
516      *
517      * To be safe, 100 chars.  Higher numbers should be possible; this is following the conservative
518      * minimum number of characters that IRC servers must return in CAP NAK replies.  This also
519      * means CAP NAK replies will contain the full list of denied capabilities.
520      *
521      * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
522      */
523     const int maxCapRequestLength = 100;
524
525     QTimer _tokenBucketTimer;
526     // No need for int type as one cannot travel into the past (at least not yet, Doc)
527     quint32 _messageDelay;       /// Token refill speed in ms
528     quint32 _burstSize;          /// Size of the token bucket
529     quint32 _tokenBucket;        /// The virtual bucket that holds the tokens
530     QList<QByteArray> _msgQueue; /// Queue of messages waiting to be sent
531     bool _skipMessageRates;      /// If true, skip all message rate limits
532
533     QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
534
535     // List of blowfish keys for channels
536     QHash<QString, QByteArray> _cipherKeys;
537 };
538
539
540 #endif //CORENETWORK_H