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