bcab1df7408d99d9273e410bb38541f94c9075b6
[quassel.git] / src / core / corenetwork.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2019 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #pragma once
22
23 #include <functional>
24
25 #include <QTimer>
26
27 #ifdef HAVE_SSL
28 #    include <QSslError>
29 #    include <QSslSocket>
30 #else
31 #    include <QTcpSocket>
32 #endif
33
34 #ifdef HAVE_QCA2
35 #    include "cipher.h"
36 #endif
37
38 #include "coreircchannel.h"
39 #include "coreircuser.h"
40 #include "coresession.h"
41 #include "irccap.h"
42 #include "irctag.h"
43 #include "network.h"
44
45 class CoreIdentity;
46 class CoreUserInputHandler;
47 class CoreIgnoreListManager;
48 class Event;
49
50 class CoreNetwork : public Network
51 {
52     Q_OBJECT
53
54 public:
55     CoreNetwork(const NetworkId& networkid, CoreSession* session);
56     ~CoreNetwork() override;
57
58     inline CoreIdentity* identityPtr() const { return coreSession()->identity(identity()); }
59     inline CoreSession* coreSession() const { return _coreSession; }
60     inline CoreNetworkConfig* networkConfig() const { return coreSession()->networkConfig(); }
61
62     inline CoreUserInputHandler* userInputHandler() const { return _userInputHandler; }
63     inline CoreIgnoreListManager* ignoreListManager() { return coreSession()->ignoreListManager(); }
64
65     //! Decode a string using the server (network) decoding.
66     inline QString serverDecode(const QByteArray& string) const { return decodeServerString(string); }
67
68     //! Decode a string using a channel-specific encoding if one is set (and use the standard encoding else).
69     QString channelDecode(const QString& channelName, const QByteArray& string) const;
70
71     //! Decode a string using an IrcUser-specific encoding, if one exists (using the standaed encoding else).
72     QString userDecode(const QString& userNick, const QByteArray& string) const;
73
74     //! Encode a string using the server (network) encoding.
75     inline QByteArray serverEncode(const QString& string) const { return encodeServerString(string); }
76
77     //! Encode a string using the channel-specific encoding, if set, and use the standard encoding else.
78     QByteArray channelEncode(const QString& channelName, const QString& string) const;
79
80     //! Encode a string using the user-specific encoding, if set, and use the standard encoding else.
81     QByteArray userEncode(const QString& userNick, const QString& string) const;
82
83     inline QString channelKey(const QString& channel) const { return _channelKeys.value(channel.toLower(), QString()); }
84
85     inline QByteArray readChannelCipherKey(const QString& channel) const { return _cipherKeys.value(channel.toLower()); }
86     inline void storeChannelCipherKey(const QString& channel, const QByteArray& key) { _cipherKeys[channel.toLower()] = key; }
87
88     /**
89      * Checks if the given target has an automatic WHO in progress
90      *
91      * @param name Channel or nickname
92      * @return True if an automatic WHO is in progress, otherwise false
93      */
94     inline bool isAutoWhoInProgress(const QString& name) const { return _autoWhoPending.value(name.toLower(), 0); }
95
96     inline UserId userId() const { return _coreSession->user(); }
97
98     inline QAbstractSocket::SocketState socketState() const { return socket.state(); }
99     inline bool socketConnected() const { return socket.state() == QAbstractSocket::ConnectedState; }
100     inline QHostAddress localAddress() const { return socket.localAddress(); }
101     inline QHostAddress peerAddress() const { return socket.peerAddress(); }
102     inline quint16 localPort() const { return socket.localPort(); }
103     inline quint16 peerPort() const { return socket.peerPort(); }
104
105     /**
106      * Gets whether or not a disconnect was expected.
107      *
108      * Distinguishes desired quits from unexpected disconnections such as socket errors or timeouts.
109      *
110      * @return True if disconnect was requested, otherwise false.
111      */
112     inline bool disconnectExpected() const { return _disconnectExpected; }
113
114     /**
115      * Gets whether or not the server replies to automated PINGs with a valid timestamp
116      *
117      * Distinguishes between servers that reply by quoting the text sent, and those that respond
118      * with whatever they want.
119      *
120      * @return True if a valid timestamp has been received as a PONG, otherwise false.
121      */
122     inline bool isPongTimestampValid() const { return _pongTimestampValid; }
123
124     /**
125      * Gets whether or not an automated PING has been sent without any PONG received
126      *
127      * Reset whenever any PONG is received, not just the automated one sent.
128      *
129      * @return True if a PING has been sent without a PONG received, otherwise false.
130      */
131     inline bool isPongReplyPending() const { return _pongReplyPending; }
132
133     QList<QList<QByteArray>> splitMessage(const QString& cmd,
134                                           const QString& message,
135                                           const std::function<QList<QByteArray>(QString&)>& cmdGenerator);
136
137     // IRCv3 capability negotiation
138
139     /**
140      * Checks if capability negotiation is currently ongoing.
141      *
142      * @returns True if in progress, otherwise false
143      */
144     inline bool capNegotiationInProgress() const { return (!_capsQueuedIndividual.empty() || !_capsQueuedBundled.empty()); }
145
146     /**
147      * Queues a capability to be requested.
148      *
149      * Adds to the list of capabilities being requested.  If non-empty, CAP REQ messages are sent
150      * to the IRC server.  This may happen at login or if capabilities are announced via CAP NEW.
151      *
152      * @param[in] capability Name of the capability
153      */
154     void queueCap(const QString& capability);
155
156     /**
157      * Begins capability negotiation if capabilities are queued, otherwise returns.
158      *
159      * If any capabilities are queued, this will begin the cycle of taking each capability and
160      * requesting it.  When no capabilities remain, capability negotiation is suitably ended.
161      */
162     void beginCapNegotiation();
163
164     /**
165      * Ends capability negotiation.
166      *
167      * This won't have effect if other CAP commands are in the command queue before calling this
168      * command.  It should only be called when capability negotiation is complete.
169      */
170     void endCapNegotiation();
171
172     /**
173      * Queues the most recent capability set for retrying individually.
174      *
175      * Retries the most recent bundle of capabilities one at a time instead of as a group, working
176      * around the issue that IRC servers can deny a group of requested capabilities without
177      * indicating which capabilities failed.
178      *
179      * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
180      *
181      * This does NOT call CoreNetwork::sendNextCap().  Call that when ready afterwards.  Does
182      * nothing if the last capability tried was individual instead of a set.
183      */
184     void retryCapsIndividually();
185
186     /**
187      * List of capabilities requiring further core<->server messages to configure.
188      *
189      * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
190      * be immediately sent.
191      *
192      * Any capabilities in this list must call CoreNetwork::sendNextCap() on their own and they will
193      * not be batched together with other capabilities.
194      *
195      * See: http://ircv3.net/specs/extensions/sasl-3.2.html
196      */
197     const QStringList capsRequiringConfiguration = QStringList{IrcCap::SASL};
198
199 public slots:
200     void setMyNick(const QString& mynick) override;
201
202     void requestConnect() const override;
203     void requestDisconnect() const override;
204     void requestSetNetworkInfo(const NetworkInfo& info) override;
205
206     void setUseAutoReconnect(bool) override;
207     void setAutoReconnectInterval(quint32) override;
208     void setAutoReconnectRetries(quint16) override;
209
210     void setPingInterval(int interval);
211
212     /**
213      * Sets whether or not the IRC server has replied to PING with a valid timestamp
214      *
215      * This allows determining whether or not an IRC server responds to PING with a PONG that quotes
216      * what was sent, or if it does something else (and therefore PONGs should be more aggressively
217      * hidden).
218      *
219      * @param timestampValid If true, a valid timestamp has been received via PONG reply
220      */
221     void setPongTimestampValid(bool validTimestamp);
222
223     /**
224      * Indicates that the CoreSession is shutting down.
225      *
226      * Disconnects the network if connected, and sets a flag that prevents reconnections.
227      */
228     void shutdown();
229
230     void connectToIrc(bool reconnecting = false);
231     /**
232      * Disconnect from the IRC server.
233      *
234      * Begin disconnecting from the IRC server, including optionally reconnecting.
235      *
236      * @param requested       If true, user requested this disconnect; don't try to reconnect
237      * @param reason          Reason for quitting, defaulting to the user-configured quit reason
238      * @param withReconnect   Reconnect to the network after disconnecting (e.g. ping timeout)
239      */
240     void disconnectFromIrc(bool requested = true, const QString& reason = QString(), bool withReconnect = false);
241
242     /**
243      * Forcibly close the IRC server socket, waiting for it to close.
244      *
245      * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
246      * be sure the network's disconnected (e.g. clean-up), call this.
247      *
248      * @param msecs  Maximum time to wait for socket to close, in milliseconds.
249      * @return True if socket closes successfully; false if error occurs or timeout reached
250      */
251     bool forceDisconnect(int msecs = 1000);
252
253     void userInput(const BufferInfo& bufferInfo, QString msg);
254
255     /**
256      * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
257      *
258      * @param[in] input   QByteArray of encoded characters
259      * @param[in] prepend
260      * @parmblock
261      * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
262      * end.  This should be used sparingly, for if either the core or the IRC server cannot maintain
263      * PING/PONG replies, the other side will close the connection.
264      * @endparmblock
265      */
266     void putRawLine(const QByteArray& input, bool prepend = false);
267
268     /**
269      * Sends the command with encoded parameters, with optional prefix or high priority.
270      *
271      * @param[in] cmd      Command to send, ignoring capitalization
272      * @param[in] params   Parameters for the command, encoded within a QByteArray
273      * @param[in] prefix   Optional command prefix
274      * @param[in] prepend
275      * @parmblock
276      * If true, the command is prepended into the start of the queue, otherwise, it's appended to
277      * the end.  This should be used sparingly, for if either the core or the IRC server cannot
278      * maintain PING/PONG replies, the other side will close the connection.
279      * @endparmblock
280      */
281     void putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix = {}, const QHash<IrcTagKey, QString> &tags = {}, bool prepend = false);
282
283     /**
284      * Sends the command for each set of encoded parameters, with optional prefix or high priority.
285      *
286      * @param[in] cmd         Command to send, ignoring capitalization
287      * @param[in] params
288      * @parmblock
289      * List of parameter lists for the command, encoded within a QByteArray.  The command will be
290      * sent multiple times, once for each set of params stored within the outer list.
291      * @endparmblock
292      * @param[in] prefix      Optional command prefix
293      * @param[in] prependAll
294      * @parmblock
295      * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
296      * appended to the end.  This should be used sparingly, for if either the core or the IRC server
297      * cannot maintain PING/PONG replies, the other side will close the connection.
298      * @endparmblock
299      */
300     void putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix = {}, const QHash<IrcTagKey, QString> &tags = {}, bool prependAll = false);
301
302     void setChannelJoined(const QString& channel);
303     void setChannelParted(const QString& channel);
304     void addChannelKey(const QString& channel, const QString& key);
305     void removeChannelKey(const QString& channel);
306
307     // Blowfish stuff
308 #ifdef HAVE_QCA2
309     Cipher* cipher(const QString& recipient);
310     QByteArray cipherKey(const QString& recipient) const;
311     void setCipherKey(const QString& recipient, const QByteArray& key);
312     bool cipherUsesCBC(const QString& target);
313 #endif
314
315     // Custom rate limiting (can be connected to signals)
316
317     /**
318      * Update rate limiting according to Network configuration
319      *
320      * Updates the token bucket and message queue timer according to the network configuration, such
321      * as on first load, or after changing settings.
322      *
323      * Calling this will reset any ongoing queue delays.  If messages exist in the queue when rate
324      * limiting is disabled, messages will be quickly sent (100 ms) with new messages queued to send
325      * until the queue is cleared.
326      *
327      * @see Network::useCustomMessageRate()
328      * @see Network::messageRateBurstSize()
329      * @see Network::messageRateDelay()
330      * @see Network::unlimitedMessageRate()
331      *
332      * @param[in] forceUnlimited
333      * @parmblock
334      * If true, override user settings to disable message rate limiting, otherwise apply rate limits
335      * set by the user.  Use with caution and remember to re-enable configured limits when done.
336      * @endparmblock
337      */
338     void updateRateLimiting(bool forceUnlimited = false);
339
340     /**
341      * Resets the token bucket up to the maximum
342      *
343      * Call this if the connection's been reset after calling updateRateLimiting() if needed.
344      *
345      * @see CoreNetwork::updateRateLimiting()
346      */
347     void resetTokenBucket();
348
349     // IRCv3 capability negotiation (can be connected to signals)
350
351     /**
352      * Indicates a capability is now available, with optional value in Network::capValue().
353      *
354      * @see Network::addCap()
355      *
356      * @param[in] capability Name of the capability
357      */
358     void serverCapAdded(const QString& capability);
359
360     /**
361      * Indicates a capability was acknowledged (enabled by the IRC server).
362      *
363      * @see Network::acknowledgeCap()
364      *
365      * @param[in] capability Name of the capability
366      */
367     void serverCapAcknowledged(const QString& capability);
368
369     /**
370      * Indicates a capability was removed from the list of available capabilities.
371      *
372      * @see Network::removeCap()
373      *
374      * @param[in] capability Name of the capability
375      */
376     void serverCapRemoved(const QString& capability);
377
378     /**
379      * Sends the next capability from the queue.
380      *
381      * During nick registration if any capabilities remain queued, this will take the next and
382      * request it.  When no capabilities remain, capability negotiation is ended.
383      */
384     void sendNextCap();
385
386     void setAutoWhoEnabled(bool enabled);
387     void setAutoWhoInterval(int interval);
388     void setAutoWhoDelay(int delay);
389
390     /**
391      * Appends the given channel/nick to the front of the AutoWho queue.
392      *
393      * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
394      * who-cycles are disabled as per IRCv3 specifications.
395      *
396      * @param[in] name Channel or nickname
397      */
398     void queueAutoWhoOneshot(const QString& name);
399
400     /**
401      * Checks if the given target has an automatic WHO in progress, and sets it as done if so
402      *
403      * @param name Channel or nickname
404      * @return True if an automatic WHO is in progress (and should be silenced), otherwise false
405      */
406     bool setAutoWhoDone(const QString& name);
407
408     void updateIssuedModes(const QString& requestedModes);
409     void updatePersistentModes(QString addModes, QString removeModes);
410     void resetPersistentModes();
411
412     Server usedServer() const;
413
414     inline void resetPingTimeout() { _pingCount = 0; }
415
416     /**
417      * Marks the network as no longer having a pending reply to an automated PING
418      */
419     inline void resetPongReplyPending() { _pongReplyPending = false; }
420
421     void onDisplayMsg(const NetworkInternalMessage& msg)
422     {
423         emit displayMsg(RawMessage(networkId(), msg));
424     }
425
426 signals:
427     void recvRawServerMsg(const QString&);
428     void displayStatusMsg(const QString&);
429     void displayMsg(const RawMessage& msg);
430     void disconnected(NetworkId networkId);
431     void connectionError(const QString& errorMsg);
432
433     void quitRequested(NetworkId networkId);
434     void sslErrors(const QVariant& errorData);
435
436     void newEvent(Event* event);
437     void socketInitialized(const CoreIdentity* identity,
438                            const QHostAddress& localAddress,
439                            quint16 localPort,
440                            const QHostAddress& peerAddress,
441                            quint16 peerPort,
442                            qint64 socketId);
443     void socketDisconnected(const CoreIdentity* identity,
444                             const QHostAddress& localAddress,
445                             quint16 localPort,
446                             const QHostAddress& peerAddress,
447                             quint16 peerPort,
448                             qint64 socketId);
449
450 protected:
451     inline IrcChannel* ircChannelFactory(const QString& channelname) override { return new CoreIrcChannel(channelname, this); }
452     inline IrcUser* ircUserFactory(const QString& hostmask) override { return new CoreIrcUser(hostmask, this); }
453
454 protected slots:
455     // TODO: remove cached cipher keys, when appropriate
456     // virtual void removeIrcUser(IrcUser *ircuser);
457     // virtual void removeIrcChannel(IrcChannel *ircChannel);
458     // virtual void removeChansAndUsers();
459
460 private slots:
461     void onSocketHasData();
462     void onSocketError(QAbstractSocket::SocketError);
463     void onSocketInitialized();
464     void onSocketCloseTimeout();
465     void onSocketDisconnected();
466     void onSocketStateChanged(QAbstractSocket::SocketState);
467
468     void networkInitialized();
469
470     void sendPerform();
471     void restoreUserModes();
472     void doAutoReconnect();
473     void sendPing();
474     void enablePingTimeout(bool enable = true);
475     void disablePingTimeout();
476     void sendAutoWho();
477     void startAutoWhoCycle();
478
479 #ifdef HAVE_SSL
480     void onSslErrors(const QList<QSslError>& errors);
481 #endif
482
483     /**
484      * Check the message token bucket
485      *
486      * If rate limiting is disabled and the message queue is empty, this disables the token bucket
487      * timer.  Otherwise, a queued message will be sent.
488      *
489      * @see CoreNetwork::fillBucketAndProcessQueue()
490      */
491     void checkTokenBucket();
492
493     /**
494      * Top up token bucket and send as many queued messages as possible
495      *
496      * If there's any room for more tokens, add to the token bucket.  Separately, if there's any
497      * messages to send, send until there's no more tokens or the queue is empty, whichever comes
498      * first.
499      */
500     void fillBucketAndProcessQueue();
501
502     void writeToSocket(const QByteArray& data);
503
504 private:
505     void showMessage(const NetworkInternalMessage& msg)
506     {
507         emit displayMsg(RawMessage(networkId(), msg));
508     }
509
510 private:
511     CoreSession* _coreSession;
512
513     bool _debugLogRawIrc;      ///< If true, include raw IRC socket messages in the debug log
514     qint32 _debugLogRawNetId;  ///< Network ID for logging raw IRC socket messages, or -1 for all
515
516 #ifdef HAVE_SSL
517     QSslSocket socket;
518 #else
519     QTcpSocket socket;
520 #endif
521     qint64 _socketId{0};
522
523     CoreUserInputHandler* _userInputHandler;
524
525     QHash<QString, QString> _channelKeys;  // stores persistent channels and their passwords, if any
526
527     QTimer _autoReconnectTimer;
528     int _autoReconnectCount;
529
530     QTimer _socketCloseTimer;
531
532     /* this flag triggers quitRequested() once the socket is closed
533      * it is needed to determine whether or not the connection needs to be
534      * in the automatic session restore. */
535     bool _quitRequested;
536     QString _quitReason;
537
538     bool _disconnectExpected;  /// If true, connection is quitting, expect a socket close
539     // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
540     // specifying a permanent (saved to core session) disconnect.
541
542     bool _shuttingDown{false};  ///< If true, we're shutting down and ignore requests to (dis)connect networks
543
544     bool _previousConnectionAttemptFailed;
545     int _lastUsedServerIndex;
546
547     QTimer _pingTimer;
548     qint64 _lastPingTime = 0;          ///< Unix time of most recently sent automatic ping
549     uint _pingCount = 0;               ///< Unacknowledged automatic pings
550     bool _sendPings = false;           ///< If true, pings should be periodically sent to server
551     bool _pongTimestampValid = false;  ///< If true, IRC server responds to PING by quoting in PONG
552     // This tracks whether or not a server responds to PING with a PONG of what was sent, or if it
553     // does something else.  If false, PING reply hiding should be more aggressive.
554     bool _pongReplyPending = false;  ///< If true, at least one PING sent without a PONG reply
555
556     QStringList _autoWhoQueue;
557     QHash<QString, int> _autoWhoPending;
558     QTimer _autoWhoTimer, _autoWhoCycleTimer;
559
560     // Maintain a list of CAPs that are being checked; if empty, negotiation finished
561     // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
562     QStringList _capsQueuedIndividual;  /// Capabilities to check that require one at a time requests
563     QStringList _capsQueuedBundled;     /// Capabilities to check that can be grouped together
564     QStringList _capsQueuedLastBundle;  /// Most recent capability bundle requested (no individuals)
565     // Some capabilities, such as SASL, require follow-up messages to be fully enabled.  These
566     // capabilities should not be grouped with others to avoid requesting new capabilities while the
567     // previous capability is still being set up.
568     // Additionally, IRC servers can choose to send a 'NAK' to any set of requested capabilities.
569     // If this happens, we need a way to retry each capability individually in order to avoid having
570     // one failing capability (e.g. SASL) block all other capabilities.
571
572     bool _capNegotiationActive;  /// Whether or not full capability negotiation was started
573     // Avoid displaying repeat "negotiation finished" messages
574     bool _capInitialNegotiationEnded;  /// Whether or not initial capability negotiation finished
575     // Avoid sending repeat "CAP END" replies when registration is already ended
576
577     /**
578      * Gets the next set of capabilities to request, removing them from the queue.
579      *
580      * May return one or multiple space-separated capabilities, depending on queue.
581      *
582      * @returns Space-separated names of capabilities to request, or empty string if none remain
583      */
584     QString takeQueuedCaps();
585
586     /**
587      * Maximum length of a single 'CAP REQ' command.
588      *
589      * To be safe, 100 chars.  Higher numbers should be possible; this is following the conservative
590      * minimum number of characters that IRC servers must return in CAP NAK replies.  This also
591      * means CAP NAK replies will contain the full list of denied capabilities.
592      *
593      * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
594      */
595     const int maxCapRequestLength = 100;
596
597     QTimer _tokenBucketTimer;
598     // No need for int type as one cannot travel into the past (at least not yet, Doc)
599     quint32 _messageDelay;        /// Token refill speed in ms
600     quint32 _burstSize;           /// Size of the token bucket
601     quint32 _tokenBucket;         /// The virtual bucket that holds the tokens
602     QList<QByteArray> _msgQueue;  /// Queue of messages waiting to be sent
603     bool _skipMessageRates;       /// If true, skip all message rate limits
604
605     QString _requestedUserModes;  // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
606
607     // List of blowfish keys for channels
608     QHash<QString, QByteArray> _cipherKeys;
609 };