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 ***************************************************************************/
25 #include "coreircchannel.h"
26 #include "coreircuser.h"
34 # include <QSslSocket>
37 # include <QTcpSocket>
44 #include "coresession.h"
49 class CoreUserInputHandler;
50 class CoreIgnoreListManager;
53 class CoreNetwork : public Network
59 CoreNetwork(const NetworkId &networkid, CoreSession *session);
61 inline virtual const QMetaObject *syncMetaObject() const { return &Network::staticMetaObject; }
63 inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); }
64 inline CoreSession *coreSession() const { return _coreSession; }
65 inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); }
67 inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; }
68 inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); }
70 //! Decode a string using the server (network) decoding.
71 inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); }
73 //! Decode a string using a channel-specific encoding if one is set (and use the standard encoding else).
74 QString channelDecode(const QString &channelName, const QByteArray &string) const;
76 //! Decode a string using an IrcUser-specific encoding, if one exists (using the standaed encoding else).
77 QString userDecode(const QString &userNick, const QByteArray &string) const;
79 //! Encode a string using the server (network) encoding.
80 inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); }
82 //! Encode a string using the channel-specific encoding, if set, and use the standard encoding else.
83 QByteArray channelEncode(const QString &channelName, const QString &string) const;
85 //! Encode a string using the user-specific encoding, if set, and use the standard encoding else.
86 QByteArray userEncode(const QString &userNick, const QString &string) const;
88 inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); }
90 inline QByteArray readChannelCipherKey(const QString &channel) const { return _cipherKeys.value(channel.toLower()); }
91 inline void storeChannelCipherKey(const QString &channel, const QByteArray &key) { _cipherKeys[channel.toLower()] = key; }
93 inline bool isAutoWhoInProgress(const QString &channel) const { return _autoWhoPending.value(channel.toLower(), 0); }
95 inline UserId userId() const { return _coreSession->user(); }
97 inline QAbstractSocket::SocketState socketState() const { return socket.state(); }
98 inline bool socketConnected() const { return socket.state() == QAbstractSocket::ConnectedState; }
99 inline QHostAddress localAddress() const { return socket.localAddress(); }
100 inline QHostAddress peerAddress() const { return socket.peerAddress(); }
101 inline quint16 localPort() const { return socket.localPort(); }
102 inline quint16 peerPort() const { return socket.peerPort(); }
105 * Gets whether or not a disconnect was expected.
107 * Distinguishes desired quits from unexpected disconnections such as socket errors or timeouts.
109 * @return True if disconnect was requested, otherwise false.
111 inline bool disconnectExpected() const { return _disconnectExpected; }
114 * Gets whether or not the server replies to automated PINGs with a valid timestamp
116 * Distinguishes between servers that reply by quoting the text sent, and those that respond
117 * with whatever they want.
119 * @return True if a valid timestamp has been received as a PONG, otherwise false.
121 inline bool isPongTimestampValid() const { return _pongTimestampValid; }
124 * Gets whether or not an automated PING has been sent without any PONG received
126 * Reset whenever any PONG is received, not just the automated one sent.
128 * @return True if a PING has been sent without a PONG received, otherwise false.
130 inline bool isPongReplyPending() const { return _pongReplyPending; }
132 QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator);
134 // IRCv3 capability negotiation
137 * Checks if capability negotiation is currently ongoing.
139 * @returns True if in progress, otherwise false
141 inline bool capNegotiationInProgress() const { return (!_capsQueuedIndividual.empty() ||
142 !_capsQueuedBundled.empty()); }
145 * Queues a capability to be requested.
147 * Adds to the list of capabilities being requested. If non-empty, CAP REQ messages are sent
148 * to the IRC server. This may happen at login or if capabilities are announced via CAP NEW.
150 * @param[in] capability Name of the capability
152 void queueCap(const QString &capability);
155 * Begins capability negotiation if capabilities are queued, otherwise returns.
157 * If any capabilities are queued, this will begin the cycle of taking each capability and
158 * requesting it. When no capabilities remain, capability negotiation is suitably ended.
160 void beginCapNegotiation();
163 * Ends capability negotiation.
165 * This won't have effect if other CAP commands are in the command queue before calling this
166 * command. It should only be called when capability negotiation is complete.
168 void endCapNegotiation();
171 * Queues the most recent capability set for retrying individually.
173 * Retries the most recent bundle of capabilities one at a time instead of as a group, working
174 * around the issue that IRC servers can deny a group of requested capabilities without
175 * indicating which capabilities failed.
177 * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
179 * This does NOT call CoreNetwork::sendNextCap(). Call that when ready afterwards. Does
180 * nothing if the last capability tried was individual instead of a set.
182 void retryCapsIndividually();
185 * List of capabilities requiring further core<->server messages to configure.
187 * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
188 * be immediately sent.
190 * Any capabilities in this list must call CoreNetwork::sendNextCap() on their own and they will
191 * not be batched together with other capabilities.
193 * See: http://ircv3.net/specs/extensions/sasl-3.2.html
195 const QStringList capsRequiringConfiguration = QStringList {
200 virtual void setMyNick(const QString &mynick);
202 virtual void requestConnect() const;
203 virtual void requestDisconnect() const;
204 virtual void requestSetNetworkInfo(const NetworkInfo &info);
206 virtual void setUseAutoReconnect(bool);
207 virtual void setAutoReconnectInterval(quint32);
208 virtual void setAutoReconnectRetries(quint16);
210 void setPingInterval(int interval);
213 * Sets whether or not the IRC server has replied to PING with a valid timestamp
215 * This allows determining whether or not an IRC server responds to PING with a PONG that quotes
216 * what was sent, or if it does something else (and therefore PONGs should be more aggressively
219 * @param timestampValid If true, a valid timestamp has been received via PONG reply
221 void setPongTimestampValid(bool validTimestamp);
223 void connectToIrc(bool reconnecting = false);
225 * Disconnect from the IRC server.
227 * Begin disconnecting from the IRC server, including optionally reconnecting.
229 * @param requested If true, user requested this disconnect; don't try to reconnect
230 * @param reason Reason for quitting, defaulting to the user-configured quit reason
231 * @param withReconnect Reconnect to the network after disconnecting (e.g. ping timeout)
232 * @param forceImmediate Immediately disconnect from network, skipping queue of other commands
234 void disconnectFromIrc(bool requested = true, const QString &reason = QString(),
235 bool withReconnect = false, bool forceImmediate = false);
238 * Forcibly close the IRC server socket, waiting for it to close.
240 * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
241 * be sure the network's disconencted (e.g. clean-up), call this.
243 * @param msecs Maximum time to wait for socket to close, in milliseconds.
244 * @return True if socket closes successfully; false if error occurs or timeout reached
246 bool forceDisconnect(int msecs = 1000);
248 void userInput(BufferInfo bufferInfo, QString msg);
251 * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
253 * @param[in] input QByteArray of encoded characters
256 * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
257 * end. This should be used sparingly, for if either the core or the IRC server cannot maintain
258 * PING/PONG replies, the other side will close the connection.
261 void putRawLine(const QByteArray input, const bool prepend = false);
264 * Sends the command with encoded parameters, with optional prefix or high priority.
266 * @param[in] cmd Command to send, ignoring capitalization
267 * @param[in] params Parameters for the command, encoded within a QByteArray
268 * @param[in] prefix Optional command prefix
271 * If true, the command is prepended into the start of the queue, otherwise, it's appended to
272 * the end. This should be used sparingly, for if either the core or the IRC server cannot
273 * maintain PING/PONG replies, the other side will close the connection.
276 void putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = QByteArray(), const bool prepend = false);
279 * Sends the command for each set of encoded parameters, with optional prefix or high priority.
281 * @param[in] cmd Command to send, ignoring capitalization
284 * List of parameter lists for the command, encoded within a QByteArray. The command will be
285 * sent multiple times, once for each set of params stored within the outer list.
287 * @param[in] prefix Optional command prefix
288 * @param[in] prependAll
290 * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
291 * appended to the end. This should be used sparingly, for if either the core or the IRC server
292 * cannot maintain PING/PONG replies, the other side will close the connection.
295 void putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = QByteArray(), const bool prependAll = false);
297 void setChannelJoined(const QString &channel);
298 void setChannelParted(const QString &channel);
299 void addChannelKey(const QString &channel, const QString &key);
300 void removeChannelKey(const QString &channel);
304 Cipher *cipher(const QString &recipient);
305 QByteArray cipherKey(const QString &recipient) const;
306 void setCipherKey(const QString &recipient, const QByteArray &key);
307 bool cipherUsesCBC(const QString &target);
310 // Custom rate limiting (can be connected to signals)
313 * Update rate limiting according to Network configuration
315 * Updates the token bucket and message queue timer according to the network configuration, such
316 * as on first load, or after changing settings.
318 * Calling this will reset any ongoing queue delays. If messages exist in the queue when rate
319 * limiting is disabled, messages will be quickly sent (100 ms) with new messages queued to send
320 * until the queue is cleared.
322 * @see Network::useCustomMessageRate()
323 * @see Network::messageRateBurstSize()
324 * @see Network::messageRateDelay()
325 * @see Network::unlimitedMessageRate()
327 * @param[in] forceUnlimited
329 * If true, override user settings to disable message rate limiting, otherwise apply rate limits
330 * set by the user. Use with caution and remember to re-enable configured limits when done.
333 void updateRateLimiting(const bool forceUnlimited = false);
336 * Resets the token bucket up to the maximum
338 * Call this if the connection's been reset after calling updateRateLimiting() if needed.
340 * @see CoreNetwork::updateRateLimiting()
342 void resetTokenBucket();
344 // IRCv3 capability negotiation (can be connected to signals)
347 * Indicates a capability is now available, with optional value in Network::capValue().
349 * @see Network::addCap()
351 * @param[in] capability Name of the capability
353 void serverCapAdded(const QString &capability);
356 * Indicates a capability was acknowledged (enabled by the IRC server).
358 * @see Network::acknowledgeCap()
360 * @param[in] capability Name of the capability
362 void serverCapAcknowledged(const QString &capability);
365 * Indicates a capability was removed from the list of available capabilities.
367 * @see Network::removeCap()
369 * @param[in] capability Name of the capability
371 void serverCapRemoved(const QString &capability);
374 * Sends the next capability from the queue.
376 * During nick registration if any capabilities remain queued, this will take the next and
377 * request it. When no capabilities remain, capability negotiation is ended.
381 void setAutoWhoEnabled(bool enabled);
382 void setAutoWhoInterval(int interval);
383 void setAutoWhoDelay(int delay);
386 * Appends the given channel/nick to the front of the AutoWho queue.
388 * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
389 * who-cycles are disabled as per IRCv3 specifications.
391 * @param[in] channelOrNick Channel or nickname to WHO
393 void queueAutoWhoOneshot(const QString &channelOrNick);
396 * Removes the given channel/nick from AutoWho queue for when it stops existing
398 * If not already in queue, nothing happens. This should only be used for nicknames and
399 * channels that have suddenly stopped existing (e.g. nick joins then quits).
401 * For when a periodic channel AutoWho finishes, see CoreNetwork::setAutoWhoDone()
403 * @param channelOrNick Channel or nickname to WHO
405 void cancelAutoWhoOneshot(const QString &channelOrNick);
407 bool setAutoWhoDone(const QString &channel);
409 void updateIssuedModes(const QString &requestedModes);
410 void updatePersistentModes(QString addModes, QString removeModes);
411 void resetPersistentModes();
413 Server usedServer() const;
415 inline void resetPingTimeout() { _pingCount = 0; }
418 * Marks the network as no longer having a pending reply to an automated PING
420 inline void resetPongReplyPending() { _pongReplyPending = false; }
422 inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
424 emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
429 void recvRawServerMsg(QString);
430 void displayStatusMsg(QString);
431 void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
432 void disconnected(NetworkId networkId);
433 void connectionError(const QString &errorMsg);
435 void quitRequested(NetworkId networkId);
436 void sslErrors(const QVariant &errorData);
438 void newEvent(Event *event);
439 void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId);
440 void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId);
443 inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
444 inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
447 // TODO: remove cached cipher keys, when appropriate
448 //virtual void removeIrcUser(IrcUser *ircuser);
449 //virtual void removeIrcChannel(IrcChannel *ircChannel);
450 //virtual void removeChansAndUsers();
453 void socketHasData();
454 void socketError(QAbstractSocket::SocketError);
455 void socketInitialized();
456 inline void socketCloseTimeout() { socket.abort(); }
457 void socketDisconnected();
458 void socketStateChanged(QAbstractSocket::SocketState);
459 void networkInitialized();
462 void restoreUserModes();
463 void doAutoReconnect();
465 void enablePingTimeout(bool enable = true);
466 void disablePingTimeout();
468 void startAutoWhoCycle();
471 void sslErrors(const QList<QSslError> &errors);
475 * Check the message token bucket
477 * If rate limiting is disabled and the message queue is empty, this disables the token bucket
478 * timer. Otherwise, a queued message will be sent.
480 * @see CoreNetwork::fillBucketAndProcessQueue()
482 void checkTokenBucket();
485 * Top up token bucket and send as many queued messages as possible
487 * If there's any room for more tokens, add to the token bucket. Separately, if there's any
488 * messages to send, send until there's no more tokens or the queue is empty, whichever comes
491 void fillBucketAndProcessQueue();
493 void writeToSocket(const QByteArray &data);
496 CoreSession *_coreSession;
498 bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log
499 qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all
508 CoreUserInputHandler *_userInputHandler;
510 QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
512 QTimer _autoReconnectTimer;
513 int _autoReconnectCount;
515 QTimer _socketCloseTimer;
517 /* this flag triggers quitRequested() once the socket is closed
518 * it is needed to determine whether or not the connection needs to be
519 * in the automatic session restore. */
523 bool _disconnectExpected; /// If true, connection is quitting, expect a socket close
524 // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
525 // specifying a permanent (saved to core session) disconnect.
527 bool _previousConnectionAttemptFailed;
528 int _lastUsedServerIndex;
531 qint64 _lastPingTime = 0; ///< Unix time of most recently sent automatic ping
532 uint _pingCount = 0; ///< Unacknowledged automatic pings
533 bool _sendPings = false; ///< If true, pings should be periodically sent to server
534 bool _pongTimestampValid = false; ///< If true, IRC server responds to PING by quoting in PONG
535 // This tracks whether or not a server responds to PING with a PONG of what was sent, or if it
536 // does something else. If false, PING reply hiding should be more aggressive.
537 bool _pongReplyPending = false; ///< If true, at least one PING sent without a PONG reply
539 QStringList _autoWhoQueue;
540 QHash<QString, int> _autoWhoPending;
541 QTimer _autoWhoTimer, _autoWhoCycleTimer;
543 // Maintain a list of CAPs that are being checked; if empty, negotiation finished
544 // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
545 QStringList _capsQueuedIndividual; /// Capabilities to check that require one at a time requests
546 QStringList _capsQueuedBundled; /// Capabilities to check that can be grouped together
547 QStringList _capsQueuedLastBundle; /// Most recent capability bundle requested (no individuals)
548 // Some capabilities, such as SASL, require follow-up messages to be fully enabled. These
549 // capabilities should not be grouped with others to avoid requesting new capabilities while the
550 // previous capability is still being set up.
551 // Additionally, IRC servers can choose to send a 'NAK' to any set of requested capabilities.
552 // If this happens, we need a way to retry each capability individually in order to avoid having
553 // one failing capability (e.g. SASL) block all other capabilities.
555 bool _capNegotiationActive; /// Whether or not full capability negotiation was started
556 // Avoid displaying repeat "negotiation finished" messages
557 bool _capInitialNegotiationEnded; /// Whether or not initial capability negotiation finished
558 // Avoid sending repeat "CAP END" replies when registration is already ended
561 * Gets the next set of capabilities to request, removing them from the queue.
563 * May return one or multiple space-separated capabilities, depending on queue.
565 * @returns Space-separated names of capabilities to request, or empty string if none remain
567 QString takeQueuedCaps();
570 * Maximum length of a single 'CAP REQ' command.
572 * To be safe, 100 chars. Higher numbers should be possible; this is following the conservative
573 * minimum number of characters that IRC servers must return in CAP NAK replies. This also
574 * means CAP NAK replies will contain the full list of denied capabilities.
576 * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
578 const int maxCapRequestLength = 100;
580 QTimer _tokenBucketTimer;
581 // No need for int type as one cannot travel into the past (at least not yet, Doc)
582 quint32 _messageDelay; /// Token refill speed in ms
583 quint32 _burstSize; /// Size of the token bucket
584 quint32 _tokenBucket; /// The virtual bucket that holds the tokens
585 QList<QByteArray> _msgQueue; /// Queue of messages waiting to be sent
586 bool _skipMessageRates; /// If true, skip all message rate limits
588 QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
590 // List of blowfish keys for channels
591 QHash<QString, QByteArray> _cipherKeys;
595 #endif //CORENETWORK_H