tackeling 30 sec ping timeout issues
[quassel.git] / src / core / corenetwork.cpp
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 #include "corenetwork.h"
22
23 #include "core.h"
24 #include "coresession.h"
25 #include "coreidentity.h"
26
27 #include "ircserverhandler.h"
28 #include "userinputhandler.h"
29 #include "ctcphandler.h"
30
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32   : Network(networkid, session),
33     _coreSession(session),
34     _ircServerHandler(new IrcServerHandler(this)),
35     _userInputHandler(new UserInputHandler(this)),
36     _ctcpHandler(new CtcpHandler(this)),
37     _autoReconnectCount(0),
38     _quitRequested(false),
39
40     _previousConnectionAttemptFailed(false),
41     _lastUsedServerIndex(0),
42
43     _lastPingTime(0),
44     _maxPingCount(3),
45     _pingCount(0),
46
47     // TODO make autowho configurable (possibly per-network)
48     _autoWhoEnabled(true),
49     _autoWhoInterval(90),
50     _autoWhoNickLimit(0), // unlimited
51     _autoWhoDelay(5)
52 {
53   _autoReconnectTimer.setSingleShot(true);
54   _socketCloseTimer.setSingleShot(true);
55   connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
56
57   _pingTimer.setInterval(30000);
58   connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
59
60   _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
61   _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
62
63   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
64   foreach(QString chan, channels.keys()) {
65     _channelKeys[chan.toLower()] = channels[chan];
66   }
67
68   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
69   connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
70   connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
71   connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
72   connect(this, SIGNAL(connectRequested()), this, SLOT(connectToIrc()));
73
74
75   connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
76   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
77   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
78   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
79   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
80 #ifdef HAVE_SSL
81   connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
82   connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
83 #endif
84 }
85
86 CoreNetwork::~CoreNetwork() {
87   if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
88     disconnectFromIrc(false);      // clean up, but this does not count as requested disconnect!
89   disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
90   delete _ircServerHandler;
91   delete _userInputHandler;
92   delete _ctcpHandler;
93 }
94
95 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
96   if(!bufferName.isEmpty()) {
97     IrcChannel *channel = ircChannel(bufferName);
98     if(channel)
99       return channel->decodeString(string);
100   }
101   return decodeString(string);
102 }
103
104 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
105   IrcUser *user = ircUser(userNick);
106   if(user)
107     return user->decodeString(string);
108   return decodeString(string);
109 }
110
111 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
112   if(!bufferName.isEmpty()) {
113     IrcChannel *channel = ircChannel(bufferName);
114     if(channel)
115       return channel->encodeString(string);
116   }
117   return encodeString(string);
118 }
119
120 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
121   IrcUser *user = ircUser(userNick);
122   if(user)
123     return user->encodeString(string);
124   return encodeString(string);
125 }
126
127 void CoreNetwork::connectToIrc(bool reconnecting) {
128   if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
129     _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
130     if(unlimitedReconnectRetries())
131       _autoReconnectCount = -1;
132     else
133       _autoReconnectCount = autoReconnectRetries();
134   }
135   if(serverList().isEmpty()) {
136     qWarning() << "Server list empty, ignoring connect request!";
137     return;
138   }
139   CoreIdentity *identity = identityPtr();
140   if(!identity) {
141     qWarning() << "Invalid identity configures, ignoring connect request!";
142     return;
143   }
144
145   // cleaning up old quit reason
146   _quitReason.clear();
147
148   // use a random server?
149   if(useRandomServer()) {
150     _lastUsedServerIndex = qrand() % serverList().size();
151   } else if(_previousConnectionAttemptFailed) {
152     // cycle to next server if previous connection attempt failed
153     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
154     if(++_lastUsedServerIndex >= serverList().size()) {
155       _lastUsedServerIndex = 0;
156     }
157   }
158   _previousConnectionAttemptFailed = false;
159
160   Server server = usedServer();
161   displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
162   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
163
164   if(server.useProxy) {
165     QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
166     socket.setProxy(proxy);
167   } else {
168     socket.setProxy(QNetworkProxy::NoProxy);
169   }
170
171 #ifdef HAVE_SSL
172   socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
173   if(server.useSsl) {
174     CoreIdentity *identity = identityPtr();
175     if(identity) {
176       socket.setLocalCertificate(identity->sslCert());
177       socket.setPrivateKey(identity->sslKey());
178     }
179     socket.connectToHostEncrypted(server.host, server.port);
180   } else {
181     socket.connectToHost(server.host, server.port);
182   }
183 #else
184   socket.connectToHost(server.host, server.port);
185 #endif
186 }
187
188 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) {
189   _quitRequested = requested; // see socketDisconnected();
190   if(!withReconnect) {
191     _autoReconnectTimer.stop();
192     _autoReconnectCount = 0; // prohibiting auto reconnect
193   }
194   disablePingTimeout();
195
196   IrcUser *me_ = me();
197   if(me_) {
198     QString awayMsg;
199     if(me_->isAway())
200       awayMsg = me_->awayMessage();
201     Core::setAwayMessage(userId(), networkId(), awayMsg);
202     Core::setUserModes(userId(), networkId(), me_->userModes());
203   }
204
205   if(reason.isEmpty() && identityPtr())
206     _quitReason = identityPtr()->quitReason();
207   else
208     _quitReason = reason;
209
210   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
211   switch(socket.state()) {
212   case QAbstractSocket::ConnectedState:
213     userInputHandler()->issueQuit(_quitReason);
214     if(requested || withReconnect) {
215       // the irc server has 10 seconds to close the socket
216       _socketCloseTimer.start(10000);
217       break;
218     }
219   default:
220     socket.close();
221     socketDisconnected();
222   }
223 }
224
225 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
226   userInputHandler()->handleUserInput(buf, msg);
227 }
228
229 void CoreNetwork::putRawLine(QByteArray s) {
230   if(_tokenBucket > 0)
231     writeToSocket(s);
232   else
233     _msgQueue.append(s);
234 }
235
236 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix) {
237   QByteArray msg;
238
239   if(!prefix.isEmpty())
240     msg += ":" + prefix + " ";
241   msg += cmd.toUpper().toAscii();
242
243   for(int i = 0; i < params.size() - 1; i++) {
244     msg += " " + params[i];
245   }
246   if(!params.isEmpty())
247     msg += " :" + params.last();
248
249   putRawLine(msg);
250 }
251
252 void CoreNetwork::setChannelJoined(const QString &channel) {
253   _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
254
255   Core::setChannelPersistent(userId(), networkId(), channel, true);
256   Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
257 }
258
259 void CoreNetwork::setChannelParted(const QString &channel) {
260   removeChannelKey(channel);
261   _autoWhoQueue.removeAll(channel.toLower());
262   _autoWhoPending.remove(channel.toLower());
263
264   Core::setChannelPersistent(userId(), networkId(), channel, false);
265 }
266
267 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
268   if(key.isEmpty()) {
269     removeChannelKey(channel);
270   } else {
271     _channelKeys[channel.toLower()] = key;
272   }
273 }
274
275 void CoreNetwork::removeChannelKey(const QString &channel) {
276   _channelKeys.remove(channel.toLower());
277 }
278
279 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
280   QString chan = channel.toLower();
281   if(_autoWhoPending.value(chan, 0) <= 0)
282     return false;
283   if(--_autoWhoPending[chan] <= 0)
284     _autoWhoPending.remove(chan);
285   return true;
286 }
287
288 void CoreNetwork::setMyNick(const QString &mynick) {
289   Network::setMyNick(mynick);
290   if(connectionState() == Network::Initializing)
291     networkInitialized();
292 }
293
294 void CoreNetwork::socketHasData() {
295   while(socket.canReadLine()) {
296     QByteArray s = socket.readLine().trimmed();
297     ircServerHandler()->handleServerMsg(s);
298   }
299 }
300
301 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
302   if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
303     return;
304
305   _previousConnectionAttemptFailed = true;
306   qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
307   emit connectionError(socket.errorString());
308   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
309   emitConnectionError(socket.errorString());
310   if(socket.state() < QAbstractSocket::ConnectedState) {
311     socketDisconnected();
312   }
313 }
314
315 void CoreNetwork::socketInitialized() {
316   Server server = usedServer();
317 #ifdef HAVE_SSL
318   if(server.useSsl && !socket.isEncrypted())
319     return;
320 #endif
321
322   CoreIdentity *identity = identityPtr();
323   if(!identity) {
324     qCritical() << "Identity invalid!";
325     disconnectFromIrc();
326     return;
327   }
328
329   // TokenBucket to avoid sending too much at once
330   _messagesPerSecond = 1;
331   _burstSize = 5;
332   _tokenBucket = 5; // init with a full bucket
333   _tokenBucketTimer.start(_messagesPerSecond * 1000);
334
335   if(!server.password.isEmpty()) {
336     putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
337   }
338   putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
339   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
340 }
341
342 void CoreNetwork::socketDisconnected() {
343   disablePingTimeout();
344
345   _autoWhoCycleTimer.stop();
346   _autoWhoTimer.stop();
347   _autoWhoQueue.clear();
348   _autoWhoPending.clear();
349
350   _socketCloseTimer.stop();
351
352   _tokenBucketTimer.stop();
353
354   IrcUser *me_ = me();
355   if(me_) {
356     foreach(QString channel, me_->channels())
357       emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
358   }
359
360   setConnected(false);
361   emit disconnected(networkId());
362   if(_quitRequested) {
363     setConnectionState(Network::Disconnected);
364     Core::setNetworkConnected(userId(), networkId(), false);
365   } else if(_autoReconnectCount != 0) {
366     setConnectionState(Network::Reconnecting);
367     if(_autoReconnectCount == autoReconnectRetries())
368       doAutoReconnect(); // first try is immediate
369     else
370       _autoReconnectTimer.start();
371   }
372 }
373
374 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
375   Network::ConnectionState state;
376   switch(socketState) {
377     case QAbstractSocket::UnconnectedState:
378       state = Network::Disconnected;
379       break;
380     case QAbstractSocket::HostLookupState:
381     case QAbstractSocket::ConnectingState:
382       state = Network::Connecting;
383       break;
384     case QAbstractSocket::ConnectedState:
385       state = Network::Initializing;
386       break;
387     case QAbstractSocket::ClosingState:
388       state = Network::Disconnecting;
389       break;
390     default:
391       state = Network::Disconnected;
392   }
393   setConnectionState(state);
394 }
395
396 void CoreNetwork::networkInitialized() {
397   setConnectionState(Network::Initialized);
398   setConnected(true);
399   _quitRequested = false;
400
401   if(useAutoReconnect()) {
402     // reset counter
403     _autoReconnectCount = autoReconnectRetries();
404   }
405
406   // restore away state
407   QString awayMsg = Core::awayMessage(userId(), networkId());
408   if(!awayMsg.isEmpty())
409     userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
410
411   // restore old user modes if server default mode is set.
412   IrcUser *me_ = me();
413   if(me_) {
414     if(!me_->userModes().isEmpty()) {
415       restoreUserModes();
416     } else {
417       connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
418       connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
419     }
420   }
421
422   sendPerform();
423
424   enablePingTimeout();
425
426   if(_autoWhoEnabled) {
427     _autoWhoCycleTimer.start();
428     _autoWhoTimer.start();
429     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
430   }
431
432   Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
433   Core::setNetworkConnected(userId(), networkId(), true);
434 }
435
436 void CoreNetwork::sendPerform() {
437   BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
438
439   // do auto identify
440   if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
441     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
442   }
443
444   // send perform list
445   foreach(QString line, perform()) {
446     if(!line.isEmpty()) userInput(statusBuf, line);
447   }
448
449   // rejoin channels we've been in
450   if(rejoinChannels()) {
451     QStringList channels, keys;
452     foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
453       QString key = channelKey(chan);
454       if(!key.isEmpty()) {
455         channels.prepend(chan);
456         keys.prepend(key);
457       } else {
458         channels.append(chan);
459       }
460     }
461     QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
462     if(!joinString.isEmpty())
463       userInputHandler()->handleJoin(statusBuf, joinString);
464   }
465 }
466
467 void CoreNetwork::restoreUserModes() {
468   IrcUser *me_ = me();
469   Q_ASSERT(me_);
470
471   disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
472   disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
473
474   QString removeModes;
475   QString addModes = Core::userModes(userId(), networkId());
476   QString currentModes = me_->userModes();
477
478   removeModes = currentModes;
479   removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
480   addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
481
482   removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
483   addModes = QString("%1 +%2").arg(me_->nick(), addModes);
484   userInputHandler()->handleMode(BufferInfo(), removeModes);
485   userInputHandler()->handleMode(BufferInfo(), addModes);
486 }
487
488 void CoreNetwork::setUseAutoReconnect(bool use) {
489   Network::setUseAutoReconnect(use);
490   if(!use)
491     _autoReconnectTimer.stop();
492 }
493
494 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
495   Network::setAutoReconnectInterval(interval);
496   _autoReconnectTimer.setInterval(interval * 1000);
497 }
498
499 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
500   Network::setAutoReconnectRetries(retries);
501   if(_autoReconnectCount != 0) {
502     if(unlimitedReconnectRetries())
503       _autoReconnectCount = -1;
504     else
505       _autoReconnectCount = autoReconnectRetries();
506   }
507 }
508
509 void CoreNetwork::doAutoReconnect() {
510   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
511     qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
512     return;
513   }
514   if(_autoReconnectCount > 0)
515     _autoReconnectCount--;
516   connectToIrc(true);
517 }
518
519 void CoreNetwork::sendPing() {
520   uint now = QDateTime::currentDateTime().toTime_t();
521   if(_pingCount >= _maxPingCount && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
522     // the second check compares the actual elapsed time since the last ping and the pingTimer interval
523     // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
524     // and unable to even handle a ping answer. So we ignore those misses.
525     disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_maxPingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
526   } else {
527     _lastPingTime = now;
528     _pingCount++;
529     userInputHandler()->handlePing(BufferInfo(), QString());
530   }
531 }
532
533 void CoreNetwork::enablePingTimeout() {
534   resetPingTimeout();
535   _pingTimer.start();
536 }
537
538 void CoreNetwork::disablePingTimeout() {
539   _pingTimer.stop();
540   resetPingTimeout();
541 }
542
543 void CoreNetwork::sendAutoWho() {
544   // Don't send autowho if there are still some pending
545   if(_autoWhoPending.count())
546     return;
547
548   while(!_autoWhoQueue.isEmpty()) {
549     QString chan = _autoWhoQueue.takeFirst();
550     IrcChannel *ircchan = ircChannel(chan);
551     if(!ircchan) continue;
552     if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
553     _autoWhoPending[chan]++;
554     putRawLine("WHO " + serverEncode(chan));
555     if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
556       // Timer was stopped, means a new cycle is due immediately
557       _autoWhoCycleTimer.start();
558       startAutoWhoCycle();
559     }
560     break;
561   }
562 }
563
564 void CoreNetwork::startAutoWhoCycle() {
565   if(!_autoWhoQueue.isEmpty()) {
566     _autoWhoCycleTimer.stop();
567     return;
568   }
569   _autoWhoQueue = channels();
570 }
571
572 #ifdef HAVE_SSL
573 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
574   Q_UNUSED(sslErrors)
575   socket.ignoreSslErrors();
576   // TODO errorhandling
577 }
578 #endif  // HAVE_SSL
579
580 void CoreNetwork::fillBucketAndProcessQueue() {
581   if(_tokenBucket < _burstSize) {
582     _tokenBucket++;
583   }
584
585   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
586     writeToSocket(_msgQueue.takeFirst());
587   }
588 }
589
590 void CoreNetwork::writeToSocket(const QByteArray &data) {
591   socket.write(data);
592   socket.write("\r\n");
593   _tokenBucket--;
594 }
595
596 Network::Server CoreNetwork::usedServer() const {
597   if(_lastUsedServerIndex < serverList().count())
598     return serverList()[_lastUsedServerIndex];
599
600   if(!serverList().isEmpty())
601     return serverList()[0];
602
603   return Network::Server();
604 }
605
606 void CoreNetwork::requestConnect() const {
607   if(connectionState() != Disconnected) {
608     qWarning() << "Requesting connect while already being connected!";
609     return;
610   }
611   Network::requestConnect();
612 }
613
614 void CoreNetwork::requestDisconnect() const {
615   if(connectionState() == Disconnected) {
616     qWarning() << "Requesting disconnect while not being connected!";
617     return;
618   }
619   userInputHandler()->handleQuit(BufferInfo(), QString());
620 }
621
622 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
623   Network::Server currentServer = usedServer();
624   setNetworkInfo(info);
625   Core::updateNetwork(coreSession()->user(), info);
626
627   // the order of the servers might have changed,
628   // so we try to find the previously used server
629   _lastUsedServerIndex = 0;
630   for(int i = 0; i < serverList().count(); i++) {
631     Network::Server server = serverList()[i];
632     if(server.host == currentServer.host && server.port == currentServer.port) {
633       _lastUsedServerIndex = i;
634       break;
635     }
636   }
637 }