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