777152794ae4345402e09cfbc672cb2731c4c405
[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     /**
102      * Gets whether or not a disconnect was expected.
103      *
104      * Distinguishes desired quits from unexpected disconnections such as socket errors or timeouts.
105      *
106      * @return True if disconnect was requested, otherwise false.
107      */
108     inline bool disconnectExpected() const { return _disconnectExpected; }
109
110     QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator);
111
112 public slots:
113     virtual void setMyNick(const QString &mynick);
114
115     virtual void requestConnect() const;
116     virtual void requestDisconnect() const;
117     virtual void requestSetNetworkInfo(const NetworkInfo &info);
118
119     virtual void setUseAutoReconnect(bool);
120     virtual void setAutoReconnectInterval(quint32);
121     virtual void setAutoReconnectRetries(quint16);
122
123     void setPingInterval(int interval);
124
125     void connectToIrc(bool reconnecting = false);
126     /**
127      * Disconnect from the IRC server.
128      *
129      * Begin disconnecting from the IRC server, including optionally reconnecting.
130      *
131      * @param requested       If true, user requested this disconnect; don't try to reconnect
132      * @param reason          Reason for quitting, defaulting to the user-configured quit reason
133      * @param withReconnect   Reconnect to the network after disconnecting (e.g. ping timeout)
134      * @param forceImmediate  Immediately disconnect from network, skipping queue of other commands
135      */
136     void disconnectFromIrc(bool requested = true, const QString &reason = QString(),
137                            bool withReconnect = false, bool forceImmediate = false);
138
139     /**
140      * Forcibly close the IRC server socket, waiting for it to close.
141      *
142      * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
143      * be sure the network's disconencted (e.g. clean-up), call this.
144      *
145      * @param msecs  Maximum time to wait for socket to close, in milliseconds.
146      * @return True if socket closes successfully; false if error occurs or timeout reached
147      */
148     bool forceDisconnect(int msecs = 1000);
149
150     void userInput(BufferInfo bufferInfo, QString msg);
151
152     /**
153      * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
154      *
155      * @param[in] input   QByteArray of encoded characters
156      * @param[in] prepend
157      * @parmblock
158      * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
159      * end.  This should be used sparingly, for if either the core or the IRC server cannot maintain
160      * PING/PONG replies, the other side will close the connection.
161      * @endparmblock
162      */
163     void putRawLine(const QByteArray input, const bool prepend = false);
164
165     /**
166      * Sends the command with encoded parameters, with optional prefix or high priority.
167      *
168      * @param[in] cmd      Command to send, ignoring capitalization
169      * @param[in] params   Parameters for the command, encoded within a QByteArray
170      * @param[in] prefix   Optional command prefix
171      * @param[in] prepend
172      * @parmblock
173      * If true, the command is prepended into the start of the queue, otherwise, it's appended to
174      * the end.  This should be used sparingly, for if either the core or the IRC server cannot
175      * maintain PING/PONG replies, the other side will close the connection.
176      * @endparmblock
177      */
178     void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray(), const bool prepend = false);
179
180     /**
181      * Sends the command for each set of encoded parameters, with optional prefix or high priority.
182      *
183      * @param[in] cmd         Command to send, ignoring capitalization
184      * @param[in] params
185      * @parmblock
186      * List of parameter lists for the command, encoded within a QByteArray.  The command will be
187      * sent multiple times, once for each set of params stored within the outer list.
188      * @endparmblock
189      * @param[in] prefix      Optional command prefix
190      * @param[in] prependAll
191      * @parmblock
192      * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
193      * appended to the end.  This should be used sparingly, for if either the core or the IRC server
194      * cannot maintain PING/PONG replies, the other side will close the connection.
195      * @endparmblock
196      */
197     void putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix = QByteArray(), const bool prependAll = false);
198
199     void setChannelJoined(const QString &channel);
200     void setChannelParted(const QString &channel);
201     void addChannelKey(const QString &channel, const QString &key);
202     void removeChannelKey(const QString &channel);
203
204     // Blowfish stuff
205 #ifdef HAVE_QCA2
206     Cipher *cipher(const QString &recipient);
207     QByteArray cipherKey(const QString &recipient) const;
208     void setCipherKey(const QString &recipient, const QByteArray &key);
209     bool cipherUsesCBC(const QString &target);
210 #endif
211
212     void setAutoWhoEnabled(bool enabled);
213     void setAutoWhoInterval(int interval);
214     void setAutoWhoDelay(int delay);
215
216     bool setAutoWhoDone(const QString &channel);
217
218     void updateIssuedModes(const QString &requestedModes);
219     void updatePersistentModes(QString addModes, QString removeModes);
220     void resetPersistentModes();
221
222     Server usedServer() const;
223
224     inline void resetPingTimeout() { _pingCount = 0; }
225
226     inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
227     {
228         emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
229     }
230
231
232 signals:
233     void recvRawServerMsg(QString);
234     void displayStatusMsg(QString);
235     void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
236     void disconnected(NetworkId networkId);
237     void connectionError(const QString &errorMsg);
238
239     void quitRequested(NetworkId networkId);
240     void sslErrors(const QVariant &errorData);
241
242     void newEvent(Event *event);
243     void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
244     void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
245
246 protected:
247     inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
248     inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
249
250 protected slots:
251     // TODO: remove cached cipher keys, when appropriate
252     //virtual void removeIrcUser(IrcUser *ircuser);
253     //virtual void removeIrcChannel(IrcChannel *ircChannel);
254     //virtual void removeChansAndUsers();
255
256 private slots:
257     void socketHasData();
258     void socketError(QAbstractSocket::SocketError);
259     void socketInitialized();
260     inline void socketCloseTimeout() { socket.abort(); }
261     void socketDisconnected();
262     void socketStateChanged(QAbstractSocket::SocketState);
263     void networkInitialized();
264
265     void sendPerform();
266     void restoreUserModes();
267     void doAutoReconnect();
268     void sendPing();
269     void enablePingTimeout(bool enable = true);
270     void disablePingTimeout();
271     void sendAutoWho();
272     void startAutoWhoCycle();
273
274 #ifdef HAVE_SSL
275     void sslErrors(const QList<QSslError> &errors);
276 #endif
277
278     void fillBucketAndProcessQueue();
279
280     void writeToSocket(const QByteArray &data);
281
282 private:
283     CoreSession *_coreSession;
284
285 #ifdef HAVE_SSL
286     QSslSocket socket;
287 #else
288     QTcpSocket socket;
289 #endif
290
291     CoreUserInputHandler *_userInputHandler;
292
293     QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
294
295     QTimer _autoReconnectTimer;
296     int _autoReconnectCount;
297
298     QTimer _socketCloseTimer;
299
300     /* this flag triggers quitRequested() once the socket is closed
301      * it is needed to determine whether or not the connection needs to be
302      * in the automatic session restore. */
303     bool _quitRequested;
304     QString _quitReason;
305
306     bool _disconnectExpected;  /// If true, connection is quitting, expect a socket close
307     // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
308     // specifying a permanent (saved to core session) disconnect.
309
310     bool _previousConnectionAttemptFailed;
311     int _lastUsedServerIndex;
312
313     QTimer _pingTimer;
314     uint _lastPingTime;
315     uint _pingCount;
316     bool _sendPings;
317
318     QStringList _autoWhoQueue;
319     QHash<QString, int> _autoWhoPending;
320     QTimer _autoWhoTimer, _autoWhoCycleTimer;
321
322     QTimer _tokenBucketTimer;
323     int _messageDelay;      // token refill speed in ms
324     int _burstSize;         // size of the token bucket
325     int _tokenBucket;       // the virtual bucket that holds the tokens
326     QList<QByteArray> _msgQueue;
327
328     QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
329
330     // List of blowfish keys for channels
331     QHash<QString, QByteArray> _cipherKeys;
332 };
333
334
335 #endif //CORENETWORK_H