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