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 !_capsQueued.empty(); }
116 * Queues a capability to be requested.
118 * Adds to the list of capabilities being requested. If non-empty, CAP REQ messages are sent
119 * to the IRC server. This may happen at login or if capabilities are announced via CAP NEW.
121 * @param[in] capability Name of the capability
123 void queueCap(const QString &capability);
126 * Begins capability negotiation if capabilities are queued, otherwise returns.
128 * If any capabilities are queued, this will begin the cycle of taking each capability and
129 * requesting it. When no capabilities remain, capability negotiation is suitably ended.
131 void beginCapNegotiation();
134 * List of capabilities requiring further core<->server messages to configure.
136 * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
137 * be immediately sent.
139 * See: http://ircv3.net/specs/extensions/sasl-3.2.html
141 const QStringList capsRequiringConfiguration = QStringList {
146 virtual void setMyNick(const QString &mynick);
148 virtual void requestConnect() const;
149 virtual void requestDisconnect() const;
150 virtual void requestSetNetworkInfo(const NetworkInfo &info);
152 virtual void setUseAutoReconnect(bool);
153 virtual void setAutoReconnectInterval(quint32);
154 virtual void setAutoReconnectRetries(quint16);
156 void setPingInterval(int interval);
158 void connectToIrc(bool reconnecting = false);
160 * Disconnect from the IRC server.
162 * Begin disconnecting from the IRC server, including optionally reconnecting.
164 * @param requested If true, user requested this disconnect; don't try to reconnect
165 * @param reason Reason for quitting, defaulting to the user-configured quit reason
166 * @param withReconnect Reconnect to the network after disconnecting (e.g. ping timeout)
167 * @param forceImmediate Immediately disconnect from network, skipping queue of other commands
169 void disconnectFromIrc(bool requested = true, const QString &reason = QString(),
170 bool withReconnect = false, bool forceImmediate = false);
173 * Forcibly close the IRC server socket, waiting for it to close.
175 * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
176 * be sure the network's disconencted (e.g. clean-up), call this.
178 * @param msecs Maximum time to wait for socket to close, in milliseconds.
179 * @return True if socket closes successfully; false if error occurs or timeout reached
181 bool forceDisconnect(int msecs = 1000);
183 void userInput(BufferInfo bufferInfo, QString msg);
186 * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
188 * @param[in] input QByteArray of encoded characters
191 * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
192 * end. This should be used sparingly, for if either the core or the IRC server cannot maintain
193 * PING/PONG replies, the other side will close the connection.
196 void putRawLine(const QByteArray input, const bool prepend = false);
199 * Sends the command with encoded parameters, with optional prefix or high priority.
201 * @param[in] cmd Command to send, ignoring capitalization
202 * @param[in] params Parameters for the command, encoded within a QByteArray
203 * @param[in] prefix Optional command prefix
206 * If true, the command is prepended into the start of the queue, otherwise, it's appended to
207 * the end. This should be used sparingly, for if either the core or the IRC server cannot
208 * maintain PING/PONG replies, the other side will close the connection.
211 void putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = QByteArray(), const bool prepend = false);
214 * Sends the command for each set of encoded parameters, with optional prefix or high priority.
216 * @param[in] cmd Command to send, ignoring capitalization
219 * List of parameter lists for the command, encoded within a QByteArray. The command will be
220 * sent multiple times, once for each set of params stored within the outer list.
222 * @param[in] prefix Optional command prefix
223 * @param[in] prependAll
225 * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
226 * appended to the end. This should be used sparingly, for if either the core or the IRC server
227 * cannot maintain PING/PONG replies, the other side will close the connection.
230 void putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = QByteArray(), const bool prependAll = false);
232 void setChannelJoined(const QString &channel);
233 void setChannelParted(const QString &channel);
234 void addChannelKey(const QString &channel, const QString &key);
235 void removeChannelKey(const QString &channel);
239 Cipher *cipher(const QString &recipient);
240 QByteArray cipherKey(const QString &recipient) const;
241 void setCipherKey(const QString &recipient, const QByteArray &key);
242 bool cipherUsesCBC(const QString &target);
245 // IRCv3 capability negotiation (can be connected to signals)
248 * Indicates a capability is now available, with optional value in Network::capValue().
250 * @see Network::addCap()
252 * @param[in] capability Name of the capability
254 void serverCapAdded(const QString &capability);
257 * Indicates a capability was acknowledged (enabled by the IRC server).
259 * @see Network::acknowledgeCap()
261 * @param[in] capability Name of the capability
263 void serverCapAcknowledged(const QString &capability);
266 * Indicates a capability was removed from the list of available capabilities.
268 * @see Network::removeCap()
270 * @param[in] capability Name of the capability
272 void serverCapRemoved(const QString &capability);
275 * Sends the next capability from the queue.
277 * During nick registration if any capabilities remain queued, this will take the next and
278 * request it. When no capabilities remain, capability negotiation is ended.
282 void setAutoWhoEnabled(bool enabled);
283 void setAutoWhoInterval(int interval);
284 void setAutoWhoDelay(int delay);
287 * Appends the given channel/nick to the front of the AutoWho queue.
289 * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
290 * who-cycles are disabled as per IRCv3 specifications.
292 * @param[in] channelOrNick Channel or nickname to WHO
294 void queueAutoWhoOneshot(const QString &channelOrNick);
296 bool setAutoWhoDone(const QString &channel);
298 void updateIssuedModes(const QString &requestedModes);
299 void updatePersistentModes(QString addModes, QString removeModes);
300 void resetPersistentModes();
302 Server usedServer() const;
304 inline void resetPingTimeout() { _pingCount = 0; }
306 inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
308 emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
313 void recvRawServerMsg(QString);
314 void displayStatusMsg(QString);
315 void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
316 void disconnected(NetworkId networkId);
317 void connectionError(const QString &errorMsg);
319 void quitRequested(NetworkId networkId);
320 void sslErrors(const QVariant &errorData);
322 void newEvent(Event *event);
323 void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
324 void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
327 inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
328 inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
331 // TODO: remove cached cipher keys, when appropriate
332 //virtual void removeIrcUser(IrcUser *ircuser);
333 //virtual void removeIrcChannel(IrcChannel *ircChannel);
334 //virtual void removeChansAndUsers();
337 void socketHasData();
338 void socketError(QAbstractSocket::SocketError);
339 void socketInitialized();
340 inline void socketCloseTimeout() { socket.abort(); }
341 void socketDisconnected();
342 void socketStateChanged(QAbstractSocket::SocketState);
343 void networkInitialized();
346 void restoreUserModes();
347 void doAutoReconnect();
349 void enablePingTimeout(bool enable = true);
350 void disablePingTimeout();
352 void startAutoWhoCycle();
355 void sslErrors(const QList<QSslError> &errors);
358 void fillBucketAndProcessQueue();
360 void writeToSocket(const QByteArray &data);
363 CoreSession *_coreSession;
371 CoreUserInputHandler *_userInputHandler;
373 QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
375 QTimer _autoReconnectTimer;
376 int _autoReconnectCount;
378 QTimer _socketCloseTimer;
380 /* this flag triggers quitRequested() once the socket is closed
381 * it is needed to determine whether or not the connection needs to be
382 * in the automatic session restore. */
386 bool _disconnectExpected; /// If true, connection is quitting, expect a socket close
387 // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
388 // specifying a permanent (saved to core session) disconnect.
390 bool _previousConnectionAttemptFailed;
391 int _lastUsedServerIndex;
398 QStringList _autoWhoQueue;
399 QHash<QString, int> _autoWhoPending;
400 QTimer _autoWhoTimer, _autoWhoCycleTimer;
402 // Maintain a list of CAPs that are being checked; if empty, negotiation finished
403 // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
404 QStringList _capsQueued; /// Capabilities to be checked
405 bool _capNegotiationActive; /// Whether or not full capability negotiation was started
406 // Avoid displaying repeat "negotiation finished" messages
407 bool _capInitialNegotiationEnded; /// Whether or not initial capability negotiation finished
408 // Avoid sending repeat "CAP END" replies when registration is already ended
411 * Gets the next capability to request, removing it from the queue.
413 * @returns Name of capability to request
415 QString takeQueuedCap();
417 QTimer _tokenBucketTimer;
418 int _messageDelay; // token refill speed in ms
419 int _burstSize; // size of the token bucket
420 int _tokenBucket; // the virtual bucket that holds the tokens
421 QList<QByteArray> _msgQueue;
423 QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
425 // List of blowfish keys for channels
426 QHash<QString, QByteArray> _cipherKeys;
430 #endif //CORENETWORK_H