Fix ident race condition
[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     void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false);
118
119     void userInput(BufferInfo bufferInfo, QString msg);
120     void putRawLine(QByteArray input);
121     void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray());
122     void putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix = QByteArray());
123
124     void setChannelJoined(const QString &channel);
125     void setChannelParted(const QString &channel);
126     void addChannelKey(const QString &channel, const QString &key);
127     void removeChannelKey(const QString &channel);
128
129     // Blowfish stuff
130 #ifdef HAVE_QCA2
131     Cipher *cipher(const QString &recipient);
132     QByteArray cipherKey(const QString &recipient) const;
133     void setCipherKey(const QString &recipient, const QByteArray &key);
134     bool cipherUsesCBC(const QString &target);
135 #endif
136
137     void setAutoWhoEnabled(bool enabled);
138     void setAutoWhoInterval(int interval);
139     void setAutoWhoDelay(int delay);
140
141     bool setAutoWhoDone(const QString &channel);
142
143     void updateIssuedModes(const QString &requestedModes);
144     void updatePersistentModes(QString addModes, QString removeModes);
145     void resetPersistentModes();
146
147     Server usedServer() const;
148
149     inline void resetPingTimeout() { _pingCount = 0; }
150
151     inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None)
152     {
153         emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
154     }
155
156
157 signals:
158     void recvRawServerMsg(QString);
159     void displayStatusMsg(QString);
160     void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
161     void disconnected(NetworkId networkId);
162     void connectionError(const QString &errorMsg);
163
164     void quitRequested(NetworkId networkId);
165     void sslErrors(const QVariant &errorData);
166
167     void newEvent(Event *event);
168     void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
169     void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
170
171 protected:
172     inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
173     inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
174
175 protected slots:
176     // TODO: remove cached cipher keys, when appropriate
177     //virtual void removeIrcUser(IrcUser *ircuser);
178     //virtual void removeIrcChannel(IrcChannel *ircChannel);
179     //virtual void removeChansAndUsers();
180
181 private slots:
182     void socketHasData();
183     void socketError(QAbstractSocket::SocketError);
184     void socketInitialized();
185     inline void socketCloseTimeout() { socket.abort(); }
186     void socketDisconnected();
187     void socketStateChanged(QAbstractSocket::SocketState);
188     void networkInitialized();
189
190     void sendPerform();
191     void restoreUserModes();
192     void doAutoReconnect();
193     void sendPing();
194     void enablePingTimeout(bool enable = true);
195     void disablePingTimeout();
196     void sendAutoWho();
197     void startAutoWhoCycle();
198
199 #ifdef HAVE_SSL
200     void sslErrors(const QList<QSslError> &errors);
201 #endif
202
203     void fillBucketAndProcessQueue();
204
205     void writeToSocket(const QByteArray &data);
206
207 private:
208     CoreSession *_coreSession;
209
210 #ifdef HAVE_SSL
211     QSslSocket socket;
212 #else
213     QTcpSocket socket;
214 #endif
215
216     CoreUserInputHandler *_userInputHandler;
217
218     QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
219
220     QTimer _autoReconnectTimer;
221     int _autoReconnectCount;
222
223     QTimer _socketCloseTimer;
224
225     /* this flag triggers quitRequested() once the socket is closed
226      * it is needed to determine whether or not the connection needs to be
227      * in the automatic session restore. */
228     bool _quitRequested;
229     QString _quitReason;
230
231     bool _previousConnectionAttemptFailed;
232     int _lastUsedServerIndex;
233
234     QTimer _pingTimer;
235     uint _lastPingTime;
236     uint _pingCount;
237     bool _sendPings;
238
239     QStringList _autoWhoQueue;
240     QHash<QString, int> _autoWhoPending;
241     QTimer _autoWhoTimer, _autoWhoCycleTimer;
242
243     QTimer _tokenBucketTimer;
244     int _messageDelay;      // token refill speed in ms
245     int _burstSize;         // size of the token bucket
246     int _tokenBucket;       // the virtual bucket that holds the tokens
247     QList<QByteArray> _msgQueue;
248
249     QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
250
251     // List of blowfish keys for channels
252     QHash<QString, QByteArray> _cipherKeys;
253 };
254
255
256 #endif //CORENETWORK_H