1 /***************************************************************************
2 * Copyright (C) 2005-2015 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"
31 # include <QSslSocket>
34 # include <QTcpSocket>
41 #include "coresession.h"
46 class CoreUserInputHandler;
47 class CoreIgnoreListManager;
50 class CoreNetwork : public Network
56 CoreNetwork(const NetworkId &networkid, CoreSession *session);
58 inline virtual const QMetaObject *syncMetaObject() const { return &Network::staticMetaObject; }
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; }
90 inline bool isAutoWhoInProgress(const QString &channel) const { return _autoWhoPending.value(channel.toLower(), 0); }
92 inline UserId userId() const { return _coreSession->user(); }
94 inline QAbstractSocket::SocketState socketState() const { return socket.state(); }
95 inline bool socketConnected() const { return socket.state() == QAbstractSocket::ConnectedState; }
96 inline QHostAddress localAddress() const { return socket.localAddress(); }
97 inline QHostAddress peerAddress() const { return socket.peerAddress(); }
98 inline quint16 localPort() const { return socket.localPort(); }
99 inline quint16 peerPort() const { return socket.peerPort(); }
101 QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator);
104 virtual void setMyNick(const QString &mynick);
106 virtual void requestConnect() const;
107 virtual void requestDisconnect() const;
108 virtual void requestSetNetworkInfo(const NetworkInfo &info);
110 virtual void setUseAutoReconnect(bool);
111 virtual void setAutoReconnectInterval(quint32);
112 virtual void setAutoReconnectRetries(quint16);
114 void setPingInterval(int interval);
116 void connectToIrc(bool reconnecting = false);
118 * Disconnect from the IRC server.
120 * Begin disconnecting from the IRC server, including optionally reconnecting.
122 * @param requested If true, user requested this disconnect; don't try to reconnect
123 * @param reason Reason for quitting, defaulting to the user-configured quit reason
124 * @param withReconnect Reconnect to the network after disconnecting (e.g. ping timeout)
125 * @param forceImmediate Immediately disconnect from network, skipping queue of other commands
127 void disconnectFromIrc(bool requested = true, const QString &reason = QString(),
128 bool withReconnect = false, bool forceImmediate = false);
131 * Forcibly close the IRC server socket, waiting for it to close.
133 * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
134 * be sure the network's disconencted (e.g. clean-up), call this.
136 * @param msecs Maximum time to wait for socket to close, in milliseconds.
137 * @return True if socket closes successfully; false if error occurs or timeout reached
139 bool forceDisconnect(int msecs = 1000);
141 void userInput(BufferInfo bufferInfo, QString msg);
144 * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
146 * @param[in] input QByteArray of encoded characters
149 * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
150 * end. This should be used sparingly, for if either the core or the IRC server cannot maintain
151 * PING/PONG replies, the other side will close the connection.
154 void putRawLine(const QByteArray input, const bool prepend = false);
157 * Sends the command with encoded parameters, with optional prefix or high priority.
159 * @param[in] cmd Command to send, ignoring capitalization
160 * @param[in] params Parameters for the command, encoded within a QByteArray
161 * @param[in] prefix Optional command prefix
164 * If true, the command is prepended into the start of the queue, otherwise, it's appended to
165 * the end. This should be used sparingly, for if either the core or the IRC server cannot
166 * maintain PING/PONG replies, the other side will close the connection.
169 void putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = QByteArray(), const bool prepend = false);
172 * Sends the command for each set of encoded parameters, with optional prefix or high priority.
174 * @param[in] cmd Command to send, ignoring capitalization
177 * List of parameter lists for the command, encoded within a QByteArray. The command will be
178 * sent multiple times, once for each set of params stored within the outer list.
180 * @param[in] prefix Optional command prefix
181 * @param[in] prependAll
183 * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
184 * appended to the end. This should be used sparingly, for if either the core or the IRC server
185 * cannot maintain PING/PONG replies, the other side will close the connection.
188 void putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = QByteArray(), const bool prependAll = false);
190 void setChannelJoined(const QString &channel);
191 void setChannelParted(const QString &channel);
192 void addChannelKey(const QString &channel, const QString &key);
193 void removeChannelKey(const QString &channel);
197 Cipher *cipher(const QString &recipient);
198 QByteArray cipherKey(const QString &recipient) const;
199 void setCipherKey(const QString &recipient, const QByteArray &key);
200 bool cipherUsesCBC(const QString &target);
203 void setAutoWhoEnabled(bool enabled);
204 void setAutoWhoInterval(int interval);
205 void setAutoWhoDelay(int delay);
207 bool setAutoWhoDone(const QString &channel);
209 void updateIssuedModes(const QString &requestedModes);
210 void updatePersistentModes(QString addModes, QString removeModes);
211 void resetPersistentModes();
213 Server usedServer() const;
215 inline void resetPingTimeout() { _pingCount = 0; }
217 inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
219 emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
224 void recvRawServerMsg(QString);
225 void displayStatusMsg(QString);
226 void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
227 void disconnected(NetworkId networkId);
228 void connectionError(const QString &errorMsg);
230 void quitRequested(NetworkId networkId);
231 void sslErrors(const QVariant &errorData);
233 void newEvent(Event *event);
234 void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
235 void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
238 inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
239 inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
242 // TODO: remove cached cipher keys, when appropriate
243 //virtual void removeIrcUser(IrcUser *ircuser);
244 //virtual void removeIrcChannel(IrcChannel *ircChannel);
245 //virtual void removeChansAndUsers();
248 void socketHasData();
249 void socketError(QAbstractSocket::SocketError);
250 void socketInitialized();
251 inline void socketCloseTimeout() { socket.abort(); }
252 void socketDisconnected();
253 void socketStateChanged(QAbstractSocket::SocketState);
254 void networkInitialized();
257 void restoreUserModes();
258 void doAutoReconnect();
260 void enablePingTimeout(bool enable = true);
261 void disablePingTimeout();
263 void startAutoWhoCycle();
266 void sslErrors(const QList<QSslError> &errors);
269 void fillBucketAndProcessQueue();
271 void writeToSocket(const QByteArray &data);
274 CoreSession *_coreSession;
282 CoreUserInputHandler *_userInputHandler;
284 QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
286 QTimer _autoReconnectTimer;
287 int _autoReconnectCount;
289 QTimer _socketCloseTimer;
291 /* this flag triggers quitRequested() once the socket is closed
292 * it is needed to determine whether or not the connection needs to be
293 * in the automatic session restore. */
297 bool _disconnectExpected; /// If true, connection is quitting, expect a socket close
298 // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
299 // specifying a permanent (saved to core session) disconnect.
301 bool _previousConnectionAttemptFailed;
302 int _lastUsedServerIndex;
309 QStringList _autoWhoQueue;
310 QHash<QString, int> _autoWhoPending;
311 QTimer _autoWhoTimer, _autoWhoCycleTimer;
313 QTimer _tokenBucketTimer;
314 int _messageDelay; // token refill speed in ms
315 int _burstSize; // size of the token bucket
316 int _tokenBucket; // the virtual bucket that holds the tokens
317 QList<QByteArray> _msgQueue;
319 QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
321 // List of blowfish keys for channels
322 QHash<QString, QByteArray> _cipherKeys;
326 #endif //CORENETWORK_H