74540be6d033f8952317349d44a08e5ec00def03
[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      * List of capabilities requiring further core<->server messages to configure.
135      *
136      * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
137      * be immediately sent.
138      *
139      * See: http://ircv3.net/specs/extensions/sasl-3.2.html
140      */
141     const QStringList capsRequiringConfiguration = QStringList {
142         IrcCap::SASL
143     };
144
145 public slots:
146     virtual void setMyNick(const QString &mynick);
147
148     virtual void requestConnect() const;
149     virtual void requestDisconnect() const;
150     virtual void requestSetNetworkInfo(const NetworkInfo &info);
151
152     virtual void setUseAutoReconnect(bool);
153     virtual void setAutoReconnectInterval(quint32);
154     virtual void setAutoReconnectRetries(quint16);
155
156     void setPingInterval(int interval);
157
158     void connectToIrc(bool reconnecting = false);
159     void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false);
160
161     void userInput(BufferInfo bufferInfo, QString msg);
162     void putRawLine(QByteArray input);
163     void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray());
164     void putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix = QByteArray());
165
166     void setChannelJoined(const QString &channel);
167     void setChannelParted(const QString &channel);
168     void addChannelKey(const QString &channel, const QString &key);
169     void removeChannelKey(const QString &channel);
170
171     // Blowfish stuff
172 #ifdef HAVE_QCA2
173     Cipher *cipher(const QString &recipient);
174     QByteArray cipherKey(const QString &recipient) const;
175     void setCipherKey(const QString &recipient, const QByteArray &key);
176     bool cipherUsesCBC(const QString &target);
177 #endif
178
179     // IRCv3 capability negotiation (can be connected to signals)
180
181     /**
182      * Indicates a capability is now available, with optional value in Network::capValue().
183      *
184      * @see Network::addCap()
185      *
186      * @param[in] capability Name of the capability
187      */
188     void serverCapAdded(const QString &capability);
189
190     /**
191      * Indicates a capability was acknowledged (enabled by the IRC server).
192      *
193      * @see Network::acknowledgeCap()
194      *
195      * @param[in] capability Name of the capability
196      */
197     void serverCapAcknowledged(const QString &capability);
198
199     /**
200      * Indicates a capability was removed from the list of available capabilities.
201      *
202      * @see Network::removeCap()
203      *
204      * @param[in] capability Name of the capability
205      */
206     void serverCapRemoved(const QString &capability);
207
208     /**
209      * Sends the next capability from the queue.
210      *
211      * During nick registration if any capabilities remain queued, this will take the next and
212      * request it.  When no capabilities remain, capability negotiation is ended.
213      */
214     void sendNextCap();
215
216     void setAutoWhoEnabled(bool enabled);
217     void setAutoWhoInterval(int interval);
218     void setAutoWhoDelay(int delay);
219
220     /**
221      * Appends the given channel/nick to the front of the AutoWho queue.
222      *
223      * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
224      * who-cycles are disabled as per IRCv3 specifications.
225      *
226      * @param[in] channelOrNick Channel or nickname to WHO
227      */
228     void queueAutoWhoOneshot(const QString &channelOrNick);
229
230     bool setAutoWhoDone(const QString &channel);
231
232     void updateIssuedModes(const QString &requestedModes);
233     void updatePersistentModes(QString addModes, QString removeModes);
234     void resetPersistentModes();
235
236     Server usedServer() const;
237
238     inline void resetPingTimeout() { _pingCount = 0; }
239
240     inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
241     {
242         emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
243     }
244
245
246 signals:
247     void recvRawServerMsg(QString);
248     void displayStatusMsg(QString);
249     void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
250     void disconnected(NetworkId networkId);
251     void connectionError(const QString &errorMsg);
252
253     void quitRequested(NetworkId networkId);
254     void sslErrors(const QVariant &errorData);
255
256     void newEvent(Event *event);
257     void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
258     void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
259
260 protected:
261     inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
262     inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
263
264 protected slots:
265     // TODO: remove cached cipher keys, when appropriate
266     //virtual void removeIrcUser(IrcUser *ircuser);
267     //virtual void removeIrcChannel(IrcChannel *ircChannel);
268     //virtual void removeChansAndUsers();
269
270 private slots:
271     void socketHasData();
272     void socketError(QAbstractSocket::SocketError);
273     void socketInitialized();
274     inline void socketCloseTimeout() { socket.abort(); }
275     void socketDisconnected();
276     void socketStateChanged(QAbstractSocket::SocketState);
277     void networkInitialized();
278
279     void sendPerform();
280     void restoreUserModes();
281     void doAutoReconnect();
282     void sendPing();
283     void enablePingTimeout(bool enable = true);
284     void disablePingTimeout();
285     void sendAutoWho();
286     void startAutoWhoCycle();
287
288 #ifdef HAVE_SSL
289     void sslErrors(const QList<QSslError> &errors);
290 #endif
291
292     void fillBucketAndProcessQueue();
293
294     void writeToSocket(const QByteArray &data);
295
296 private:
297     CoreSession *_coreSession;
298
299 #ifdef HAVE_SSL
300     QSslSocket socket;
301 #else
302     QTcpSocket socket;
303 #endif
304
305     CoreUserInputHandler *_userInputHandler;
306
307     QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
308
309     QTimer _autoReconnectTimer;
310     int _autoReconnectCount;
311
312     QTimer _socketCloseTimer;
313
314     /* this flag triggers quitRequested() once the socket is closed
315      * it is needed to determine whether or not the connection needs to be
316      * in the automatic session restore. */
317     bool _quitRequested;
318     QString _quitReason;
319
320     bool _previousConnectionAttemptFailed;
321     int _lastUsedServerIndex;
322
323     QTimer _pingTimer;
324     uint _lastPingTime;
325     uint _pingCount;
326     bool _sendPings;
327
328     QStringList _autoWhoQueue;
329     QHash<QString, int> _autoWhoPending;
330     QTimer _autoWhoTimer, _autoWhoCycleTimer;
331
332     // Maintain a list of CAPs that are being checked; if empty, negotiation finished
333     // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
334     QStringList _capsQueued;           /// Capabilities to be checked
335     bool _capNegotiationActive;        /// Whether or not full capability negotiation was started
336     // Avoid displaying repeat "negotiation finished" messages
337     bool _capInitialNegotiationEnded;  /// Whether or not initial capability negotiation finished
338     // Avoid sending repeat "CAP END" replies when registration is already ended
339
340     /**
341      * Gets the next capability to request, removing it from the queue.
342      *
343      * @returns Name of capability to request
344      */
345     QString takeQueuedCap();
346
347     QTimer _tokenBucketTimer;
348     int _messageDelay;      // token refill speed in ms
349     int _burstSize;         // size of the token bucket
350     int _tokenBucket;       // the virtual bucket that holds the tokens
351     QList<QByteArray> _msgQueue;
352
353     QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
354
355     // List of blowfish keys for channels
356     QHash<QString, QByteArray> _cipherKeys;
357 };
358
359
360 #endif //CORENETWORK_H