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