Handle IRCv3 servers without any capabilities
[quassel.git] / src / core / corenetwork.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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 // IRCv3 capabilities
29 #include "irccap.h"
30
31 #include <QTimer>
32
33 #ifdef HAVE_SSL
34 # include <QSslSocket>
35 # include <QSslError>
36 #else
37 # include <QTcpSocket>
38 #endif
39
40 #ifdef HAVE_QCA2
41 #  include "cipher.h"
42 #endif
43
44 #include "coresession.h"
45
46 #include <functional>
47
48 class CoreIdentity;
49 class CoreUserInputHandler;
50 class CoreIgnoreListManager;
51 class Event;
52
53 class CoreNetwork : public Network
54 {
55     SYNCABLE_OBJECT
56         Q_OBJECT
57
58 public:
59     CoreNetwork(const NetworkId &networkid, CoreSession *session);
60     ~CoreNetwork();
61     inline virtual const QMetaObject *syncMetaObject() const { return &Network::staticMetaObject; }
62
63     inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); }
64     inline CoreSession *coreSession() const { return _coreSession; }
65     inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); }
66
67     inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; }
68     inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); }
69
70     //! Decode a string using the server (network) decoding.
71     inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); }
72
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;
75
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;
78
79     //! Encode a string using the server (network) encoding.
80     inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); }
81
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;
84
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;
87
88     inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); }
89
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; }
92
93     inline bool isAutoWhoInProgress(const QString &channel) const { return _autoWhoPending.value(channel.toLower(), 0); }
94
95     inline UserId userId() const { return _coreSession->user(); }
96
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(); }
103
104     QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator);
105
106     // IRCv3 capability negotiation
107
108     /**
109      * Checks if capability negotiation is currently ongoing.
110      *
111      * @returns True if in progress, otherwise false
112      */
113     inline bool capNegotiationInProgress() const { return !_capsQueued.empty(); }
114
115     /**
116      * Queues a capability to be requested.
117      *
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.
120      *
121      * @param[in] capability Name of the capability
122      */
123     void queueCap(const QString &capability);
124
125     /**
126      * Begins capability negotiation if capabilities are queued, otherwise returns.
127      *
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.
130      */
131     void beginCapNegotiation();
132
133     /**
134      * Ends capability negotiation.
135      *
136      * This won't have effect if other CAP commands are in the command queue before calling this
137      * command.  It should only be called when capability negotiation is complete.
138      */
139     void endCapNegotiation();
140
141     /**
142      * List of capabilities requiring further core<->server messages to configure.
143      *
144      * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
145      * be immediately sent.
146      *
147      * See: http://ircv3.net/specs/extensions/sasl-3.2.html
148      */
149     const QStringList capsRequiringConfiguration = QStringList {
150         IrcCap::SASL
151     };
152
153 public slots:
154     virtual void setMyNick(const QString &mynick);
155
156     virtual void requestConnect() const;
157     virtual void requestDisconnect() const;
158     virtual void requestSetNetworkInfo(const NetworkInfo &info);
159
160     virtual void setUseAutoReconnect(bool);
161     virtual void setAutoReconnectInterval(quint32);
162     virtual void setAutoReconnectRetries(quint16);
163
164     void setPingInterval(int interval);
165
166     void connectToIrc(bool reconnecting = false);
167     /**
168      * Disconnect from the IRC server.
169      *
170      * Begin disconnecting from the IRC server, including optionally reconnecting.
171      *
172      * @param requested       If true, user requested this disconnect; don't try to reconnect
173      * @param reason          Reason for quitting, defaulting to the user-configured quit reason
174      * @param withReconnect   Reconnect to the network after disconnecting (e.g. ping timeout)
175      * @param forceImmediate  Immediately disconnect from network, skipping queue of other commands
176      */
177     void disconnectFromIrc(bool requested = true, const QString &reason = QString(),
178                            bool withReconnect = false, bool forceImmediate = false);
179
180     /**
181      * Forcibly close the IRC server socket, waiting for it to close.
182      *
183      * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
184      * be sure the network's disconencted (e.g. clean-up), call this.
185      *
186      * @param msecs  Maximum time to wait for socket to close, in milliseconds.
187      * @return True if socket closes successfully; false if error occurs or timeout reached
188      */
189     bool forceDisconnect(int msecs = 1000);
190
191     void userInput(BufferInfo bufferInfo, QString msg);
192
193     /**
194      * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
195      *
196      * @param[in] input   QByteArray of encoded characters
197      * @param[in] prepend
198      * @parmblock
199      * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
200      * end.  This should be used sparingly, for if either the core or the IRC server cannot maintain
201      * PING/PONG replies, the other side will close the connection.
202      * @endparmblock
203      */
204     void putRawLine(const QByteArray input, const bool prepend = false);
205
206     /**
207      * Sends the command with encoded parameters, with optional prefix or high priority.
208      *
209      * @param[in] cmd      Command to send, ignoring capitalization
210      * @param[in] params   Parameters for the command, encoded within a QByteArray
211      * @param[in] prefix   Optional command prefix
212      * @param[in] prepend
213      * @parmblock
214      * If true, the command is prepended into the start of the queue, otherwise, it's appended to
215      * the end.  This should be used sparingly, for if either the core or the IRC server cannot
216      * maintain PING/PONG replies, the other side will close the connection.
217      * @endparmblock
218      */
219     void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray(), const bool prepend = false);
220
221     /**
222      * Sends the command for each set of encoded parameters, with optional prefix or high priority.
223      *
224      * @param[in] cmd         Command to send, ignoring capitalization
225      * @param[in] params
226      * @parmblock
227      * List of parameter lists for the command, encoded within a QByteArray.  The command will be
228      * sent multiple times, once for each set of params stored within the outer list.
229      * @endparmblock
230      * @param[in] prefix      Optional command prefix
231      * @param[in] prependAll
232      * @parmblock
233      * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
234      * appended to the end.  This should be used sparingly, for if either the core or the IRC server
235      * cannot maintain PING/PONG replies, the other side will close the connection.
236      * @endparmblock
237      */
238     void putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix = QByteArray(), const bool prependAll = false);
239
240     void setChannelJoined(const QString &channel);
241     void setChannelParted(const QString &channel);
242     void addChannelKey(const QString &channel, const QString &key);
243     void removeChannelKey(const QString &channel);
244
245     // Blowfish stuff
246 #ifdef HAVE_QCA2
247     Cipher *cipher(const QString &recipient);
248     QByteArray cipherKey(const QString &recipient) const;
249     void setCipherKey(const QString &recipient, const QByteArray &key);
250     bool cipherUsesCBC(const QString &target);
251 #endif
252
253     // IRCv3 capability negotiation (can be connected to signals)
254
255     /**
256      * Indicates a capability is now available, with optional value in Network::capValue().
257      *
258      * @see Network::addCap()
259      *
260      * @param[in] capability Name of the capability
261      */
262     void serverCapAdded(const QString &capability);
263
264     /**
265      * Indicates a capability was acknowledged (enabled by the IRC server).
266      *
267      * @see Network::acknowledgeCap()
268      *
269      * @param[in] capability Name of the capability
270      */
271     void serverCapAcknowledged(const QString &capability);
272
273     /**
274      * Indicates a capability was removed from the list of available capabilities.
275      *
276      * @see Network::removeCap()
277      *
278      * @param[in] capability Name of the capability
279      */
280     void serverCapRemoved(const QString &capability);
281
282     /**
283      * Sends the next capability from the queue.
284      *
285      * During nick registration if any capabilities remain queued, this will take the next and
286      * request it.  When no capabilities remain, capability negotiation is ended.
287      */
288     void sendNextCap();
289
290     void setAutoWhoEnabled(bool enabled);
291     void setAutoWhoInterval(int interval);
292     void setAutoWhoDelay(int delay);
293
294     /**
295      * Appends the given channel/nick to the front of the AutoWho queue.
296      *
297      * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
298      * who-cycles are disabled as per IRCv3 specifications.
299      *
300      * @param[in] channelOrNick Channel or nickname to WHO
301      */
302     void queueAutoWhoOneshot(const QString &channelOrNick);
303
304     bool setAutoWhoDone(const QString &channel);
305
306     void updateIssuedModes(const QString &requestedModes);
307     void updatePersistentModes(QString addModes, QString removeModes);
308     void resetPersistentModes();
309
310     Server usedServer() const;
311
312     inline void resetPingTimeout() { _pingCount = 0; }
313
314     inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
315     {
316         emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
317     }
318
319
320 signals:
321     void recvRawServerMsg(QString);
322     void displayStatusMsg(QString);
323     void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
324     void disconnected(NetworkId networkId);
325     void connectionError(const QString &errorMsg);
326
327     void quitRequested(NetworkId networkId);
328     void sslErrors(const QVariant &errorData);
329
330     void newEvent(Event *event);
331     void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
332     void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
333
334 protected:
335     inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
336     inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
337
338 protected slots:
339     // TODO: remove cached cipher keys, when appropriate
340     //virtual void removeIrcUser(IrcUser *ircuser);
341     //virtual void removeIrcChannel(IrcChannel *ircChannel);
342     //virtual void removeChansAndUsers();
343
344 private slots:
345     void socketHasData();
346     void socketError(QAbstractSocket::SocketError);
347     void socketInitialized();
348     inline void socketCloseTimeout() { socket.abort(); }
349     void socketDisconnected();
350     void socketStateChanged(QAbstractSocket::SocketState);
351     void networkInitialized();
352
353     void sendPerform();
354     void restoreUserModes();
355     void doAutoReconnect();
356     void sendPing();
357     void enablePingTimeout(bool enable = true);
358     void disablePingTimeout();
359     void sendAutoWho();
360     void startAutoWhoCycle();
361
362 #ifdef HAVE_SSL
363     void sslErrors(const QList<QSslError> &errors);
364 #endif
365
366     void fillBucketAndProcessQueue();
367
368     void writeToSocket(const QByteArray &data);
369
370 private:
371     CoreSession *_coreSession;
372
373 #ifdef HAVE_SSL
374     QSslSocket socket;
375 #else
376     QTcpSocket socket;
377 #endif
378
379     CoreUserInputHandler *_userInputHandler;
380
381     QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
382
383     QTimer _autoReconnectTimer;
384     int _autoReconnectCount;
385
386     QTimer _socketCloseTimer;
387
388     /* this flag triggers quitRequested() once the socket is closed
389      * it is needed to determine whether or not the connection needs to be
390      * in the automatic session restore. */
391     bool _quitRequested;
392     QString _quitReason;
393
394     bool _disconnectExpected;  /// If true, connection is quitting, expect a socket close
395     // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
396     // specifying a permanent (saved to core session) disconnect.
397
398     bool _previousConnectionAttemptFailed;
399     int _lastUsedServerIndex;
400
401     QTimer _pingTimer;
402     uint _lastPingTime;
403     uint _pingCount;
404     bool _sendPings;
405
406     QStringList _autoWhoQueue;
407     QHash<QString, int> _autoWhoPending;
408     QTimer _autoWhoTimer, _autoWhoCycleTimer;
409
410     // Maintain a list of CAPs that are being checked; if empty, negotiation finished
411     // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
412     QStringList _capsQueued;           /// Capabilities to be checked
413     bool _capNegotiationActive;        /// Whether or not full capability negotiation was started
414     // Avoid displaying repeat "negotiation finished" messages
415     bool _capInitialNegotiationEnded;  /// Whether or not initial capability negotiation finished
416     // Avoid sending repeat "CAP END" replies when registration is already ended
417
418     /**
419      * Gets the next capability to request, removing it from the queue.
420      *
421      * @returns Name of capability to request
422      */
423     QString takeQueuedCap();
424
425     QTimer _tokenBucketTimer;
426     int _messageDelay;      // token refill speed in ms
427     int _burstSize;         // size of the token bucket
428     int _tokenBucket;       // the virtual bucket that holds the tokens
429     QList<QByteArray> _msgQueue;
430
431     QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
432
433     // List of blowfish keys for channels
434     QHash<QString, QByteArray> _cipherKeys;
435 };
436
437
438 #endif //CORENETWORK_H