7ad13f4343690da573145b044447ae8e2062fdfb
[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
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 class CoreIdentity;
44 class CoreUserInputHandler;
45 class CoreIgnoreListManager;
46 class Event;
47
48 class CoreNetwork : public Network {
49   SYNCABLE_OBJECT
50   Q_OBJECT
51
52 public:
53   CoreNetwork(const NetworkId &networkid, CoreSession *session);
54   ~CoreNetwork();
55   inline virtual const QMetaObject *syncMetaObject() const { return &Network::staticMetaObject; }
56
57   inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); }
58   inline CoreSession *coreSession() const { return _coreSession; }
59   inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); }
60
61   inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; }
62   inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); }
63
64   //! Decode a string using the server (network) decoding.
65   inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); }
66
67   //! Decode a string using a channel-specific encoding if one is set (and use the standard encoding else).
68   QString channelDecode(const QString &channelName, const QByteArray &string) const;
69
70   //! Decode a string using an IrcUser-specific encoding, if one exists (using the standaed encoding else).
71   QString userDecode(const QString &userNick, const QByteArray &string) const;
72
73   //! Encode a string using the server (network) encoding.
74   inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); }
75
76   //! Encode a string using the channel-specific encoding, if set, and use the standard encoding else.
77   QByteArray channelEncode(const QString &channelName, const QString &string) const;
78
79   //! Encode a string using the user-specific encoding, if set, and use the standard encoding else.
80   QByteArray userEncode(const QString &userNick, const QString &string) const;
81
82   inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); }
83
84   inline bool isAutoWhoInProgress(const QString &channel) const { return _autoWhoPending.value(channel.toLower(), 0); }
85
86   inline UserId userId() const { return _coreSession->user(); }
87
88   inline QAbstractSocket::SocketState socketState() const { return socket.state(); }
89   inline bool socketConnected() const { return socket.state() == QAbstractSocket::ConnectedState; }
90   inline QHostAddress localAddress() const { return socket.localAddress(); }
91   inline QHostAddress peerAddress() const { return socket.peerAddress(); }
92   inline quint16 localPort() const { return socket.localPort(); }
93   inline quint16 peerPort() const { return socket.peerPort(); }
94
95 public slots:
96   virtual void setMyNick(const QString &mynick);
97
98   virtual void requestConnect() const;
99   virtual void requestDisconnect() const;
100   virtual void requestSetNetworkInfo(const NetworkInfo &info);
101
102   virtual void setUseAutoReconnect(bool);
103   virtual void setAutoReconnectInterval(quint32);
104   virtual void setAutoReconnectRetries(quint16);
105
106   void setPingInterval(int interval);
107
108   void connectToIrc(bool reconnecting = false);
109   void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false);
110
111   void userInput(BufferInfo bufferInfo, QString msg);
112   void putRawLine(QByteArray input);
113   void putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix = QByteArray());
114
115   void setChannelJoined(const QString &channel);
116   void setChannelParted(const QString &channel);
117   void addChannelKey(const QString &channel, const QString &key);
118   void removeChannelKey(const QString &channel);
119
120   // Blowfish stuff
121 #ifdef HAVE_QCA2
122   Cipher *cipher(const QString &recipient) const;
123   QByteArray cipherKey(const QString &recipient) const;
124   void setCipherKey(const QString &recipient, const QByteArray &key);
125 #endif
126
127   void setAutoWhoEnabled(bool enabled);
128   void setAutoWhoInterval(int interval);
129   void setAutoWhoDelay(int delay);
130
131   bool setAutoWhoDone(const QString &channel);
132
133   void updateIssuedModes(const QString &requestedModes);
134   void updatePersistentModes(QString addModes, QString removeModes);
135   void resetPersistentModes();
136
137   Server usedServer() const;
138
139   inline void resetPingTimeout() { _pingCount = 0; }
140
141   inline void displayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None) {
142     emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
143   }
144
145 signals:
146   void recvRawServerMsg(QString);
147   void displayStatusMsg(QString);
148   void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
149   void disconnected(NetworkId networkId);
150   void connectionError(const QString &errorMsg);
151
152   void quitRequested(NetworkId networkId);
153   void sslErrors(const QVariant &errorData);
154
155   void newEvent(Event *event);
156   void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
157   void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort);
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