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