Add support for userhost-in-names capability
[quassel.git] / src / core / corenetwork.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2015 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #ifndef CORENETWORK_H
22 #define CORENETWORK_H
23
24 #include "network.h"
25 #include "coreircchannel.h"
26 #include "coreircuser.h"
27
28 #include <QTimer>
29
30 #ifdef HAVE_SSL
31 # include <QSslSocket>
32 # include <QSslError>
33 #else
34 # include <QTcpSocket>
35 #endif
36
37 #ifdef HAVE_QCA2
38 #  include "cipher.h"
39 #endif
40
41 #include "coresession.h"
42
43 #include <functional>
44
45 class CoreIdentity;
46 class CoreUserInputHandler;
47 class CoreIgnoreListManager;
48 class Event;
49
50 class CoreNetwork : public Network
51 {
52     SYNCABLE_OBJECT
53         Q_OBJECT
54
55 public:
56     CoreNetwork(const NetworkId &networkid, CoreSession *session);
57     ~CoreNetwork();
58     inline virtual const QMetaObject *syncMetaObject() const { return &Network::staticMetaObject; }
59
60     inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); }
61     inline CoreSession *coreSession() const { return _coreSession; }
62     inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); }
63
64     inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; }
65     inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); }
66
67     //! Decode a string using the server (network) decoding.
68     inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); }
69
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;
72
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;
75
76     //! Encode a string using the server (network) encoding.
77     inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); }
78
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;
81
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;
84
85     inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); }
86
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; }
89
90     inline bool isAutoWhoInProgress(const QString &channel) const { return _autoWhoPending.value(channel.toLower(), 0); }
91
92     inline UserId userId() const { return _coreSession->user(); }
93
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(); }
100
101     QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator);
102
103     // IRCv3 capability negotiation
104
105     /**
106      * Checks if a given capability is enabled.
107      *
108      * @returns True if enabled, otherwise false
109      */
110     inline bool capEnabled(const QString &capability) const { return _capsSupported.contains(capability); }
111
112     /**
113      * Checks if capability negotiation is currently ongoing.
114      *
115      * @returns True if in progress, otherwise false
116      */
117     inline bool capNegotiationInProgress() const { return !_capsQueued.empty(); }
118
119     /**
120      * Gets the value of an enabled or pending capability, e.g. sasl=plain.
121      *
122      * @returns Value of capability if one was specified, otherwise empty string
123      */
124     QString capValue(const QString &capability) const;
125
126     /**
127      * Gets the next capability to request, removing it from the queue.
128      *
129      * @returns Name of capability to request
130      */
131     QString takeQueuedCap();
132
133     // Specific capabilities for easy reference
134
135     /**
136      * Gets the status of the sasl authentication capability.
137      *
138      * http://ircv3.net/specs/extensions/sasl-3.2.html
139      *
140      * @returns True if SASL authentication is enabled, otherwise false
141      */
142     inline bool useCapSASL() const { return capEnabled("sasl"); }
143
144     /**
145      * Gets the status of the away-notify capability.
146      *
147      * http://ircv3.net/specs/extensions/away-notify-3.1.html
148      *
149      * @returns True if away-notify is enabled, otherwise false
150      */
151     inline bool useCapAwayNotify() const { return capEnabled("away-notify"); }
152
153     /**
154      * Gets the status of the account-notify capability.
155      *
156      * http://ircv3.net/specs/extensions/account-notify-3.1.html
157      *
158      * @returns True if account-notify is enabled, otherwise false
159      */
160     inline bool useCapAccountNotify() const { return capEnabled("account-notify"); }
161
162     /**
163      * Gets the status of the extended-join capability.
164      *
165      * http://ircv3.net/specs/extensions/extended-join-3.1.html
166      *
167      * @returns True if extended-join is enabled, otherwise false
168      */
169     inline bool useCapExtendedJoin() const { return capEnabled("extended-join"); }
170
171     /**
172      * Gets the status of the userhost-in-names capability.
173      *
174      * http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
175      *
176      * @returns True if userhost-in-names is enabled, otherwise false
177      */
178     inline bool useCapUserhostInNames() const { return capEnabled("userhost-in-names"); }
179
180 public slots:
181     virtual void setMyNick(const QString &mynick);
182
183     virtual void requestConnect() const;
184     virtual void requestDisconnect() const;
185     virtual void requestSetNetworkInfo(const NetworkInfo &info);
186
187     virtual void setUseAutoReconnect(bool);
188     virtual void setAutoReconnectInterval(quint32);
189     virtual void setAutoReconnectRetries(quint16);
190
191     void setPingInterval(int interval);
192
193     void connectToIrc(bool reconnecting = false);
194     void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false);
195
196     void userInput(BufferInfo bufferInfo, QString msg);
197     void putRawLine(QByteArray input);
198     void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray());
199     void putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix = QByteArray());
200
201     void setChannelJoined(const QString &channel);
202     void setChannelParted(const QString &channel);
203     void addChannelKey(const QString &channel, const QString &key);
204     void removeChannelKey(const QString &channel);
205
206     // Blowfish stuff
207 #ifdef HAVE_QCA2
208     Cipher *cipher(const QString &recipient);
209     QByteArray cipherKey(const QString &recipient) const;
210     void setCipherKey(const QString &recipient, const QByteArray &key);
211     bool cipherUsesCBC(const QString &target);
212 #endif
213
214     // IRCv3 capability negotiation (can be connected to signals)
215
216     /**
217      * Marks a capability as accepted, providing an optional value.
218      *
219      * Removes it from queue of pending capabilities and triggers any capability-specific
220      * activation.
221      *
222      * @param[in] capability Name of the capability
223      * @param[in] value
224      * @parblock
225      * Optional value of the capability, e.g. sasl=plain.  If left empty, will be copied from the
226      * pending capability.
227      * @endparblock
228      */
229     void addCap(const QString &capability, const QString &value = QString());
230
231     /**
232      * Marks a capability as denied.
233      *
234      * Removes it from the queue of pending capabilities and triggers any capability-specific
235      * deactivation.
236      *
237      * @param[in] capability Name of the capability
238      */
239     void removeCap(const QString &capability);
240
241     /**
242      * Queues a capability as available but not yet accepted or denied.
243      *
244      * Capabilities should be queued when registration pauses for CAP LS for capabilities are only
245      * requested during login.
246      *
247      * @param[in] capability Name of the capability
248      * @param[in] value      Optional value of the capability, e.g. sasl=plain
249      */
250     void queuePendingCap(const QString &capability, const QString &value = QString());
251
252     void setAutoWhoEnabled(bool enabled);
253     void setAutoWhoInterval(int interval);
254     void setAutoWhoDelay(int delay);
255
256     /**
257      * Appends the given channel/nick to the front of the AutoWho queue.
258      *
259      * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
260      * who-cycles are disabled as per IRCv3 specifications.
261      *
262      * @param[in] channelOrNick Channel or nickname to WHO
263      */
264     void queueAutoWhoOneshot(const QString &channelOrNick);
265
266     bool setAutoWhoDone(const QString &channel);
267
268     void updateIssuedModes(const QString &requestedModes);
269     void updatePersistentModes(QString addModes, QString removeModes);
270     void resetPersistentModes();
271
272     Server usedServer() const;
273
274     inline void resetPingTimeout() { _pingCount = 0; }
275
276     inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
277     {
278         emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
279     }
280
281
282 signals:
283     void recvRawServerMsg(QString);
284     void displayStatusMsg(QString);
285     void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
286     void disconnected(NetworkId networkId);
287     void connectionError(const QString &errorMsg);
288
289     void quitRequested(NetworkId networkId);
290     void sslErrors(const QVariant &errorData);
291
292     void newEvent(Event *event);
293     void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
294     void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
295
296 protected:
297     inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
298     inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
299
300 protected slots:
301     // TODO: remove cached cipher keys, when appropriate
302     //virtual void removeIrcUser(IrcUser *ircuser);
303     //virtual void removeIrcChannel(IrcChannel *ircChannel);
304     //virtual void removeChansAndUsers();
305
306 private slots:
307     void socketHasData();
308     void socketError(QAbstractSocket::SocketError);
309     void socketInitialized();
310     inline void socketCloseTimeout() { socket.abort(); }
311     void socketDisconnected();
312     void socketStateChanged(QAbstractSocket::SocketState);
313     void networkInitialized();
314
315     void sendPerform();
316     void restoreUserModes();
317     void doAutoReconnect();
318     void sendPing();
319     void enablePingTimeout(bool enable = true);
320     void disablePingTimeout();
321     void sendAutoWho();
322     void startAutoWhoCycle();
323
324 #ifdef HAVE_SSL
325     void sslErrors(const QList<QSslError> &errors);
326 #endif
327
328     void fillBucketAndProcessQueue();
329
330     void writeToSocket(const QByteArray &data);
331
332 private:
333     CoreSession *_coreSession;
334
335 #ifdef HAVE_SSL
336     QSslSocket socket;
337 #else
338     QTcpSocket socket;
339 #endif
340
341     CoreUserInputHandler *_userInputHandler;
342
343     QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
344
345     QTimer _autoReconnectTimer;
346     int _autoReconnectCount;
347
348     QTimer _socketCloseTimer;
349
350     /* this flag triggers quitRequested() once the socket is closed
351      * it is needed to determine whether or not the connection needs to be
352      * in the automatic session restore. */
353     bool _quitRequested;
354     QString _quitReason;
355
356     bool _previousConnectionAttemptFailed;
357     int _lastUsedServerIndex;
358
359     QTimer _pingTimer;
360     uint _lastPingTime;
361     uint _pingCount;
362     bool _sendPings;
363
364     QStringList _autoWhoQueue;
365     QHash<QString, int> _autoWhoPending;
366     QTimer _autoWhoTimer, _autoWhoCycleTimer;
367
368     // CAPs may have parameter values
369     // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
370     QStringList _capsQueued;                /// Capabilities to be checked
371     QHash<QString, QString> _capsPending;   /// Capabilities pending 'CAP ACK' from server
372     QHash<QString, QString> _capsSupported; /// Enabled capabilities that received 'CAP ACK'
373
374     QTimer _tokenBucketTimer;
375     int _messageDelay;      // token refill speed in ms
376     int _burstSize;         // size of the token bucket
377     int _tokenBucket;       // the virtual bucket that holds the tokens
378     QList<QByteArray> _msgQueue;
379
380     QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
381
382     // List of blowfish keys for channels
383     QHash<QString, QByteArray> _cipherKeys;
384 };
385
386
387 #endif //CORENETWORK_H