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