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);
103 // IRCv3 capability negotiation
106 * Checks if a given capability is enabled.
108 * @returns True if enabled, otherwise false
110 inline bool capEnabled(const QString &capability) const { return _capsSupported.contains(capability); }
113 * Checks if capability negotiation is currently ongoing.
115 * @returns True if in progress, otherwise false
117 inline bool capNegotiationInProgress() const { return !_capsQueued.empty(); }
120 * Gets the value of an enabled or pending capability, e.g. sasl=plain.
122 * @returns Value of capability if one was specified, otherwise empty string
124 QString capValue(const QString &capability) const;
127 * Gets the next capability to request, removing it from the queue.
129 * @returns Name of capability to request
131 QString takeQueuedCap();
133 // Specific capabilities for easy reference
136 * Gets the status of the sasl authentication capability.
138 * http://ircv3.net/specs/extensions/sasl-3.2.html
140 * @returns True if SASL authentication is enabled, otherwise false
142 inline bool useCapSASL() const { return capEnabled("sasl"); }
145 * Gets the status of the away-notify capability.
147 * http://ircv3.net/specs/extensions/away-notify-3.1.html
149 * @returns True if away-notify is enabled, otherwise false
151 inline bool useCapAwayNotify() const { return capEnabled("away-notify"); }
154 * Gets the status of the account-notify capability.
156 * http://ircv3.net/specs/extensions/account-notify-3.1.html
158 * @returns True if account-notify is enabled, otherwise false
160 inline bool useCapAccountNotify() const { return capEnabled("account-notify"); }
163 * Gets the status of the extended-join capability.
165 * http://ircv3.net/specs/extensions/extended-join-3.1.html
167 * @returns True if extended-join is enabled, otherwise false
169 inline bool useCapExtendedJoin() const { return capEnabled("extended-join"); }
172 * Gets the status of the userhost-in-names capability.
174 * http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
176 * @returns True if userhost-in-names is enabled, otherwise false
178 inline bool useCapUserhostInNames() const { return capEnabled("userhost-in-names"); }
181 * Gets the status of the multi-prefix capability.
183 * http://ircv3.net/specs/extensions/multi-prefix-3.1.html
185 * @returns True if multi-prefix is enabled, otherwise false
187 inline bool useCapMultiPrefix() const { return capEnabled("multi-prefix"); }
190 virtual void setMyNick(const QString &mynick);
192 virtual void requestConnect() const;
193 virtual void requestDisconnect() const;
194 virtual void requestSetNetworkInfo(const NetworkInfo &info);
196 virtual void setUseAutoReconnect(bool);
197 virtual void setAutoReconnectInterval(quint32);
198 virtual void setAutoReconnectRetries(quint16);
200 void setPingInterval(int interval);
202 void connectToIrc(bool reconnecting = false);
203 void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false);
205 void userInput(BufferInfo bufferInfo, QString msg);
206 void putRawLine(QByteArray input);
207 void putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = QByteArray());
208 void putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = QByteArray());
210 void setChannelJoined(const QString &channel);
211 void setChannelParted(const QString &channel);
212 void addChannelKey(const QString &channel, const QString &key);
213 void removeChannelKey(const QString &channel);
217 Cipher *cipher(const QString &recipient);
218 QByteArray cipherKey(const QString &recipient) const;
219 void setCipherKey(const QString &recipient, const QByteArray &key);
220 bool cipherUsesCBC(const QString &target);
223 // IRCv3 capability negotiation (can be connected to signals)
226 * Marks a capability as accepted, providing an optional value.
228 * Removes it from queue of pending capabilities and triggers any capability-specific
231 * @param[in] capability Name of the capability
234 * Optional value of the capability, e.g. sasl=plain. If left empty, will be copied from the
235 * pending capability.
238 void addCap(const QString &capability, const QString &value = QString());
241 * Marks a capability as denied.
243 * Removes it from the queue of pending capabilities and triggers any capability-specific
246 * @param[in] capability Name of the capability
248 void removeCap(const QString &capability);
251 * Queues a capability as available but not yet accepted or denied.
253 * Capabilities should be queued when registration pauses for CAP LS for capabilities are only
254 * requested during login.
256 * @param[in] capability Name of the capability
257 * @param[in] value Optional value of the capability, e.g. sasl=plain
259 void queuePendingCap(const QString &capability, const QString &value = QString());
261 void setAutoWhoEnabled(bool enabled);
262 void setAutoWhoInterval(int interval);
263 void setAutoWhoDelay(int delay);
266 * Appends the given channel/nick to the front of the AutoWho queue.
268 * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
269 * who-cycles are disabled as per IRCv3 specifications.
271 * @param[in] channelOrNick Channel or nickname to WHO
273 void queueAutoWhoOneshot(const QString &channelOrNick);
275 bool setAutoWhoDone(const QString &channel);
277 void updateIssuedModes(const QString &requestedModes);
278 void updatePersistentModes(QString addModes, QString removeModes);
279 void resetPersistentModes();
281 Server usedServer() const;
283 inline void resetPingTimeout() { _pingCount = 0; }
285 inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
287 emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
292 void recvRawServerMsg(QString);
293 void displayStatusMsg(QString);
294 void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
295 void disconnected(NetworkId networkId);
296 void connectionError(const QString &errorMsg);
298 void quitRequested(NetworkId networkId);
299 void sslErrors(const QVariant &errorData);
301 void newEvent(Event *event);
302 void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
303 void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
306 inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
307 inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
310 // TODO: remove cached cipher keys, when appropriate
311 //virtual void removeIrcUser(IrcUser *ircuser);
312 //virtual void removeIrcChannel(IrcChannel *ircChannel);
313 //virtual void removeChansAndUsers();
316 void socketHasData();
317 void socketError(QAbstractSocket::SocketError);
318 void socketInitialized();
319 inline void socketCloseTimeout() { socket.abort(); }
320 void socketDisconnected();
321 void socketStateChanged(QAbstractSocket::SocketState);
322 void networkInitialized();
325 void restoreUserModes();
326 void doAutoReconnect();
328 void enablePingTimeout(bool enable = true);
329 void disablePingTimeout();
331 void startAutoWhoCycle();
334 void sslErrors(const QList<QSslError> &errors);
337 void fillBucketAndProcessQueue();
339 void writeToSocket(const QByteArray &data);
342 CoreSession *_coreSession;
350 CoreUserInputHandler *_userInputHandler;
352 QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
354 QTimer _autoReconnectTimer;
355 int _autoReconnectCount;
357 QTimer _socketCloseTimer;
359 /* this flag triggers quitRequested() once the socket is closed
360 * it is needed to determine whether or not the connection needs to be
361 * in the automatic session restore. */
365 bool _previousConnectionAttemptFailed;
366 int _lastUsedServerIndex;
373 QStringList _autoWhoQueue;
374 QHash<QString, int> _autoWhoPending;
375 QTimer _autoWhoTimer, _autoWhoCycleTimer;
377 // CAPs may have parameter values
378 // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
379 QStringList _capsQueued; /// Capabilities to be checked
380 QHash<QString, QString> _capsPending; /// Capabilities pending 'CAP ACK' from server
381 QHash<QString, QString> _capsSupported; /// Enabled capabilities that received 'CAP ACK'
383 QTimer _tokenBucketTimer;
384 int _messageDelay; // token refill speed in ms
385 int _burstSize; // size of the token bucket
386 int _tokenBucket; // the virtual bucket that holds the tokens
387 QList<QByteArray> _msgQueue;
389 QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
391 // List of blowfish keys for channels
392 QHash<QString, QByteArray> _cipherKeys;
396 #endif //CORENETWORK_H