despammificating the pglog
[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 "coreidentity.h"
25 #include "corenetworkconfig.h"
26 #include "coresession.h"
27 #include "coreuserinputhandler.h"
28 #include "networkevent.h"
29
30 INIT_SYNCABLE_OBJECT(CoreNetwork)
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32   : Network(networkid, session),
33     _coreSession(session),
34     _userInputHandler(new CoreUserInputHandler(this)),
35     _autoReconnectCount(0),
36     _quitRequested(false),
37
38     _previousConnectionAttemptFailed(false),
39     _lastUsedServerIndex(0),
40
41     _lastPingTime(0),
42     _pingCount(0),
43    _requestedUserModes('-')
44 {
45   _autoReconnectTimer.setSingleShot(true);
46   _socketCloseTimer.setSingleShot(true);
47   connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
48
49   setPingInterval(networkConfig()->pingInterval());
50   connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
51
52   setAutoWhoDelay(networkConfig()->autoWhoDelay());
53   setAutoWhoInterval(networkConfig()->autoWhoInterval());
54
55   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
56   foreach(QString chan, channels.keys()) {
57     _channelKeys[chan.toLower()] = channels[chan];
58   }
59
60   connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
61   connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
62   connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
63   connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
64   connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
65
66   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
67   connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
68   connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
69   connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
70
71   connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
72   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
73   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
74   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
75   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
76 #ifdef HAVE_SSL
77   connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
78   connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
79 #endif
80 }
81
82 CoreNetwork::~CoreNetwork() {
83   if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
84     disconnectFromIrc(false);      // clean up, but this does not count as requested disconnect!
85   disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
86   delete _userInputHandler;
87 }
88
89 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
90   if(!bufferName.isEmpty()) {
91     IrcChannel *channel = ircChannel(bufferName);
92     if(channel)
93       return channel->decodeString(string);
94   }
95   return decodeString(string);
96 }
97
98 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
99   IrcUser *user = ircUser(userNick);
100   if(user)
101     return user->decodeString(string);
102   return decodeString(string);
103 }
104
105 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
106   if(!bufferName.isEmpty()) {
107     IrcChannel *channel = ircChannel(bufferName);
108     if(channel)
109       return channel->encodeString(string);
110   }
111   return encodeString(string);
112 }
113
114 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
115   IrcUser *user = ircUser(userNick);
116   if(user)
117     return user->encodeString(string);
118   return encodeString(string);
119 }
120
121 void CoreNetwork::connectToIrc(bool reconnecting) {
122   if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
123     _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
124     if(unlimitedReconnectRetries())
125       _autoReconnectCount = -1;
126     else
127       _autoReconnectCount = autoReconnectRetries();
128   }
129   if(serverList().isEmpty()) {
130     qWarning() << "Server list empty, ignoring connect request!";
131     return;
132   }
133   CoreIdentity *identity = identityPtr();
134   if(!identity) {
135     qWarning() << "Invalid identity configures, ignoring connect request!";
136     return;
137   }
138
139   // cleaning up old quit reason
140   _quitReason.clear();
141
142   // use a random server?
143   if(useRandomServer()) {
144     _lastUsedServerIndex = qrand() % serverList().size();
145   } else if(_previousConnectionAttemptFailed) {
146     // cycle to next server if previous connection attempt failed
147     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
148     if(++_lastUsedServerIndex >= serverList().size()) {
149       _lastUsedServerIndex = 0;
150     }
151   }
152   _previousConnectionAttemptFailed = false;
153
154   Server server = usedServer();
155   displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
156   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
157
158   if(server.useProxy) {
159     QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
160     socket.setProxy(proxy);
161   } else {
162     socket.setProxy(QNetworkProxy::NoProxy);
163   }
164
165 #ifdef HAVE_SSL
166   socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
167   if(server.useSsl) {
168     CoreIdentity *identity = identityPtr();
169     if(identity) {
170       socket.setLocalCertificate(identity->sslCert());
171       socket.setPrivateKey(identity->sslKey());
172     }
173     socket.connectToHostEncrypted(server.host, server.port);
174   } else {
175     socket.connectToHost(server.host, server.port);
176   }
177 #else
178   socket.connectToHost(server.host, server.port);
179 #endif
180 }
181
182 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) {
183   _quitRequested = requested; // see socketDisconnected();
184   if(!withReconnect) {
185     _autoReconnectTimer.stop();
186     _autoReconnectCount = 0; // prohibiting auto reconnect
187   }
188   disablePingTimeout();
189   _msgQueue.clear();
190
191   IrcUser *me_ = me();
192   if(me_) {
193     QString awayMsg;
194     if(me_->isAway())
195       awayMsg = me_->awayMessage();
196     Core::setAwayMessage(userId(), networkId(), awayMsg);
197   }
198
199   if(reason.isEmpty() && identityPtr())
200     _quitReason = identityPtr()->quitReason();
201   else
202     _quitReason = reason;
203
204   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
205   switch(socket.state()) {
206   case QAbstractSocket::ConnectedState:
207     userInputHandler()->issueQuit(_quitReason);
208     if(requested || withReconnect) {
209       // the irc server has 10 seconds to close the socket
210       _socketCloseTimer.start(10000);
211       break;
212     }
213   default:
214     socket.close();
215     socketDisconnected();
216   }
217 }
218
219 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
220   userInputHandler()->handleUserInput(buf, msg);
221 }
222
223 void CoreNetwork::putRawLine(QByteArray s) {
224   if(_tokenBucket > 0)
225     writeToSocket(s);
226   else
227     _msgQueue.append(s);
228 }
229
230 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix) {
231   QByteArray msg;
232
233   if(!prefix.isEmpty())
234     msg += ":" + prefix + " ";
235   msg += cmd.toUpper().toAscii();
236
237   for(int i = 0; i < params.size() - 1; i++) {
238     msg += " " + params[i];
239   }
240   if(!params.isEmpty())
241     msg += " :" + params.last();
242
243   putRawLine(msg);
244 }
245
246 void CoreNetwork::setChannelJoined(const QString &channel) {
247   _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
248
249   Core::setChannelPersistent(userId(), networkId(), channel, true);
250   Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
251 }
252
253 void CoreNetwork::setChannelParted(const QString &channel) {
254   removeChannelKey(channel);
255   _autoWhoQueue.removeAll(channel.toLower());
256   _autoWhoPending.remove(channel.toLower());
257
258   Core::setChannelPersistent(userId(), networkId(), channel, false);
259 }
260
261 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
262   if(key.isEmpty()) {
263     removeChannelKey(channel);
264   } else {
265     _channelKeys[channel.toLower()] = key;
266   }
267 }
268
269 void CoreNetwork::removeChannelKey(const QString &channel) {
270   _channelKeys.remove(channel.toLower());
271 }
272
273 #ifdef HAVE_QCA2
274 Cipher *CoreNetwork::cipher(const QString &target) const {
275   if(target.isEmpty())
276     return 0;
277
278   QByteArray key = cipherKey(target);
279   if(key.isEmpty())
280     return 0;
281
282   CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
283   if(channel) {
284     if(channel->cipher()->setKey(key))
285       return channel->cipher();
286   } else {
287     CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
288     if(user && user->cipher()->setKey(key))
289       return user->cipher();
290   }
291   return 0;
292 }
293
294 QByteArray CoreNetwork::cipherKey(const QString &recipient) const {
295   return _cipherKeys.value(recipient.toLower(), QByteArray());
296 }
297
298 void CoreNetwork::setCipherKey(const QString &recipient, const QByteArray &key) {
299   if(!key.isEmpty())
300     _cipherKeys[recipient.toLower()] = key;
301   else
302     _cipherKeys.remove(recipient.toLower());
303 }
304 #endif /* HAVE_QCA2 */
305
306 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
307   QString chan = channel.toLower();
308   if(_autoWhoPending.value(chan, 0) <= 0)
309     return false;
310   if(--_autoWhoPending[chan] <= 0)
311     _autoWhoPending.remove(chan);
312   return true;
313 }
314
315 void CoreNetwork::setMyNick(const QString &mynick) {
316   Network::setMyNick(mynick);
317   if(connectionState() == Network::Initializing)
318     networkInitialized();
319 }
320
321 void CoreNetwork::socketHasData() {
322   while(socket.canReadLine()) {
323     QByteArray s = socket.readLine().trimmed();
324     NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
325 #if QT_VERSION >= 0x040700
326     event->setTimestamp(QDateTime::currentDateTimeUtc());
327 #else
328     event->setTimestamp(QDateTime::currentDateTime().toUTC());
329 #endif
330     coreSession()->eventManager()->sendEvent(event);
331   }
332 }
333
334 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
335   if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
336     return;
337
338   _previousConnectionAttemptFailed = true;
339   qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
340   emit connectionError(socket.errorString());
341   displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
342   emitConnectionError(socket.errorString());
343   if(socket.state() < QAbstractSocket::ConnectedState) {
344     socketDisconnected();
345   }
346 }
347
348 void CoreNetwork::socketInitialized() {
349   Server server = usedServer();
350 #ifdef HAVE_SSL
351   if(server.useSsl && !socket.isEncrypted())
352     return;
353 #endif
354
355   CoreIdentity *identity = identityPtr();
356   if(!identity) {
357     qCritical() << "Identity invalid!";
358     disconnectFromIrc();
359     return;
360   }
361
362   // TokenBucket to avoid sending too much at once
363   _messageDelay = 2200;    // this seems to be a safe value (2.2 seconds delay)
364   _burstSize = 5;
365   _tokenBucket = _burstSize; // init with a full bucket
366   _tokenBucketTimer.start(_messageDelay);
367
368   if(networkInfo().useSasl) {
369     putRawLine(serverEncode(QString("CAP REQ :sasl")));
370   }
371   if(!server.password.isEmpty()) {
372     putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
373   }
374   QString nick;
375   if(identity->nicks().isEmpty()) {
376     nick = "quassel";
377     qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
378   } else {
379     nick = identity->nicks()[0];
380   }
381   putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
382   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
383 }
384
385 void CoreNetwork::socketDisconnected() {
386   disablePingTimeout();
387   _msgQueue.clear();
388
389   _autoWhoCycleTimer.stop();
390   _autoWhoTimer.stop();
391   _autoWhoQueue.clear();
392   _autoWhoPending.clear();
393
394   _socketCloseTimer.stop();
395
396   _tokenBucketTimer.stop();
397
398   IrcUser *me_ = me();
399   if(me_) {
400     foreach(QString channel, me_->channels())
401       displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
402   }
403
404   setConnected(false);
405   emit disconnected(networkId());
406   if(_quitRequested) {
407     _quitRequested = false;
408     setConnectionState(Network::Disconnected);
409     Core::setNetworkConnected(userId(), networkId(), false);
410   } else if(_autoReconnectCount != 0) {
411     setConnectionState(Network::Reconnecting);
412     if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
413       doAutoReconnect(); // first try is immediate
414     else
415       _autoReconnectTimer.start();
416   }
417 }
418
419 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
420   Network::ConnectionState state;
421   switch(socketState) {
422     case QAbstractSocket::UnconnectedState:
423       state = Network::Disconnected;
424       break;
425     case QAbstractSocket::HostLookupState:
426     case QAbstractSocket::ConnectingState:
427       state = Network::Connecting;
428       break;
429     case QAbstractSocket::ConnectedState:
430       state = Network::Initializing;
431       break;
432     case QAbstractSocket::ClosingState:
433       state = Network::Disconnecting;
434       break;
435     default:
436       state = Network::Disconnected;
437   }
438   setConnectionState(state);
439 }
440
441 void CoreNetwork::networkInitialized() {
442   setConnectionState(Network::Initialized);
443   setConnected(true);
444   _quitRequested = false;
445
446   if(useAutoReconnect()) {
447     // reset counter
448     _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
449   }
450
451   // restore away state
452   QString awayMsg = Core::awayMessage(userId(), networkId());
453   if(!awayMsg.isEmpty())
454     userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
455
456   sendPerform();
457
458   enablePingTimeout();
459
460   if(networkConfig()->autoWhoEnabled()) {
461     _autoWhoCycleTimer.start();
462     _autoWhoTimer.start();
463     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
464   }
465
466   Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
467   Core::setNetworkConnected(userId(), networkId(), true);
468 }
469
470 void CoreNetwork::sendPerform() {
471   BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
472
473   // do auto identify
474   if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
475     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
476   }
477
478   // restore old user modes if server default mode is set.
479   IrcUser *me_ = me();
480   if(me_) {
481     if(!me_->userModes().isEmpty()) {
482       restoreUserModes();
483     } else {
484       connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
485       connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
486     }
487   }
488
489   // send perform list
490   foreach(QString line, perform()) {
491     if(!line.isEmpty()) userInput(statusBuf, line);
492   }
493
494   // rejoin channels we've been in
495   if(rejoinChannels()) {
496     QStringList channels, keys;
497     foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
498       QString key = channelKey(chan);
499       if(!key.isEmpty()) {
500         channels.prepend(chan);
501         keys.prepend(key);
502       } else {
503         channels.append(chan);
504       }
505     }
506     QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
507     if(!joinString.isEmpty())
508       userInputHandler()->handleJoin(statusBuf, joinString);
509   }
510 }
511
512 void CoreNetwork::restoreUserModes() {
513   IrcUser *me_ = me();
514   Q_ASSERT(me_);
515
516   disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
517   disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
518
519   QString modesDelta = Core::userModes(userId(), networkId());
520   QString currentModes = me_->userModes();
521
522   QString addModes, removeModes;
523   if(modesDelta.contains('-')) {
524     addModes = modesDelta.section('-', 0, 0);
525     removeModes = modesDelta.section('-', 1);
526   } else {
527     addModes = modesDelta;
528   }
529
530
531   addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
532   if(currentModes.isEmpty())
533     removeModes = QString();
534   else
535     removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
536
537   if(addModes.isEmpty() && removeModes.isEmpty())
538     return;
539
540   if(!addModes.isEmpty())
541     addModes = '+' + addModes;
542   if(!removeModes.isEmpty())
543     removeModes = '-' + removeModes;
544
545   // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
546   putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
547 }
548
549 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
550   QString addModes;
551   QString removeModes;
552   bool addMode = true;
553
554   for(int i = 0; i < requestedModes.length(); i++) {
555     if(requestedModes[i] == '+') {
556       addMode = true;
557       continue;
558     }
559     if(requestedModes[i] == '-') {
560       addMode = false;
561       continue;
562     }
563     if(addMode) {
564       addModes += requestedModes[i];
565     } else {
566       removeModes += requestedModes[i];
567     }
568   }
569
570
571   QString addModesOld = _requestedUserModes.section('-', 0, 0);
572   QString removeModesOld = _requestedUserModes.section('-', 1);
573
574   addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
575   addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
576   addModes += addModesOld;
577
578   removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
579   removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
580   removeModes += removeModesOld;
581
582   _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
583 }
584
585 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
586   QString persistentUserModes = Core::userModes(userId(), networkId());
587
588   QString requestedAdd = _requestedUserModes.section('-', 0, 0);
589   QString requestedRemove = _requestedUserModes.section('-', 1);
590
591   QString persistentAdd, persistentRemove;
592   if(persistentUserModes.contains('-')) {
593     persistentAdd = persistentUserModes.section('-', 0, 0);
594     persistentRemove = persistentUserModes.section('-', 1);
595   } else {
596     persistentAdd = persistentUserModes;
597   }
598
599   // remove modes we didn't issue
600   if(requestedAdd.isEmpty())
601     addModes = QString();
602   else
603     addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
604
605   if(requestedRemove.isEmpty())
606     removeModes = QString();
607   else
608     removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
609
610   // deduplicate
611   persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
612   persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
613
614   // update
615   persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
616   persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
617
618   // update issued mode list
619   requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
620   requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
621   _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
622
623   persistentAdd += addModes;
624   persistentRemove += removeModes;
625   Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
626 }
627
628 void CoreNetwork::resetPersistentModes() {
629   _requestedUserModes = QString('-');
630   Core::setUserModes(userId(), networkId(), QString());
631 }
632
633 void CoreNetwork::setUseAutoReconnect(bool use) {
634   Network::setUseAutoReconnect(use);
635   if(!use)
636     _autoReconnectTimer.stop();
637 }
638
639 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
640   Network::setAutoReconnectInterval(interval);
641   _autoReconnectTimer.setInterval(interval * 1000);
642 }
643
644 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
645   Network::setAutoReconnectRetries(retries);
646   if(_autoReconnectCount != 0) {
647     if(unlimitedReconnectRetries())
648       _autoReconnectCount = -1;
649     else
650       _autoReconnectCount = autoReconnectRetries();
651   }
652 }
653
654 void CoreNetwork::doAutoReconnect() {
655   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
656     qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
657     return;
658   }
659   if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
660     _autoReconnectCount--; // -2 means we delay the next reconnect
661   connectToIrc(true);
662 }
663
664 void CoreNetwork::sendPing() {
665   uint now = QDateTime::currentDateTime().toTime_t();
666   if(_pingCount != 0) {
667     qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
668              << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
669   }
670   if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
671     // the second check compares the actual elapsed time since the last ping and the pingTimer interval
672     // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
673     // and unable to even handle a ping answer. So we ignore those misses.
674     disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
675   } else {
676     _lastPingTime = now;
677     _pingCount++;
678     userInputHandler()->handlePing(BufferInfo(), QString());
679   }
680 }
681
682 void CoreNetwork::enablePingTimeout(bool enable) {
683   if(!enable)
684     disablePingTimeout();
685   else {
686     resetPingTimeout();
687     if(networkConfig()->pingTimeoutEnabled())
688       _pingTimer.start();
689   }
690 }
691
692 void CoreNetwork::disablePingTimeout() {
693   _pingTimer.stop();
694   resetPingTimeout();
695 }
696
697 void CoreNetwork::setPingInterval(int interval) {
698   _pingTimer.setInterval(interval * 1000);
699 }
700
701 /******** AutoWHO ********/
702
703 void CoreNetwork::startAutoWhoCycle() {
704   if(!_autoWhoQueue.isEmpty()) {
705     _autoWhoCycleTimer.stop();
706     return;
707   }
708   _autoWhoQueue = channels();
709 }
710
711 void CoreNetwork::setAutoWhoDelay(int delay) {
712   _autoWhoTimer.setInterval(delay * 1000);
713 }
714
715 void CoreNetwork::setAutoWhoInterval(int interval) {
716   _autoWhoCycleTimer.setInterval(interval * 1000);
717 }
718
719 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
720   if(enabled && isConnected() && !_autoWhoTimer.isActive())
721     _autoWhoTimer.start();
722   else if(!enabled) {
723     _autoWhoTimer.stop();
724     _autoWhoCycleTimer.stop();
725   }
726 }
727
728 void CoreNetwork::sendAutoWho() {
729   // Don't send autowho if there are still some pending
730   if(_autoWhoPending.count())
731     return;
732
733   while(!_autoWhoQueue.isEmpty()) {
734     QString chan = _autoWhoQueue.takeFirst();
735     IrcChannel *ircchan = ircChannel(chan);
736     if(!ircchan) continue;
737     if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
738       continue;
739     _autoWhoPending[chan]++;
740     putRawLine("WHO " + serverEncode(chan));
741     break;
742   }
743   if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
744     // Timer was stopped, means a new cycle is due immediately
745     _autoWhoCycleTimer.start();
746     startAutoWhoCycle();
747   }
748 }
749
750 #ifdef HAVE_SSL
751 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
752   Q_UNUSED(sslErrors)
753   socket.ignoreSslErrors();
754   // TODO errorhandling
755 }
756 #endif  // HAVE_SSL
757
758 void CoreNetwork::fillBucketAndProcessQueue() {
759   if(_tokenBucket < _burstSize) {
760     _tokenBucket++;
761   }
762
763   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
764     writeToSocket(_msgQueue.takeFirst());
765   }
766 }
767
768 void CoreNetwork::writeToSocket(const QByteArray &data) {
769   socket.write(data);
770   socket.write("\r\n");
771   _tokenBucket--;
772 }
773
774 Network::Server CoreNetwork::usedServer() const {
775   if(_lastUsedServerIndex < serverList().count())
776     return serverList()[_lastUsedServerIndex];
777
778   if(!serverList().isEmpty())
779     return serverList()[0];
780
781   return Network::Server();
782 }
783
784 void CoreNetwork::requestConnect() const {
785   if(connectionState() != Disconnected) {
786     qWarning() << "Requesting connect while already being connected!";
787     return;
788   }
789   QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
790 }
791
792 void CoreNetwork::requestDisconnect() const {
793   if(connectionState() == Disconnected) {
794     qWarning() << "Requesting disconnect while not being connected!";
795     return;
796   }
797   userInputHandler()->handleQuit(BufferInfo(), QString());
798 }
799
800 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
801   Network::Server currentServer = usedServer();
802   setNetworkInfo(info);
803   Core::updateNetwork(coreSession()->user(), info);
804
805   // the order of the servers might have changed,
806   // so we try to find the previously used server
807   _lastUsedServerIndex = 0;
808   for(int i = 0; i < serverList().count(); i++) {
809     Network::Server server = serverList()[i];
810     if(server.host == currentServer.host && server.port == currentServer.port) {
811       _lastUsedServerIndex = i;
812       break;
813     }
814   }
815 }