76a9d5592c7e1ec61ad7b152ca13935a804a49ad
[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 #include "corenetworkconfig.h"
27
28 #include "ircserverhandler.h"
29 #include "coreuserinputhandler.h"
30 #include "ctcphandler.h"
31
32 INIT_SYNCABLE_OBJECT(CoreNetwork)
33 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
34   : Network(networkid, session),
35     _coreSession(session),
36     _ircServerHandler(new IrcServerHandler(this)),
37     _userInputHandler(new CoreUserInputHandler(this)),
38     _ctcpHandler(new CtcpHandler(this)),
39     _autoReconnectCount(0),
40     _quitRequested(false),
41
42     _previousConnectionAttemptFailed(false),
43     _lastUsedServerIndex(0),
44
45     _lastPingTime(0),
46     _pingCount(0),
47    _requestedUserModes('-')
48 {
49   _autoReconnectTimer.setSingleShot(true);
50   _socketCloseTimer.setSingleShot(true);
51   connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
52
53   setPingInterval(networkConfig()->pingInterval());
54   connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
55
56   setAutoWhoDelay(networkConfig()->autoWhoDelay());
57   setAutoWhoInterval(networkConfig()->autoWhoInterval());
58
59   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
60   foreach(QString chan, channels.keys()) {
61     _channelKeys[chan.toLower()] = channels[chan];
62   }
63
64   connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
65   connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
66   connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
67   connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
68   connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
69
70   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
71   connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
72   connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
73   connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
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   _msgQueue.clear();
196
197   IrcUser *me_ = me();
198   if(me_) {
199     QString awayMsg;
200     if(me_->isAway())
201       awayMsg = me_->awayMessage();
202     Core::setAwayMessage(userId(), networkId(), awayMsg);
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   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   _messageDelay = 2200;    // this seems to be a safe value (2.2 seconds delay)
331   _burstSize = 5;
332   _tokenBucket = _burstSize; // init with a full bucket
333   _tokenBucketTimer.start(_messageDelay);
334
335   if(networkInfo().useSasl) {
336     putRawLine(serverEncode(QString("CAP REQ :sasl")));
337   }
338   if(!server.password.isEmpty()) {
339     putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
340   }
341   QString nick;
342   if(identity->nicks().isEmpty()) {
343     nick = "quassel";
344     qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
345   } else {
346     nick = identity->nicks()[0];
347   }
348   putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
349   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
350 }
351
352 void CoreNetwork::socketDisconnected() {
353   disablePingTimeout();
354   _msgQueue.clear();
355
356   _autoWhoCycleTimer.stop();
357   _autoWhoTimer.stop();
358   _autoWhoQueue.clear();
359   _autoWhoPending.clear();
360
361   _socketCloseTimer.stop();
362
363   _tokenBucketTimer.stop();
364
365   IrcUser *me_ = me();
366   if(me_) {
367     foreach(QString channel, me_->channels())
368       displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
369   }
370
371   setConnected(false);
372   emit disconnected(networkId());
373   if(_quitRequested) {
374     _quitRequested = false;
375     setConnectionState(Network::Disconnected);
376     Core::setNetworkConnected(userId(), networkId(), false);
377   } else if(_autoReconnectCount != 0) {
378     setConnectionState(Network::Reconnecting);
379     if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
380       doAutoReconnect(); // first try is immediate
381     else
382       _autoReconnectTimer.start();
383   }
384 }
385
386 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
387   Network::ConnectionState state;
388   switch(socketState) {
389     case QAbstractSocket::UnconnectedState:
390       state = Network::Disconnected;
391       break;
392     case QAbstractSocket::HostLookupState:
393     case QAbstractSocket::ConnectingState:
394       state = Network::Connecting;
395       break;
396     case QAbstractSocket::ConnectedState:
397       state = Network::Initializing;
398       break;
399     case QAbstractSocket::ClosingState:
400       state = Network::Disconnecting;
401       break;
402     default:
403       state = Network::Disconnected;
404   }
405   setConnectionState(state);
406 }
407
408 void CoreNetwork::networkInitialized() {
409   setConnectionState(Network::Initialized);
410   setConnected(true);
411   _quitRequested = false;
412
413   if(useAutoReconnect()) {
414     // reset counter
415     _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
416   }
417
418   // restore away state
419   QString awayMsg = Core::awayMessage(userId(), networkId());
420   if(!awayMsg.isEmpty())
421     userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
422
423   sendPerform();
424
425   enablePingTimeout();
426
427   if(networkConfig()->autoWhoEnabled()) {
428     _autoWhoCycleTimer.start();
429     _autoWhoTimer.start();
430     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
431   }
432
433   Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
434   Core::setNetworkConnected(userId(), networkId(), true);
435 }
436
437 void CoreNetwork::sendPerform() {
438   BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
439
440   // do auto identify
441   if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
442     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
443   }
444
445   // restore old user modes if server default mode is set.
446   IrcUser *me_ = me();
447   if(me_) {
448     if(!me_->userModes().isEmpty()) {
449       restoreUserModes();
450     } else {
451       connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
452       connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
453     }
454   }
455
456   // send perform list
457   foreach(QString line, perform()) {
458     if(!line.isEmpty()) userInput(statusBuf, line);
459   }
460
461   // rejoin channels we've been in
462   if(rejoinChannels()) {
463     QStringList channels, keys;
464     foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
465       QString key = channelKey(chan);
466       if(!key.isEmpty()) {
467         channels.prepend(chan);
468         keys.prepend(key);
469       } else {
470         channels.append(chan);
471       }
472     }
473     QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
474     if(!joinString.isEmpty())
475       userInputHandler()->handleJoin(statusBuf, joinString);
476   }
477 }
478
479 void CoreNetwork::restoreUserModes() {
480   IrcUser *me_ = me();
481   Q_ASSERT(me_);
482
483   disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
484   disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
485
486   QString modesDelta = Core::userModes(userId(), networkId());
487   QString currentModes = me_->userModes();
488
489   QString addModes, removeModes;
490   if(modesDelta.contains('-')) {
491     addModes = modesDelta.section('-', 0, 0);
492     removeModes = modesDelta.section('-', 1);
493   } else {
494     addModes = modesDelta;
495   }
496
497
498   addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
499   if(currentModes.isEmpty())
500     removeModes = QString();
501   else
502     removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
503
504   if(addModes.isEmpty() && removeModes.isEmpty())
505     return;
506
507   if(!addModes.isEmpty())
508     addModes = '+' + addModes;
509   if(!removeModes.isEmpty())
510     removeModes = '-' + removeModes;
511
512   // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
513   putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
514 }
515
516 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
517   QString addModes;
518   QString removeModes;
519   bool addMode = true;
520
521   for(int i = 0; i < requestedModes.length(); i++) {
522     if(requestedModes[i] == '+') {
523       addMode = true;
524       continue;
525     }
526     if(requestedModes[i] == '-') {
527       addMode = false;
528       continue;
529     }
530     if(addMode) {
531       addModes += requestedModes[i];
532     } else {
533       removeModes += requestedModes[i];
534     }
535   }
536
537
538   QString addModesOld = _requestedUserModes.section('-', 0, 0);
539   QString removeModesOld = _requestedUserModes.section('-', 1);
540
541   addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
542   addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
543   addModes += addModesOld;
544
545   removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
546   removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
547   removeModes += removeModesOld;
548
549   _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
550 }
551
552 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
553   QString persistentUserModes = Core::userModes(userId(), networkId());
554
555   QString requestedAdd = _requestedUserModes.section('-', 0, 0);
556   QString requestedRemove = _requestedUserModes.section('-', 1);
557
558   QString persistentAdd, persistentRemove;
559   if(persistentUserModes.contains('-')) {
560     persistentAdd = persistentUserModes.section('-', 0, 0);
561     persistentRemove = persistentUserModes.section('-', 1);
562   } else {
563     persistentAdd = persistentUserModes;
564   }
565
566   // remove modes we didn't issue
567   if(requestedAdd.isEmpty())
568     addModes = QString();
569   else
570     addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
571
572   if(requestedRemove.isEmpty())
573     removeModes = QString();
574   else
575     removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
576
577   // deduplicate
578   persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
579   persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
580
581   // update
582   persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
583   persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
584
585   // update issued mode list
586   requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
587   requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
588   _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
589
590   persistentAdd += addModes;
591   persistentRemove += removeModes;
592   Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
593 }
594
595 void CoreNetwork::resetPersistentModes() {
596   _requestedUserModes = QString('-');
597   Core::setUserModes(userId(), networkId(), QString());
598 }
599
600 void CoreNetwork::setUseAutoReconnect(bool use) {
601   Network::setUseAutoReconnect(use);
602   if(!use)
603     _autoReconnectTimer.stop();
604 }
605
606 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
607   Network::setAutoReconnectInterval(interval);
608   _autoReconnectTimer.setInterval(interval * 1000);
609 }
610
611 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
612   Network::setAutoReconnectRetries(retries);
613   if(_autoReconnectCount != 0) {
614     if(unlimitedReconnectRetries())
615       _autoReconnectCount = -1;
616     else
617       _autoReconnectCount = autoReconnectRetries();
618   }
619 }
620
621 void CoreNetwork::doAutoReconnect() {
622   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
623     qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
624     return;
625   }
626   if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
627     _autoReconnectCount--; // -2 means we delay the next reconnect
628   connectToIrc(true);
629 }
630
631 void CoreNetwork::sendPing() {
632   uint now = QDateTime::currentDateTime().toTime_t();
633   if(_pingCount != 0) {
634     qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
635              << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
636   }
637   if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
638     // the second check compares the actual elapsed time since the last ping and the pingTimer interval
639     // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
640     // and unable to even handle a ping answer. So we ignore those misses.
641     disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
642   } else {
643     _lastPingTime = now;
644     _pingCount++;
645     userInputHandler()->handlePing(BufferInfo(), QString());
646   }
647 }
648
649 void CoreNetwork::enablePingTimeout(bool enable) {
650   if(!enable)
651     disablePingTimeout();
652   else {
653     resetPingTimeout();
654     if(networkConfig()->pingTimeoutEnabled())
655       _pingTimer.start();
656   }
657 }
658
659 void CoreNetwork::disablePingTimeout() {
660   _pingTimer.stop();
661   resetPingTimeout();
662 }
663
664 void CoreNetwork::setPingInterval(int interval) {
665   _pingTimer.setInterval(interval * 1000);
666 }
667
668 /******** AutoWHO ********/
669
670 void CoreNetwork::startAutoWhoCycle() {
671   if(!_autoWhoQueue.isEmpty()) {
672     _autoWhoCycleTimer.stop();
673     return;
674   }
675   _autoWhoQueue = channels();
676 }
677
678 void CoreNetwork::setAutoWhoDelay(int delay) {
679   _autoWhoTimer.setInterval(delay * 1000);
680 }
681
682 void CoreNetwork::setAutoWhoInterval(int interval) {
683   _autoWhoCycleTimer.setInterval(interval * 1000);
684 }
685
686 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
687   if(enabled && isConnected() && !_autoWhoTimer.isActive())
688     _autoWhoTimer.start();
689   else if(!enabled) {
690     _autoWhoTimer.stop();
691     _autoWhoCycleTimer.stop();
692   }
693 }
694
695 void CoreNetwork::sendAutoWho() {
696   // Don't send autowho if there are still some pending
697   if(_autoWhoPending.count())
698     return;
699
700   while(!_autoWhoQueue.isEmpty()) {
701     QString chan = _autoWhoQueue.takeFirst();
702     IrcChannel *ircchan = ircChannel(chan);
703     if(!ircchan) continue;
704     if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
705       continue;
706     _autoWhoPending[chan]++;
707     putRawLine("WHO " + serverEncode(chan));
708     break;
709   }
710   if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
711     // Timer was stopped, means a new cycle is due immediately
712     _autoWhoCycleTimer.start();
713     startAutoWhoCycle();
714   }
715 }
716
717 #ifdef HAVE_SSL
718 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
719   Q_UNUSED(sslErrors)
720   socket.ignoreSslErrors();
721   // TODO errorhandling
722 }
723 #endif  // HAVE_SSL
724
725 void CoreNetwork::fillBucketAndProcessQueue() {
726   if(_tokenBucket < _burstSize) {
727     _tokenBucket++;
728   }
729
730   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
731     writeToSocket(_msgQueue.takeFirst());
732   }
733 }
734
735 void CoreNetwork::writeToSocket(const QByteArray &data) {
736   socket.write(data);
737   socket.write("\r\n");
738   _tokenBucket--;
739 }
740
741 Network::Server CoreNetwork::usedServer() const {
742   if(_lastUsedServerIndex < serverList().count())
743     return serverList()[_lastUsedServerIndex];
744
745   if(!serverList().isEmpty())
746     return serverList()[0];
747
748   return Network::Server();
749 }
750
751 void CoreNetwork::requestConnect() const {
752   if(connectionState() != Disconnected) {
753     qWarning() << "Requesting connect while already being connected!";
754     return;
755   }
756   QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
757 }
758
759 void CoreNetwork::requestDisconnect() const {
760   if(connectionState() == Disconnected) {
761     qWarning() << "Requesting disconnect while not being connected!";
762     return;
763   }
764   userInputHandler()->handleQuit(BufferInfo(), QString());
765 }
766
767 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
768   Network::Server currentServer = usedServer();
769   setNetworkInfo(info);
770   Core::updateNetwork(coreSession()->user(), info);
771
772   // the order of the servers might have changed,
773   // so we try to find the previously used server
774   _lastUsedServerIndex = 0;
775   for(int i = 0; i < serverList().count(); i++) {
776     Network::Server server = serverList()[i];
777     if(server.host == currentServer.host && server.port == currentServer.port) {
778       _lastUsedServerIndex = i;
779       break;
780     }
781   }
782 }