2dbd6a9e271dd718d9de5093bf3ccbfc6b148146
[quassel.git] / src / core / corenetwork.h
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, 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 #include <QDebug>
30
31 #ifdef HAVE_SSL
32 # include <QSslSocket>
33 # include <QSslError>
34 #else
35 # include <QTcpSocket>
36 #endif
37 #include <QAbstractSocket>
38
39 #ifdef HAVE_QCA2
40 #  include "cipher.h"
41 #endif
42
43 #include "coresession.h"
44
45 class CoreIdentity;
46 class CoreUserInputHandler;
47 class CoreIgnoreListManager;
48 class Event;
49
50 class CoreNetwork : public Network {
51   SYNCABLE_OBJECT
52   Q_OBJECT
53
54 public:
55   CoreNetwork(const NetworkId &networkid, CoreSession *session);
56   ~CoreNetwork();
57   inline virtual const QMetaObject *syncMetaObject() const { return &Network::staticMetaObject; }
58
59   inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); }
60   inline CoreSession *coreSession() const { return _coreSession; }
61   inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); }
62
63   inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; }
64   inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); }
65
66   //! Decode a string using the server (network) decoding.
67   inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); }
68
69   //! Decode a string using a channel-specific encoding if one is set (and use the standard encoding else).
70   QString channelDecode(const QString &channelName, const QByteArray &string) const;
71
72   //! Decode a string using an IrcUser-specific encoding, if one exists (using the standaed encoding else).
73   QString userDecode(const QString &userNick, const QByteArray &string) const;
74
75   //! Encode a string using the server (network) encoding.
76   inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); }
77
78   //! Encode a string using the channel-specific encoding, if set, and use the standard encoding else.
79   QByteArray channelEncode(const QString &channelName, const QString &string) const;
80
81   //! Encode a string using the user-specific encoding, if set, and use the standard encoding else.
82   QByteArray userEncode(const QString &userNick, const QString &string) const;
83
84   inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); }
85
86   inline bool isAutoWhoInProgress(const QString &channel) const { return _autoWhoPending.value(channel.toLower(), 0); }
87
88   inline UserId userId() const { return _coreSession->user(); }
89
90   inline QAbstractSocket::SocketState socketState() { return socket.state(); }
91   inline bool socketConnected() { return socket.state() == QAbstractSocket::ConnectedState; }
92   inline QHostAddress localAddress() { return socket.localAddress(); }
93   inline QHostAddress peerAddress() { return socket.peerAddress(); }
94   inline quint16 localPort() { return socket.localPort(); }
95   inline quint16 peerPort() { return socket.peerPort(); }
96
97 public slots:
98   virtual void setMyNick(const QString &mynick);
99
100   virtual void requestConnect() const;
101   virtual void requestDisconnect() const;
102   virtual void requestSetNetworkInfo(const NetworkInfo &info);
103
104   virtual void setUseAutoReconnect(bool);
105   virtual void setAutoReconnectInterval(quint32);
106   virtual void setAutoReconnectRetries(quint16);
107
108   void setPingInterval(int interval);
109
110   void connectToIrc(bool reconnecting = false);
111   void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false);
112
113   void userInput(BufferInfo bufferInfo, QString msg);
114   void putRawLine(QByteArray input);
115   void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray());
116
117   void setChannelJoined(const QString &channel);
118   void setChannelParted(const QString &channel);
119   void addChannelKey(const QString &channel, const QString &key);
120   void removeChannelKey(const QString &channel);
121
122   // Blowfish stuff
123 #ifdef HAVE_QCA2
124   Cipher *cipher(const QString &recipient) const;
125   QByteArray cipherKey(const QString &recipient) const;
126   void setCipherKey(const QString &recipient, const QByteArray &key);
127 #endif
128
129   void setAutoWhoEnabled(bool enabled);
130   void setAutoWhoInterval(int interval);
131   void setAutoWhoDelay(int delay);
132
133   bool setAutoWhoDone(const QString &channel);
134
135   void updateIssuedModes(const QString &requestedModes);
136   void updatePersistentModes(QString addModes, QString removeModes);
137   void resetPersistentModes();
138
139   Server usedServer() const;
140
141   inline void resetPingTimeout() { _pingCount = 0; }
142
143   inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None) {
144     emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
145   }
146
147 signals:
148   void recvRawServerMsg(QString);
149   void displayStatusMsg(QString);
150   void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
151   void disconnected(NetworkId networkId);
152   void connectionError(const QString &errorMsg);
153
154   void quitRequested(NetworkId networkId);
155   void sslErrors(const QVariant &errorData);
156
157   void newEvent(Event *event);
158
159 protected:
160   inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new CoreIrcChannel(channelname, this); }
161   inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new CoreIrcUser(hostmask, this); }
162
163 protected slots:
164   // TODO: remove cached cipher keys, when appropriate
165   //virtual void removeIrcUser(IrcUser *ircuser);
166   //virtual void removeIrcChannel(IrcChannel *ircChannel);
167   //virtual void removeChansAndUsers();
168
169 private slots:
170   void socketHasData();
171   void socketError(QAbstractSocket::SocketError);
172   void socketInitialized();
173   inline void socketCloseTimeout() { socket.disconnectFromHost(); }
174   void socketDisconnected();
175   void socketStateChanged(QAbstractSocket::SocketState);
176   void networkInitialized();
177
178   void sendPerform();
179   void restoreUserModes();
180   void doAutoReconnect();
181   void sendPing();
182   void enablePingTimeout(bool enable = true);
183   void disablePingTimeout();
184   void sendAutoWho();
185   void startAutoWhoCycle();
186
187 #ifdef HAVE_SSL
188   void sslErrors(const QList<QSslError> &errors);
189 #endif
190
191   void fillBucketAndProcessQueue();
192
193   void writeToSocket(const QByteArray &data);
194
195 private:
196   CoreSession *_coreSession;
197
198 #ifdef HAVE_SSL
199   QSslSocket socket;
200 #else
201   QTcpSocket socket;
202 #endif
203
204   CoreUserInputHandler *_userInputHandler;
205
206   QHash<QString, QString> _channelKeys;  // stores persistent channels and their passwords, if any
207
208   QTimer _autoReconnectTimer;
209   int _autoReconnectCount;
210
211   QTimer _socketCloseTimer;
212
213   /* this flag triggers quitRequested() once the socket is closed
214    * it is needed to determine whether or not the connection needs to be
215    * in the automatic session restore. */
216   bool _quitRequested;
217   QString _quitReason;
218
219   bool _previousConnectionAttemptFailed;
220   int _lastUsedServerIndex;
221
222   QTimer _pingTimer;
223   uint _lastPingTime;
224   uint _pingCount;
225
226   QStringList _autoWhoQueue;
227   QHash<QString, int> _autoWhoPending;
228   QTimer _autoWhoTimer, _autoWhoCycleTimer;
229
230   QTimer _tokenBucketTimer;
231   int _messageDelay;        // token refill speed in ms
232   int _burstSize;           // size of the token bucket
233   int _tokenBucket;         // the virtual bucket that holds the tokens
234   QList<QByteArray> _msgQueue;
235
236   QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
237
238   // Blowfish key map
239   QHash<QString, QByteArray> _cipherKeys;
240 };
241
242 #endif //CORENETWORK_H