1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
24 #include "coreircchannel.h"
25 #include "coreircuser.h"
33 # include <QSslSocket>
36 # include <QTcpSocket>
43 #include "coresession.h"
48 class CoreUserInputHandler;
49 class CoreIgnoreListManager;
52 class CoreNetwork : public Network
57 CoreNetwork(const NetworkId &networkid, CoreSession *session);
58 ~CoreNetwork() override;
60 inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); }
61 inline CoreSession *coreSession() const { return _coreSession; }
62 inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); }
64 inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; }
65 inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); }
67 //! Decode a string using the server (network) decoding.
68 inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); }
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;
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;
76 //! Encode a string using the server (network) encoding.
77 inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); }
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;
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;
85 inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); }
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; }
91 * Checks if the given target has an automatic WHO in progress
93 * @param name Channel or nickname
94 * @return True if an automatic WHO is in progress, otherwise false
96 inline bool isAutoWhoInProgress(const QString &name) const
98 return _autoWhoPending.value(name.toLower(), 0);
101 inline UserId userId() const { return _coreSession->user(); }
103 inline QAbstractSocket::SocketState socketState() const { return socket.state(); }
104 inline bool socketConnected() const { return socket.state() == QAbstractSocket::ConnectedState; }
105 inline QHostAddress localAddress() const { return socket.localAddress(); }
106 inline QHostAddress peerAddress() const { return socket.peerAddress(); }
107 inline quint16 localPort() const { return socket.localPort(); }
108 inline quint16 peerPort() const { return socket.peerPort(); }
111 * Gets whether or not a disconnect was expected.
113 * Distinguishes desired quits from unexpected disconnections such as socket errors or timeouts.
115 * @return True if disconnect was requested, otherwise false.
117 inline bool disconnectExpected() const { return _disconnectExpected; }
120 * Gets whether or not the server replies to automated PINGs with a valid timestamp
122 * Distinguishes between servers that reply by quoting the text sent, and those that respond
123 * with whatever they want.
125 * @return True if a valid timestamp has been received as a PONG, otherwise false.
127 inline bool isPongTimestampValid() const { return _pongTimestampValid; }
130 * Gets whether or not an automated PING has been sent without any PONG received
132 * Reset whenever any PONG is received, not just the automated one sent.
134 * @return True if a PING has been sent without a PONG received, otherwise false.
136 inline bool isPongReplyPending() const { return _pongReplyPending; }
138 QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, const std::function<QList<QByteArray>(QString &)> &cmdGenerator);
140 // IRCv3 capability negotiation
143 * Checks if capability negotiation is currently ongoing.
145 * @returns True if in progress, otherwise false
147 inline bool capNegotiationInProgress() const { return (!_capsQueuedIndividual.empty() || !_capsQueuedBundled.empty()); }
150 * Queues a capability to be requested.
152 * Adds to the list of capabilities being requested. If non-empty, CAP REQ messages are sent
153 * to the IRC server. This may happen at login or if capabilities are announced via CAP NEW.
155 * @param[in] capability Name of the capability
157 void queueCap(const QString &capability);
160 * Begins capability negotiation if capabilities are queued, otherwise returns.
162 * If any capabilities are queued, this will begin the cycle of taking each capability and
163 * requesting it. When no capabilities remain, capability negotiation is suitably ended.
165 void beginCapNegotiation();
168 * Ends capability negotiation.
170 * This won't have effect if other CAP commands are in the command queue before calling this
171 * command. It should only be called when capability negotiation is complete.
173 void endCapNegotiation();
176 * Queues the most recent capability set for retrying individually.
178 * Retries the most recent bundle of capabilities one at a time instead of as a group, working
179 * around the issue that IRC servers can deny a group of requested capabilities without
180 * indicating which capabilities failed.
182 * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
184 * This does NOT call CoreNetwork::sendNextCap(). Call that when ready afterwards. Does
185 * nothing if the last capability tried was individual instead of a set.
187 void retryCapsIndividually();
190 * List of capabilities requiring further core<->server messages to configure.
192 * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
193 * be immediately sent.
195 * Any capabilities in this list must call CoreNetwork::sendNextCap() on their own and they will
196 * not be batched together with other capabilities.
198 * See: http://ircv3.net/specs/extensions/sasl-3.2.html
200 const QStringList capsRequiringConfiguration = QStringList {
205 void setMyNick(const QString &mynick) override;
207 void requestConnect() const override;
208 void requestDisconnect() const override;
209 void requestSetNetworkInfo(const NetworkInfo &info) override;
211 void setUseAutoReconnect(bool) override;
212 void setAutoReconnectInterval(quint32) override;
213 void setAutoReconnectRetries(quint16) override;
215 void setPingInterval(int interval);
218 * Sets whether or not the IRC server has replied to PING with a valid timestamp
220 * This allows determining whether or not an IRC server responds to PING with a PONG that quotes
221 * what was sent, or if it does something else (and therefore PONGs should be more aggressively
224 * @param timestampValid If true, a valid timestamp has been received via PONG reply
226 void setPongTimestampValid(bool validTimestamp);
229 * Indicates that the CoreSession is shutting down.
231 * Disconnects the network if connected, and sets a flag that prevents reconnections.
235 void connectToIrc(bool reconnecting = false);
237 * Disconnect from the IRC server.
239 * Begin disconnecting from the IRC server, including optionally reconnecting.
241 * @param requested If true, user requested this disconnect; don't try to reconnect
242 * @param reason Reason for quitting, defaulting to the user-configured quit reason
243 * @param withReconnect Reconnect to the network after disconnecting (e.g. ping timeout)
245 void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false);
248 * Forcibly close the IRC server socket, waiting for it to close.
250 * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
251 * be sure the network's disconnected (e.g. clean-up), call this.
253 * @param msecs Maximum time to wait for socket to close, in milliseconds.
254 * @return True if socket closes successfully; false if error occurs or timeout reached
256 bool forceDisconnect(int msecs = 1000);
258 void userInput(const BufferInfo &bufferInfo, QString msg);
261 * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
263 * @param[in] input QByteArray of encoded characters
266 * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
267 * end. This should be used sparingly, for if either the core or the IRC server cannot maintain
268 * PING/PONG replies, the other side will close the connection.
271 void putRawLine(const QByteArray &input, bool prepend = false);
274 * Sends the command with encoded parameters, with optional prefix or high priority.
276 * @param[in] cmd Command to send, ignoring capitalization
277 * @param[in] params Parameters for the command, encoded within a QByteArray
278 * @param[in] prefix Optional command prefix
281 * If true, the command is prepended into the start of the queue, otherwise, it's appended to
282 * the end. This should be used sparingly, for if either the core or the IRC server cannot
283 * maintain PING/PONG replies, the other side will close the connection.
286 void putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = {}, bool prepend = false);
289 * Sends the command for each set of encoded parameters, with optional prefix or high priority.
291 * @param[in] cmd Command to send, ignoring capitalization
294 * List of parameter lists for the command, encoded within a QByteArray. The command will be
295 * sent multiple times, once for each set of params stored within the outer list.
297 * @param[in] prefix Optional command prefix
298 * @param[in] prependAll
300 * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
301 * appended to the end. This should be used sparingly, for if either the core or the IRC server
302 * cannot maintain PING/PONG replies, the other side will close the connection.
305 void putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = {}, bool prependAll = false);
307 void setChannelJoined(const QString &channel);
308 void setChannelParted(const QString &channel);
309 void addChannelKey(const QString &channel, const QString &key);
310 void removeChannelKey(const QString &channel);
314 Cipher *cipher(const QString &recipient);
315 QByteArray cipherKey(const QString &recipient) const;
316 void setCipherKey(const QString &recipient, const QByteArray &key);
317 bool cipherUsesCBC(const QString &target);
320 // Custom rate limiting (can be connected to signals)
323 * Update rate limiting according to Network configuration
325 * Updates the token bucket and message queue timer according to the network configuration, such
326 * as on first load, or after changing settings.
328 * Calling this will reset any ongoing queue delays. If messages exist in the queue when rate
329 * limiting is disabled, messages will be quickly sent (100 ms) with new messages queued to send
330 * until the queue is cleared.
332 * @see Network::useCustomMessageRate()
333 * @see Network::messageRateBurstSize()
334 * @see Network::messageRateDelay()
335 * @see Network::unlimitedMessageRate()
337 * @param[in] forceUnlimited
339 * If true, override user settings to disable message rate limiting, otherwise apply rate limits
340 * set by the user. Use with caution and remember to re-enable configured limits when done.
343 void updateRateLimiting(const bool forceUnlimited = false);
346 * Resets the token bucket up to the maximum
348 * Call this if the connection's been reset after calling updateRateLimiting() if needed.
350 * @see CoreNetwork::updateRateLimiting()
352 void resetTokenBucket();
354 // IRCv3 capability negotiation (can be connected to signals)
357 * Indicates a capability is now available, with optional value in Network::capValue().
359 * @see Network::addCap()
361 * @param[in] capability Name of the capability
363 void serverCapAdded(const QString &capability);
366 * Indicates a capability was acknowledged (enabled by the IRC server).
368 * @see Network::acknowledgeCap()
370 * @param[in] capability Name of the capability
372 void serverCapAcknowledged(const QString &capability);
375 * Indicates a capability was removed from the list of available capabilities.
377 * @see Network::removeCap()
379 * @param[in] capability Name of the capability
381 void serverCapRemoved(const QString &capability);
384 * Sends the next capability from the queue.
386 * During nick registration if any capabilities remain queued, this will take the next and
387 * request it. When no capabilities remain, capability negotiation is ended.
391 void setAutoWhoEnabled(bool enabled);
392 void setAutoWhoInterval(int interval);
393 void setAutoWhoDelay(int delay);
396 * Appends the given channel/nick to the front of the AutoWho queue.
398 * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
399 * who-cycles are disabled as per IRCv3 specifications.
401 * @param[in] name Channel or nickname
403 void queueAutoWhoOneshot(const QString &name);
406 * Checks if the given target has an automatic WHO in progress, and sets it as done if so
408 * @param name Channel or nickname
409 * @return True if an automatic WHO is in progress (and should be silenced), otherwise false
411 bool setAutoWhoDone(const QString &name);
413 void updateIssuedModes(const QString &requestedModes);
414 void updatePersistentModes(QString addModes, QString removeModes);
415 void resetPersistentModes();
417 Server usedServer() const;
419 inline void resetPingTimeout() { _pingCount = 0; }
422 * Marks the network as no longer having a pending reply to an automated PING
424 inline void resetPongReplyPending() { _pongReplyPending = false; }
426 void onDisplayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender, Message::Flags flags)
428 emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
433 void recvRawServerMsg(QString);
434 void displayStatusMsg(QString);
435 void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender, Message::Flags flags);
436 void disconnected(NetworkId networkId);
437 void connectionError(const QString &errorMsg);
439 void quitRequested(NetworkId networkId);
440 void sslErrors(const QVariant &errorData);
442 void newEvent(Event *event);
443 void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId);
444 void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId);
447 inline IrcChannel *ircChannelFactory(const QString &channelname) override { return new CoreIrcChannel(channelname, this); }
448 inline IrcUser *ircUserFactory(const QString &hostmask) override { return new CoreIrcUser(hostmask, this); }
451 // TODO: remove cached cipher keys, when appropriate
452 //virtual void removeIrcUser(IrcUser *ircuser);
453 //virtual void removeIrcChannel(IrcChannel *ircChannel);
454 //virtual void removeChansAndUsers();
457 void onSocketHasData();
458 void onSocketError(QAbstractSocket::SocketError);
459 void onSocketInitialized();
460 void onSocketCloseTimeout();
461 void onSocketDisconnected();
462 void onSocketStateChanged(QAbstractSocket::SocketState);
464 void networkInitialized();
467 void restoreUserModes();
468 void doAutoReconnect();
470 void enablePingTimeout(bool enable = true);
471 void disablePingTimeout();
473 void startAutoWhoCycle();
476 void onSslErrors(const QList<QSslError> &errors);
480 * Check the message token bucket
482 * If rate limiting is disabled and the message queue is empty, this disables the token bucket
483 * timer. Otherwise, a queued message will be sent.
485 * @see CoreNetwork::fillBucketAndProcessQueue()
487 void checkTokenBucket();
490 * Top up token bucket and send as many queued messages as possible
492 * If there's any room for more tokens, add to the token bucket. Separately, if there's any
493 * messages to send, send until there's no more tokens or the queue is empty, whichever comes
496 void fillBucketAndProcessQueue();
498 void writeToSocket(const QByteArray &data);
501 void showMessage(Message::Type msgType,
502 BufferInfo::Type bufferType,
503 const QString &target,
505 const QString &sender = "",
506 Message::Flags flags = Message::None)
508 emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
512 CoreSession *_coreSession;
514 bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log
515 qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all
524 CoreUserInputHandler *_userInputHandler;
526 QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
528 QTimer _autoReconnectTimer;
529 int _autoReconnectCount;
531 QTimer _socketCloseTimer;
533 /* this flag triggers quitRequested() once the socket is closed
534 * it is needed to determine whether or not the connection needs to be
535 * in the automatic session restore. */
539 bool _disconnectExpected; /// If true, connection is quitting, expect a socket close
540 // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
541 // specifying a permanent (saved to core session) disconnect.
543 bool _shuttingDown{false}; ///< If true, we're shutting down and ignore requests to (dis)connect networks
545 bool _previousConnectionAttemptFailed;
546 int _lastUsedServerIndex;
549 qint64 _lastPingTime = 0; ///< Unix time of most recently sent automatic ping
550 uint _pingCount = 0; ///< Unacknowledged automatic pings
551 bool _sendPings = false; ///< If true, pings should be periodically sent to server
552 bool _pongTimestampValid = false; ///< If true, IRC server responds to PING by quoting in PONG
553 // This tracks whether or not a server responds to PING with a PONG of what was sent, or if it
554 // does something else. If false, PING reply hiding should be more aggressive.
555 bool _pongReplyPending = false; ///< If true, at least one PING sent without a PONG reply
557 QStringList _autoWhoQueue;
558 QHash<QString, int> _autoWhoPending;
559 QTimer _autoWhoTimer, _autoWhoCycleTimer;
561 // Maintain a list of CAPs that are being checked; if empty, negotiation finished
562 // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
563 QStringList _capsQueuedIndividual; /// Capabilities to check that require one at a time requests
564 QStringList _capsQueuedBundled; /// Capabilities to check that can be grouped together
565 QStringList _capsQueuedLastBundle; /// Most recent capability bundle requested (no individuals)
566 // Some capabilities, such as SASL, require follow-up messages to be fully enabled. These
567 // capabilities should not be grouped with others to avoid requesting new capabilities while the
568 // previous capability is still being set up.
569 // Additionally, IRC servers can choose to send a 'NAK' to any set of requested capabilities.
570 // If this happens, we need a way to retry each capability individually in order to avoid having
571 // one failing capability (e.g. SASL) block all other capabilities.
573 bool _capNegotiationActive; /// Whether or not full capability negotiation was started
574 // Avoid displaying repeat "negotiation finished" messages
575 bool _capInitialNegotiationEnded; /// Whether or not initial capability negotiation finished
576 // Avoid sending repeat "CAP END" replies when registration is already ended
579 * Gets the next set of capabilities to request, removing them from the queue.
581 * May return one or multiple space-separated capabilities, depending on queue.
583 * @returns Space-separated names of capabilities to request, or empty string if none remain
585 QString takeQueuedCaps();
588 * Maximum length of a single 'CAP REQ' command.
590 * To be safe, 100 chars. Higher numbers should be possible; this is following the conservative
591 * minimum number of characters that IRC servers must return in CAP NAK replies. This also
592 * means CAP NAK replies will contain the full list of denied capabilities.
594 * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
596 const int maxCapRequestLength = 100;
598 QTimer _tokenBucketTimer;
599 // No need for int type as one cannot travel into the past (at least not yet, Doc)
600 quint32 _messageDelay; /// Token refill speed in ms
601 quint32 _burstSize; /// Size of the token bucket
602 quint32 _tokenBucket; /// The virtual bucket that holds the tokens
603 QList<QByteArray> _msgQueue; /// Queue of messages waiting to be sent
604 bool _skipMessageRates; /// If true, skip all message rate limits
606 QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
608 // List of blowfish keys for channels
609 QHash<QString, QByteArray> _cipherKeys;