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