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