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