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