1 /***************************************************************************
2 * Copyright (C) 2005-2016 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(); }
104 QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator);
106 // IRCv3 capability negotiation
109 * Checks if capability negotiation is currently ongoing.
111 * @returns True if in progress, otherwise false
113 inline bool capNegotiationInProgress() const { return (!_capsQueuedIndividual.empty() ||
114 !_capsQueuedBundled.empty()); }
117 * Queues a capability to be requested.
119 * Adds to the list of capabilities being requested. If non-empty, CAP REQ messages are sent
120 * to the IRC server. This may happen at login or if capabilities are announced via CAP NEW.
122 * @param[in] capability Name of the capability
124 void queueCap(const QString &capability);
127 * Begins capability negotiation if capabilities are queued, otherwise returns.
129 * If any capabilities are queued, this will begin the cycle of taking each capability and
130 * requesting it. When no capabilities remain, capability negotiation is suitably ended.
132 void beginCapNegotiation();
135 * Ends capability negotiation.
137 * This won't have effect if other CAP commands are in the command queue before calling this
138 * command. It should only be called when capability negotiation is complete.
140 void endCapNegotiation();
143 * Queues the most recent capability set for retrying individually.
145 * Retries the most recent bundle of capabilities one at a time instead of as a group, working
146 * around the issue that IRC servers can deny a group of requested capabilities without
147 * indicating which capabilities failed.
149 * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
151 * This does NOT call CoreNetwork::sendNextCap(). Call that when ready afterwards. Does
152 * nothing if the last capability tried was individual instead of a set.
154 void retryCapsIndividually();
157 * List of capabilities requiring further core<->server messages to configure.
159 * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
160 * be immediately sent.
162 * Any capabilities in this list must call CoreNetwork::sendNextCap() on their own and they will
163 * not be batched together with other capabilities.
165 * See: http://ircv3.net/specs/extensions/sasl-3.2.html
167 const QStringList capsRequiringConfiguration = QStringList {
172 virtual void setMyNick(const QString &mynick);
174 virtual void requestConnect() const;
175 virtual void requestDisconnect() const;
176 virtual void requestSetNetworkInfo(const NetworkInfo &info);
178 virtual void setUseAutoReconnect(bool);
179 virtual void setAutoReconnectInterval(quint32);
180 virtual void setAutoReconnectRetries(quint16);
182 void setPingInterval(int interval);
184 void connectToIrc(bool reconnecting = false);
186 * Disconnect from the IRC server.
188 * Begin disconnecting from the IRC server, including optionally reconnecting.
190 * @param requested If true, user requested this disconnect; don't try to reconnect
191 * @param reason Reason for quitting, defaulting to the user-configured quit reason
192 * @param withReconnect Reconnect to the network after disconnecting (e.g. ping timeout)
193 * @param forceImmediate Immediately disconnect from network, skipping queue of other commands
195 void disconnectFromIrc(bool requested = true, const QString &reason = QString(),
196 bool withReconnect = false, bool forceImmediate = false);
199 * Forcibly close the IRC server socket, waiting for it to close.
201 * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
202 * be sure the network's disconencted (e.g. clean-up), call this.
204 * @param msecs Maximum time to wait for socket to close, in milliseconds.
205 * @return True if socket closes successfully; false if error occurs or timeout reached
207 bool forceDisconnect(int msecs = 1000);
209 void userInput(BufferInfo bufferInfo, QString msg);
212 * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
214 * @param[in] input QByteArray of encoded characters
217 * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
218 * end. This should be used sparingly, for if either the core or the IRC server cannot maintain
219 * PING/PONG replies, the other side will close the connection.
222 void putRawLine(const QByteArray input, const bool prepend = false);
225 * Sends the command with encoded parameters, with optional prefix or high priority.
227 * @param[in] cmd Command to send, ignoring capitalization
228 * @param[in] params Parameters for the command, encoded within a QByteArray
229 * @param[in] prefix Optional command prefix
232 * If true, the command is prepended into the start of the queue, otherwise, it's appended to
233 * the end. This should be used sparingly, for if either the core or the IRC server cannot
234 * maintain PING/PONG replies, the other side will close the connection.
237 void putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = QByteArray(), const bool prepend = false);
240 * Sends the command for each set of encoded parameters, with optional prefix or high priority.
242 * @param[in] cmd Command to send, ignoring capitalization
245 * List of parameter lists for the command, encoded within a QByteArray. The command will be
246 * sent multiple times, once for each set of params stored within the outer list.
248 * @param[in] prefix Optional command prefix
249 * @param[in] prependAll
251 * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
252 * appended to the end. This should be used sparingly, for if either the core or the IRC server
253 * cannot maintain PING/PONG replies, the other side will close the connection.
256 void putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = QByteArray(), const bool prependAll = false);
258 void setChannelJoined(const QString &channel);
259 void setChannelParted(const QString &channel);
260 void addChannelKey(const QString &channel, const QString &key);
261 void removeChannelKey(const QString &channel);
265 Cipher *cipher(const QString &recipient);
266 QByteArray cipherKey(const QString &recipient) const;
267 void setCipherKey(const QString &recipient, const QByteArray &key);
268 bool cipherUsesCBC(const QString &target);
271 // Custom rate limiting (can be connected to signals)
274 * Update rate limiting according to Network configuration
276 * Updates the token bucket and message queue timer according to the network configuration, such
277 * as on first load, or after changing settings.
279 * Calling this will reset any ongoing queue delays. If messages exist in the queue when rate
280 * limiting is disabled, messages will be quickly sent (100 ms) with new messages queued to send
281 * until the queue is cleared.
283 * @see Network::useCustomMessageRate()
284 * @see Network::messageRateBurstSize()
285 * @see Network::messageRateDelay()
286 * @see Network::unlimitedMessageRate()
288 void updateRateLimiting();
291 * Resets the token bucket up to the maximum
293 * Call this if the connection's been reset after calling updateRateLimiting() if needed.
295 * @see CoreNetwork::updateRateLimiting()
297 void resetTokenBucket();
299 // IRCv3 capability negotiation (can be connected to signals)
302 * Indicates a capability is now available, with optional value in Network::capValue().
304 * @see Network::addCap()
306 * @param[in] capability Name of the capability
308 void serverCapAdded(const QString &capability);
311 * Indicates a capability was acknowledged (enabled by the IRC server).
313 * @see Network::acknowledgeCap()
315 * @param[in] capability Name of the capability
317 void serverCapAcknowledged(const QString &capability);
320 * Indicates a capability was removed from the list of available capabilities.
322 * @see Network::removeCap()
324 * @param[in] capability Name of the capability
326 void serverCapRemoved(const QString &capability);
329 * Sends the next capability from the queue.
331 * During nick registration if any capabilities remain queued, this will take the next and
332 * request it. When no capabilities remain, capability negotiation is ended.
336 void setAutoWhoEnabled(bool enabled);
337 void setAutoWhoInterval(int interval);
338 void setAutoWhoDelay(int delay);
341 * Appends the given channel/nick to the front of the AutoWho queue.
343 * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
344 * who-cycles are disabled as per IRCv3 specifications.
346 * @param[in] channelOrNick Channel or nickname to WHO
348 void queueAutoWhoOneshot(const QString &channelOrNick);
350 bool setAutoWhoDone(const QString &channel);
352 void updateIssuedModes(const QString &requestedModes);
353 void updatePersistentModes(QString addModes, QString removeModes);
354 void resetPersistentModes();
356 Server usedServer() const;
358 inline void resetPingTimeout() { _pingCount = 0; }
360 inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
362 emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
367 void recvRawServerMsg(QString);
368 void displayStatusMsg(QString);
369 void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
370 void disconnected(NetworkId networkId);
371 void connectionError(const QString &errorMsg);
373 void quitRequested(NetworkId networkId);
374 void sslErrors(const QVariant &errorData);
376 void newEvent(Event *event);
377 void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
378 void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
381 inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
382 inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
385 // TODO: remove cached cipher keys, when appropriate
386 //virtual void removeIrcUser(IrcUser *ircuser);
387 //virtual void removeIrcChannel(IrcChannel *ircChannel);
388 //virtual void removeChansAndUsers();
391 void socketHasData();
392 void socketError(QAbstractSocket::SocketError);
393 void socketInitialized();
394 inline void socketCloseTimeout() { socket.abort(); }
395 void socketDisconnected();
396 void socketStateChanged(QAbstractSocket::SocketState);
397 void networkInitialized();
400 void restoreUserModes();
401 void doAutoReconnect();
403 void enablePingTimeout(bool enable = true);
404 void disablePingTimeout();
406 void startAutoWhoCycle();
409 void sslErrors(const QList<QSslError> &errors);
413 * Check the message token bucket
415 * If rate limiting is disabled and the message queue is empty, this disables the token bucket
416 * timer. Otherwise, a queued message will be sent.
418 * @see CoreNetwork::fillBucketAndProcessQueue()
420 void checkTokenBucket();
423 * Top up token bucket and send as many queued messages as possible
425 * If there's any room for more tokens, add to the token bucket. Separately, if there's any
426 * messages to send, send until there's no more tokens or the queue is empty, whichever comes
429 void fillBucketAndProcessQueue();
431 void writeToSocket(const QByteArray &data);
434 CoreSession *_coreSession;
442 CoreUserInputHandler *_userInputHandler;
444 QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
446 QTimer _autoReconnectTimer;
447 int _autoReconnectCount;
449 QTimer _socketCloseTimer;
451 /* this flag triggers quitRequested() once the socket is closed
452 * it is needed to determine whether or not the connection needs to be
453 * in the automatic session restore. */
457 bool _disconnectExpected; /// If true, connection is quitting, expect a socket close
458 // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
459 // specifying a permanent (saved to core session) disconnect.
461 bool _previousConnectionAttemptFailed;
462 int _lastUsedServerIndex;
469 QStringList _autoWhoQueue;
470 QHash<QString, int> _autoWhoPending;
471 QTimer _autoWhoTimer, _autoWhoCycleTimer;
473 // Maintain a list of CAPs that are being checked; if empty, negotiation finished
474 // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
475 QStringList _capsQueuedIndividual; /// Capabilities to check that require one at a time requests
476 QStringList _capsQueuedBundled; /// Capabilities to check that can be grouped together
477 QStringList _capsQueuedLastBundle; /// Most recent capability bundle requested (no individuals)
478 // Some capabilities, such as SASL, require follow-up messages to be fully enabled. These
479 // capabilities should not be grouped with others to avoid requesting new capabilities while the
480 // previous capability is still being set up.
481 // Additionally, IRC servers can choose to send a 'NAK' to any set of requested capabilities.
482 // If this happens, we need a way to retry each capability individually in order to avoid having
483 // one failing capability (e.g. SASL) block all other capabilities.
485 bool _capNegotiationActive; /// Whether or not full capability negotiation was started
486 // Avoid displaying repeat "negotiation finished" messages
487 bool _capInitialNegotiationEnded; /// Whether or not initial capability negotiation finished
488 // Avoid sending repeat "CAP END" replies when registration is already ended
491 * Gets the next set of capabilities to request, removing them from the queue.
493 * May return one or multiple space-separated capabilities, depending on queue.
495 * @returns Space-separated names of capabilities to request, or empty string if none remain
497 QString takeQueuedCaps();
500 * Maximum length of a single 'CAP REQ' command.
502 * To be safe, 100 chars. Higher numbers should be possible; this is following the conservative
503 * minimum number of characters that IRC servers must return in CAP NAK replies. This also
504 * means CAP NAK replies will contain the full list of denied capabilities.
506 * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
508 const int maxCapRequestLength = 100;
510 QTimer _tokenBucketTimer;
511 // No need for int type as one cannot travel into the past (at least not yet, Doc)
512 quint32 _messageDelay; /// Token refill speed in ms
513 quint32 _burstSize; /// Size of the token bucket
514 quint32 _tokenBucket; /// The virtual bucket that holds the tokens
515 QList<QByteArray> _msgQueue; /// Queue of messages waiting to be sent
516 bool _skipMessageRates; /// If true, skip all message rate limits
518 QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
520 // List of blowfish keys for channels
521 QHash<QString, QByteArray> _cipherKeys;
525 #endif //CORENETWORK_H