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