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