Porting autoWHO fix (r809) from branches/0.3 to trunk.
[quassel.git] / src / core / networkconnection.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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 #include "networkconnection.h"
21
22 #include <QMetaObject>
23 #include <QMetaMethod>
24 #include <QDateTime>
25
26 #include "util.h"
27 #include "core.h"
28 #include "coresession.h"
29
30 #include "ircchannel.h"
31 #include "ircuser.h"
32 #include "network.h"
33 #include "identity.h"
34
35 #include "ircserverhandler.h"
36 #include "userinputhandler.h"
37 #include "ctcphandler.h"
38
39 NetworkConnection::NetworkConnection(Network *network, CoreSession *session) : QObject(network),
40     _connectionState(Network::Disconnected),
41     _network(network),
42     _coreSession(session),
43     _ircServerHandler(new IrcServerHandler(this)),
44     _userInputHandler(new UserInputHandler(this)),
45     _ctcpHandler(new CtcpHandler(this)),
46     _autoReconnectCount(0)
47 {
48   _autoReconnectTimer.setSingleShot(true);
49
50   _previousConnectionAttemptFailed = false;
51   _lastUsedServerlistIndex = 0;
52
53   // TODO make autowho configurable (possibly per-network)
54   _autoWhoEnabled = true;
55   _autoWhoInterval = 90;
56   _autoWhoNickLimit = 0; // unlimited
57   _autoWhoDelay = 3;
58
59   _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
60   _autoWhoTimer.setSingleShot(false);
61   _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
62   _autoWhoCycleTimer.setSingleShot(false);
63
64   // TokenBucket to avaid sending too much at once
65   _messagesPerSecond = 1;
66   _burstSize = 5;
67   _tokenBucket = 5; // init with a full bucket
68
69   _tokenBucketTimer.start(_messagesPerSecond * 1000);
70   _tokenBucketTimer.setSingleShot(false);
71
72   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
73   foreach(QString chan, channels.keys()) {
74     _channelKeys[chan.toLower()] = channels[chan];
75   }
76
77   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
78   connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
79   connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
80   connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
81
82   connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
83   connect(network, SIGNAL(useAutoReconnectSet(bool)), this, SLOT(autoReconnectSettingsChanged()));
84   connect(network, SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(autoReconnectSettingsChanged()));
85   connect(network, SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(autoReconnectSettingsChanged()));
86
87 #ifndef QT_NO_OPENSSL
88   connect(&socket, SIGNAL(encrypted()), this, SLOT(socketEncrypted()));
89   connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
90 #endif
91   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
92
93   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
94   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
95   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
96   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
97
98   connect(_ircServerHandler, SIGNAL(nickChanged(const QString &, const QString &)),
99           this, SLOT(nickChanged(const QString &, const QString &)));
100
101   network->proxy()->attachSignal(this, SIGNAL(sslErrors(const QVariant &)));
102 }
103
104 NetworkConnection::~NetworkConnection() {
105   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
106     disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
107   delete _ircServerHandler;
108   delete _userInputHandler;
109   delete _ctcpHandler;
110 }
111
112 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
113   _connectionState = state;
114   network()->setConnectionState(state);
115   emit connectionStateChanged(state);
116 }
117
118 QString NetworkConnection::serverDecode(const QByteArray &string) const {
119   return network()->decodeServerString(string);
120 }
121
122 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
123   if(!bufferName.isEmpty()) {
124     IrcChannel *channel = network()->ircChannel(bufferName);
125     if(channel) return channel->decodeString(string);
126   }
127   return network()->decodeString(string);
128 }
129
130 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
131   IrcUser *user = network()->ircUser(userNick);
132   if(user) return user->decodeString(string);
133   return network()->decodeString(string);
134 }
135
136 QByteArray NetworkConnection::serverEncode(const QString &string) const {
137   return network()->encodeServerString(string);
138 }
139
140 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
141   if(!bufferName.isEmpty()) {
142     IrcChannel *channel = network()->ircChannel(bufferName);
143     if(channel) return channel->encodeString(string);
144   }
145   return network()->encodeString(string);
146 }
147
148 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
149   IrcUser *user = network()->ircUser(userNick);
150   if(user) return user->encodeString(string);
151   return network()->encodeString(string);
152 }
153
154 void NetworkConnection::autoReconnectSettingsChanged() {
155   if(!network()->useAutoReconnect()) {
156     _autoReconnectTimer.stop();
157     _autoReconnectCount = 0;
158   } else {
159     _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
160     if(_autoReconnectCount != 0) {
161       if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
162       else _autoReconnectCount = network()->autoReconnectRetries();
163     }
164   }
165 }
166
167 void NetworkConnection::connectToIrc(bool reconnecting) {
168   if(!reconnecting && network()->useAutoReconnect() && _autoReconnectCount == 0) {
169     _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
170     if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
171     else _autoReconnectCount = network()->autoReconnectRetries();
172   }
173   QVariantList serverList = network()->serverList();
174   Identity *identity = coreSession()->identity(network()->identity());
175   if(!serverList.count()) {
176     qWarning() << "Server list empty, ignoring connect request!";
177     return;
178   }
179   if(!identity) {
180     qWarning() << "Invalid identity configures, ignoring connect request!";
181     return;
182   }
183   // use a random server?
184   if(network()->useRandomServer()) {
185     _lastUsedServerlistIndex = qrand() % serverList.size();
186   } else if(_previousConnectionAttemptFailed) {
187     // cycle to next server if previous connection attempt failed
188     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
189     if(++_lastUsedServerlistIndex == serverList.size()) {
190       _lastUsedServerlistIndex = 0;
191     }
192   }
193   _previousConnectionAttemptFailed = false;
194
195   QString host = serverList[_lastUsedServerlistIndex].toMap()["Host"].toString();
196   quint16 port = serverList[_lastUsedServerlistIndex].toMap()["Port"].toUInt();
197   displayStatusMsg(tr("Connecting to %1:%2...").arg(host).arg(port));
198   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(host).arg(port));
199   socket.connectToHost(host, port);
200 }
201
202 void NetworkConnection::networkInitialized(const QString &currentServer) {
203   if(currentServer.isEmpty()) return;
204
205   if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
206     _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
207   }
208
209   sendPerform();
210
211   // now we are initialized
212   setConnectionState(Network::Initialized);
213   network()->setConnected(true);
214   emit connected(networkId());
215
216   if(_autoWhoEnabled) {
217     _autoWhoCycleTimer.start();
218     _autoWhoTimer.start();
219     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
220   }
221 }
222
223 void NetworkConnection::sendPerform() {
224   BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
225   // do auto identify
226   if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
227     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
228   }
229   // send perform list
230   foreach(QString line, network()->perform()) {
231     if(!line.isEmpty()) userInput(statusBuf, line);
232   }
233
234   // rejoin channels we've been in
235   QStringList channels, keys;
236   foreach(QString chan, persistentChannels()) {
237     QString key = channelKey(chan);
238     if(!key.isEmpty()) {
239       channels.prepend(chan); keys.prepend(key);
240     } else {
241       channels.append(chan);
242     }
243   }
244   QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
245   if(!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString);
246 }
247
248 void NetworkConnection::disconnectFromIrc(bool requested) {
249   _autoReconnectTimer.stop();
250   _autoReconnectCount = 0;
251   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
252   if(socket.state() < QAbstractSocket::ConnectedState) {
253     setConnectionState(Network::Disconnected);
254     socketDisconnected();
255   } else socket.disconnectFromHost();
256
257   if(requested) {
258     emit quitRequested(networkId());
259   }
260 }
261
262 void NetworkConnection::socketHasData() {
263   while(socket.canReadLine()) {
264     QByteArray s = socket.readLine().trimmed();
265     ircServerHandler()->handleServerMsg(s);
266   }
267 }
268
269 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
270   _previousConnectionAttemptFailed = true;
271   qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
272   emit connectionError(socket.errorString());
273   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
274   network()->emitConnectionError(socket.errorString());
275   if(socket.state() < QAbstractSocket::ConnectedState) {
276     setConnectionState(Network::Disconnected);
277     socketDisconnected();
278   }
279   // mark last connection attempt as failed
280   
281   //qDebug() << "exiting...";
282   //exit(1);
283 }
284
285 #ifndef QT_NO_OPENSSL
286
287 void NetworkConnection::sslErrors(const QList<QSslError> &sslErrors) {
288   Q_UNUSED(sslErrors)
289   socket.ignoreSslErrors();
290   /* TODO errorhandling
291   QVariantMap errmsg;
292   QVariantList errnums;
293   foreach(QSslError err, errors) errnums << err.error();
294   errmsg["SslErrors"] = errnums;
295   errmsg["SslCert"] = socket.peerCertificate().toPem();
296   errmsg["PeerAddress"] = socket.peerAddress().toString();
297   errmsg["PeerPort"] = socket.peerPort();
298   errmsg["PeerName"] = socket.peerName();
299   emit sslErrors(errmsg);
300   disconnectFromIrc();
301   */
302 }
303
304 void NetworkConnection::socketEncrypted() {
305   //qDebug() << "encrypted!";
306   socketInitialized();
307 }
308
309 #endif  // QT_NO_OPENSSL
310
311 void NetworkConnection::socketConnected() {
312 #ifdef QT_NO_OPENSSL
313   socketInitialized();
314   return;
315 #else
316   if(!network()->serverList()[_lastUsedServerlistIndex].toMap()["UseSSL"].toBool()) {
317     socketInitialized();
318     return;
319   }
320   //qDebug() << "starting handshake";
321   socket.startClientEncryption();
322 #endif
323 }
324
325 void NetworkConnection::socketInitialized() {
326   //emit connected(networkId());  initialize first!
327   Identity *identity = coreSession()->identity(network()->identity());
328   if(!identity) {
329     qWarning() << "Identity invalid!";
330     disconnectFromIrc();
331     return;
332   }
333   QString passwd = network()->serverList()[_lastUsedServerlistIndex].toMap()["Password"].toString();
334   if(!passwd.isEmpty()) {
335     putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
336   }
337   putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));  // FIXME: try more nicks if error occurs
338   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
339 }
340
341 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
342   Network::ConnectionState state;
343   switch(socketState) {
344     case QAbstractSocket::UnconnectedState:
345       state = Network::Disconnected;
346       break;
347     case QAbstractSocket::HostLookupState:
348     case QAbstractSocket::ConnectingState:
349       state = Network::Connecting;
350       break;
351     case QAbstractSocket::ConnectedState:
352       state = Network::Initializing;
353       break;
354     case QAbstractSocket::ClosingState:
355       state = Network::Disconnecting;
356       break;
357     default:
358       state = Network::Disconnected;
359   }
360   setConnectionState(state);
361 }
362
363 void NetworkConnection::socketDisconnected() {
364   _autoWhoCycleTimer.stop();
365   _autoWhoTimer.stop();
366   _autoWhoQueue.clear();
367   _autoWhoInProgress.clear();
368
369   network()->setConnected(false);
370   emit disconnected(networkId());
371   if(_autoReconnectCount != 0) {
372     setConnectionState(Network::Reconnecting);
373     if(_autoReconnectCount == network()->autoReconnectRetries()) doAutoReconnect(); // first try is immediate
374     else _autoReconnectTimer.start();
375   }
376 }
377
378 void NetworkConnection::doAutoReconnect() {
379   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
380     qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
381     return;
382   }
383   if(_autoReconnectCount > 0) _autoReconnectCount--;
384   connectToIrc(true);
385 }
386
387 // FIXME switch to BufferId
388 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
389   userInputHandler()->handleUserInput(buf, msg);
390 }
391
392 void NetworkConnection::putRawLine(QByteArray s) {
393   if(_tokenBucket > 0) {
394     writeToSocket(s);
395   } else {
396     _msgQueue.append(s);
397   }
398 }
399
400 void NetworkConnection::writeToSocket(QByteArray s) {
401   s += "\r\n";
402   socket.write(s);
403   _tokenBucket--;
404 }
405
406 void NetworkConnection::fillBucketAndProcessQueue() {
407   if(_tokenBucket < _burstSize) {
408     _tokenBucket++;
409   }
410
411   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
412     writeToSocket(_msgQueue.takeFirst());
413   }
414 }
415
416 void NetworkConnection::putCmd(const QString &cmd, const QVariantList &params, const QByteArray &prefix) {
417   QByteArray msg;
418   if(!prefix.isEmpty())
419     msg += ":" + prefix + " ";
420   msg += cmd.toUpper().toAscii();
421
422   for(int i = 0; i < params.size() - 1; i++) {
423     msg += " " + params[i].toByteArray();
424   }
425   if(!params.isEmpty())
426     msg += " :" + params.last().toByteArray();
427
428   putRawLine(msg);
429 }
430
431 void NetworkConnection::sendAutoWho() {
432   while(!_autoWhoQueue.isEmpty()) {
433     QString chan = _autoWhoQueue.takeFirst();
434     IrcChannel *ircchan = network()->ircChannel(chan);
435     if(!ircchan) continue;
436     if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
437     _autoWhoInProgress[chan]++;
438     putRawLine("WHO " + serverEncode(chan));
439     if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
440       // Timer was stopped, means a new cycle is due immediately
441       _autoWhoCycleTimer.start();
442       startAutoWhoCycle();
443     }
444     break;
445   }
446 }
447
448 void NetworkConnection::startAutoWhoCycle() {
449   if(!_autoWhoQueue.isEmpty()) {
450     _autoWhoCycleTimer.stop();
451     return;
452   }
453   _autoWhoQueue = network()->channels();
454 }
455
456 bool NetworkConnection::setAutoWhoDone(const QString &channel) {
457   if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0) return false;
458   _autoWhoInProgress[channel.toLower()]--;
459   return true;
460 }
461
462 void NetworkConnection::setChannelJoined(const QString &channel) {
463   emit channelJoined(networkId(), channel, _channelKeys[channel.toLower()]);
464   _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
465 }
466
467 void NetworkConnection::setChannelParted(const QString &channel) {
468   removeChannelKey(channel);
469   _autoWhoQueue.removeAll(channel.toLower());
470   _autoWhoInProgress.remove(channel.toLower());
471   emit channelParted(networkId(), channel);
472 }
473
474 void NetworkConnection::addChannelKey(const QString &channel, const QString &key) {
475   if(key.isEmpty()) {
476     removeChannelKey(channel);
477   } else {
478     _channelKeys[channel.toLower()] = key;
479   }
480 }
481
482 void NetworkConnection::removeChannelKey(const QString &channel) {
483   _channelKeys.remove(channel.toLower());
484 }
485
486 void NetworkConnection::nickChanged(const QString &newNick, const QString &oldNick) {
487   emit nickChanged(networkId(), newNick, oldNick);
488 }
489
490 /* Exception classes for message handling */
491 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
492   Q_UNUSED(prefix);
493   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
494 }
495
496 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
497   Q_UNUSED(prefix);
498   _msg = QString("Unknown Command: ") + cmd + params.join(" ");
499 }
500