Allow prioritizing QUIT over other commands
[quassel.git] / src / core / corenetwork.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include <QHostInfo>
22
23 #include "corenetwork.h"
24
25 #include "core.h"
26 #include "coreidentity.h"
27 #include "corenetworkconfig.h"
28 #include "coresession.h"
29 #include "coreuserinputhandler.h"
30 #include "networkevent.h"
31
32 // IRCv3 capabilities
33 #include "irccap.h"
34
35 INIT_SYNCABLE_OBJECT(CoreNetwork)
36 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
37     : Network(networkid, session),
38     _coreSession(session),
39     _userInputHandler(new CoreUserInputHandler(this)),
40     _autoReconnectCount(0),
41     _quitRequested(false),
42
43     _previousConnectionAttemptFailed(false),
44     _lastUsedServerIndex(0),
45
46     _lastPingTime(0),
47     _pingCount(0),
48     _sendPings(false),
49     _requestedUserModes('-')
50 {
51     _autoReconnectTimer.setSingleShot(true);
52     connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
53
54     setPingInterval(networkConfig()->pingInterval());
55     connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
56
57     setAutoWhoDelay(networkConfig()->autoWhoDelay());
58     setAutoWhoInterval(networkConfig()->autoWhoInterval());
59
60     QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
61     foreach(QString chan, channels.keys()) {
62         _channelKeys[chan.toLower()] = channels[chan];
63     }
64
65     connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
66     connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
67     connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
68     connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
69     connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
70
71     connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
72     connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
73     connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
74     connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
75
76     connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
77     connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
78     connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
79     connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
80 #ifdef HAVE_SSL
81     connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
82     connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
83 #endif
84     connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
85
86     // IRCv3 capability handling
87     // These react to CAP messages from the server
88     connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
89     connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
90     connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
91
92     if (Quassel::isOptionSet("oidentd")) {
93         connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
94         connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
95     }
96 }
97
98
99 CoreNetwork::~CoreNetwork()
100 {
101     if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
102         disconnectFromIrc(false);  // clean up, but this does not count as requested disconnect!
103     disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
104     delete _userInputHandler;
105 }
106
107
108 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
109 {
110     if (!bufferName.isEmpty()) {
111         IrcChannel *channel = ircChannel(bufferName);
112         if (channel)
113             return channel->decodeString(string);
114     }
115     return decodeString(string);
116 }
117
118
119 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
120 {
121     IrcUser *user = ircUser(userNick);
122     if (user)
123         return user->decodeString(string);
124     return decodeString(string);
125 }
126
127
128 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
129 {
130     if (!bufferName.isEmpty()) {
131         IrcChannel *channel = ircChannel(bufferName);
132         if (channel)
133             return channel->encodeString(string);
134     }
135     return encodeString(string);
136 }
137
138
139 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
140 {
141     IrcUser *user = ircUser(userNick);
142     if (user)
143         return user->encodeString(string);
144     return encodeString(string);
145 }
146
147
148 void CoreNetwork::connectToIrc(bool reconnecting)
149 {
150     if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
151         _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
152         if (unlimitedReconnectRetries())
153             _autoReconnectCount = -1;
154         else
155             _autoReconnectCount = autoReconnectRetries();
156     }
157     if (serverList().isEmpty()) {
158         qWarning() << "Server list empty, ignoring connect request!";
159         return;
160     }
161     CoreIdentity *identity = identityPtr();
162     if (!identity) {
163         qWarning() << "Invalid identity configures, ignoring connect request!";
164         return;
165     }
166
167     // cleaning up old quit reason
168     _quitReason.clear();
169
170     // Reset capability negotiation tracking, also handling server changes during reconnect
171     _capsQueued.clear();
172     clearCaps();
173     _capNegotiationActive = false;
174     _capInitialNegotiationEnded = false;
175
176     // use a random server?
177     if (useRandomServer()) {
178         _lastUsedServerIndex = qrand() % serverList().size();
179     }
180     else if (_previousConnectionAttemptFailed) {
181         // cycle to next server if previous connection attempt failed
182         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
183         if (++_lastUsedServerIndex >= serverList().size()) {
184             _lastUsedServerIndex = 0;
185         }
186     }
187     _previousConnectionAttemptFailed = false;
188
189     Server server = usedServer();
190     displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
191     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
192
193     if (server.useProxy) {
194         QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
195         socket.setProxy(proxy);
196     }
197     else {
198         socket.setProxy(QNetworkProxy::NoProxy);
199     }
200
201     enablePingTimeout();
202
203     // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
204     // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
205     QHostInfo::fromName(server.host);
206
207 #ifdef HAVE_SSL
208     if (server.useSsl) {
209         CoreIdentity *identity = identityPtr();
210         if (identity) {
211             socket.setLocalCertificate(identity->sslCert());
212             socket.setPrivateKey(identity->sslKey());
213         }
214         socket.connectToHostEncrypted(server.host, server.port);
215     }
216     else {
217         socket.connectToHost(server.host, server.port);
218     }
219 #else
220     socket.connectToHost(server.host, server.port);
221 #endif
222 }
223
224
225 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
226                                     bool forceImmediate)
227 {
228     _quitRequested = requested; // see socketDisconnected();
229     if (!withReconnect) {
230         _autoReconnectTimer.stop();
231         _autoReconnectCount = 0; // prohibiting auto reconnect
232     }
233     disablePingTimeout();
234     _msgQueue.clear();
235
236     IrcUser *me_ = me();
237     if (me_) {
238         QString awayMsg;
239         if (me_->isAway())
240             awayMsg = me_->awayMessage();
241         Core::setAwayMessage(userId(), networkId(), awayMsg);
242     }
243
244     if (reason.isEmpty() && identityPtr())
245         _quitReason = identityPtr()->quitReason();
246     else
247         _quitReason = reason;
248
249     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
250     if (socket.state() == QAbstractSocket::UnconnectedState) {
251         socketDisconnected();
252     } else {
253         if (socket.state() == QAbstractSocket::ConnectedState) {
254             userInputHandler()->issueQuit(_quitReason, forceImmediate);
255         } else {
256             socket.close();
257         }
258         if (requested || withReconnect) {
259             // the irc server has 10 seconds to close the socket
260             _socketCloseTimer.start(10000);
261         }
262     }
263 }
264
265
266 void CoreNetwork::userInput(BufferInfo buf, QString msg)
267 {
268     userInputHandler()->handleUserInput(buf, msg);
269 }
270
271
272 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
273 {
274     if (_tokenBucket > 0) {
275         writeToSocket(s);
276     } else {
277         if (prepend) {
278             _msgQueue.prepend(s);
279         } else {
280             _msgQueue.append(s);
281         }
282     }
283 }
284
285
286 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix, const bool prepend)
287 {
288     QByteArray msg;
289
290     if (!prefix.isEmpty())
291         msg += ":" + prefix + " ";
292     msg += cmd.toUpper().toLatin1();
293
294     for (int i = 0; i < params.size(); i++) {
295         msg += " ";
296
297         if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
298             msg += ":";
299
300         msg += params[i];
301     }
302
303     putRawLine(msg, prepend);
304 }
305
306
307 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix, const bool prependAll)
308 {
309     QListIterator<QList<QByteArray>> i(params);
310     while (i.hasNext()) {
311         QList<QByteArray> msg = i.next();
312         putCmd(cmd, msg, prefix, prependAll);
313     }
314 }
315
316
317 void CoreNetwork::setChannelJoined(const QString &channel)
318 {
319     queueAutoWhoOneshot(channel); // check this new channel first
320
321     Core::setChannelPersistent(userId(), networkId(), channel, true);
322     Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
323 }
324
325
326 void CoreNetwork::setChannelParted(const QString &channel)
327 {
328     removeChannelKey(channel);
329     _autoWhoQueue.removeAll(channel.toLower());
330     _autoWhoPending.remove(channel.toLower());
331
332     Core::setChannelPersistent(userId(), networkId(), channel, false);
333 }
334
335
336 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
337 {
338     if (key.isEmpty()) {
339         removeChannelKey(channel);
340     }
341     else {
342         _channelKeys[channel.toLower()] = key;
343     }
344 }
345
346
347 void CoreNetwork::removeChannelKey(const QString &channel)
348 {
349     _channelKeys.remove(channel.toLower());
350 }
351
352
353 #ifdef HAVE_QCA2
354 Cipher *CoreNetwork::cipher(const QString &target)
355 {
356     if (target.isEmpty())
357         return 0;
358
359     if (!Cipher::neededFeaturesAvailable())
360         return 0;
361
362     CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
363     if (channel) {
364         return channel->cipher();
365     }
366     CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
367     if (user) {
368         return user->cipher();
369     } else if (!isChannelName(target)) {
370         return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
371     }
372     return 0;
373 }
374
375
376 QByteArray CoreNetwork::cipherKey(const QString &target) const
377 {
378     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
379     if (c)
380         return c->cipher()->key();
381
382     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
383     if (u)
384         return u->cipher()->key();
385
386     return QByteArray();
387 }
388
389
390 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
391 {
392     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
393     if (c) {
394         c->setEncrypted(c->cipher()->setKey(key));
395         return;
396     }
397
398     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
399     if (!u && !isChannelName(target))
400         u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
401
402     if (u) {
403         u->setEncrypted(u->cipher()->setKey(key));
404         return;
405     }
406 }
407
408
409 bool CoreNetwork::cipherUsesCBC(const QString &target)
410 {
411     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
412     if (c)
413         return c->cipher()->usesCBC();
414     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
415     if (u)
416         return u->cipher()->usesCBC();
417
418     return false;
419 }
420 #endif /* HAVE_QCA2 */
421
422 bool CoreNetwork::setAutoWhoDone(const QString &channel)
423 {
424     QString chan = channel.toLower();
425     if (_autoWhoPending.value(chan, 0) <= 0)
426         return false;
427     if (--_autoWhoPending[chan] <= 0)
428         _autoWhoPending.remove(chan);
429     return true;
430 }
431
432
433 void CoreNetwork::setMyNick(const QString &mynick)
434 {
435     Network::setMyNick(mynick);
436     if (connectionState() == Network::Initializing)
437         networkInitialized();
438 }
439
440
441 void CoreNetwork::socketHasData()
442 {
443     while (socket.canReadLine()) {
444         QByteArray s = socket.readLine();
445         if (s.endsWith("\r\n"))
446             s.chop(2);
447         else if (s.endsWith("\n"))
448             s.chop(1);
449         NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
450         event->setTimestamp(QDateTime::currentDateTimeUtc());
451         emit newEvent(event);
452     }
453 }
454
455
456 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
457 {
458     if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
459         return;
460
461     _previousConnectionAttemptFailed = true;
462     qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
463     emit connectionError(socket.errorString());
464     displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
465     emitConnectionError(socket.errorString());
466     if (socket.state() < QAbstractSocket::ConnectedState) {
467         socketDisconnected();
468     }
469 }
470
471
472 void CoreNetwork::socketInitialized()
473 {
474     CoreIdentity *identity = identityPtr();
475     if (!identity) {
476         qCritical() << "Identity invalid!";
477         disconnectFromIrc();
478         return;
479     }
480
481     Server server = usedServer();
482
483 #ifdef HAVE_SSL
484     // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
485     // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
486     if (!server.useSsl || !socket.isEncrypted()) {
487         emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
488     }
489
490     if (server.useSsl && !socket.isEncrypted()) {
491         // We'll finish setup once we're encrypted, and called again
492         return;
493     }
494 #else
495     emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
496 #endif
497
498     socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
499
500     // TokenBucket to avoid sending too much at once
501     _messageDelay = 2200;  // this seems to be a safe value (2.2 seconds delay)
502     _burstSize = 5;
503     _tokenBucket = _burstSize; // init with a full bucket
504     _tokenBucketTimer.start(_messageDelay);
505
506     // Request capabilities as per IRCv3.2 specifications
507     // Older servers should ignore this; newer servers won't downgrade to RFC1459
508     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
509     putRawLine(serverEncode(QString("CAP LS 302")));
510
511     if (!server.password.isEmpty()) {
512         putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
513     }
514     QString nick;
515     if (identity->nicks().isEmpty()) {
516         nick = "quassel";
517         qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
518     }
519     else {
520         nick = identity->nicks()[0];
521     }
522     putRawLine(serverEncode(QString("NICK %1").arg(nick)));
523     putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
524 }
525
526
527 void CoreNetwork::socketDisconnected()
528 {
529     disablePingTimeout();
530     _msgQueue.clear();
531
532     _autoWhoCycleTimer.stop();
533     _autoWhoTimer.stop();
534     _autoWhoQueue.clear();
535     _autoWhoPending.clear();
536
537     _socketCloseTimer.stop();
538
539     _tokenBucketTimer.stop();
540
541     IrcUser *me_ = me();
542     if (me_) {
543         foreach(QString channel, me_->channels())
544         displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
545     }
546
547     setConnected(false);
548     emit disconnected(networkId());
549     emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
550     if (_quitRequested) {
551         _quitRequested = false;
552         setConnectionState(Network::Disconnected);
553         Core::setNetworkConnected(userId(), networkId(), false);
554     }
555     else if (_autoReconnectCount != 0) {
556         setConnectionState(Network::Reconnecting);
557         if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
558             doAutoReconnect();  // first try is immediate
559         else
560             _autoReconnectTimer.start();
561     }
562 }
563
564
565 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
566 {
567     Network::ConnectionState state;
568     switch (socketState) {
569     case QAbstractSocket::UnconnectedState:
570         state = Network::Disconnected;
571         socketDisconnected();
572         break;
573     case QAbstractSocket::HostLookupState:
574     case QAbstractSocket::ConnectingState:
575         state = Network::Connecting;
576         break;
577     case QAbstractSocket::ConnectedState:
578         state = Network::Initializing;
579         break;
580     case QAbstractSocket::ClosingState:
581         state = Network::Disconnecting;
582         break;
583     default:
584         state = Network::Disconnected;
585     }
586     setConnectionState(state);
587 }
588
589
590 void CoreNetwork::networkInitialized()
591 {
592     setConnectionState(Network::Initialized);
593     setConnected(true);
594     _quitRequested = false;
595
596     if (useAutoReconnect()) {
597         // reset counter
598         _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
599     }
600
601     // restore away state
602     QString awayMsg = Core::awayMessage(userId(), networkId());
603     if (!awayMsg.isEmpty())
604         userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
605
606     sendPerform();
607
608     _sendPings = true;
609
610     if (networkConfig()->autoWhoEnabled()) {
611         _autoWhoCycleTimer.start();
612         _autoWhoTimer.start();
613         startAutoWhoCycle(); // FIXME wait for autojoin to be completed
614     }
615
616     Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
617     Core::setNetworkConnected(userId(), networkId(), true);
618 }
619
620
621 void CoreNetwork::sendPerform()
622 {
623     BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
624
625     // do auto identify
626     if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
627         userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
628     }
629
630     // restore old user modes if server default mode is set.
631     IrcUser *me_ = me();
632     if (me_) {
633         if (!me_->userModes().isEmpty()) {
634             restoreUserModes();
635         }
636         else {
637             connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
638             connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
639         }
640     }
641
642     // send perform list
643     foreach(QString line, perform()) {
644         if (!line.isEmpty()) userInput(statusBuf, line);
645     }
646
647     // rejoin channels we've been in
648     if (rejoinChannels()) {
649         QStringList channels, keys;
650         foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
651             QString key = channelKey(chan);
652             if (!key.isEmpty()) {
653                 channels.prepend(chan);
654                 keys.prepend(key);
655             }
656             else {
657                 channels.append(chan);
658             }
659         }
660         QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
661         if (!joinString.isEmpty())
662             userInputHandler()->handleJoin(statusBuf, joinString);
663     }
664 }
665
666
667 void CoreNetwork::restoreUserModes()
668 {
669     IrcUser *me_ = me();
670     Q_ASSERT(me_);
671
672     disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
673     disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
674
675     QString modesDelta = Core::userModes(userId(), networkId());
676     QString currentModes = me_->userModes();
677
678     QString addModes, removeModes;
679     if (modesDelta.contains('-')) {
680         addModes = modesDelta.section('-', 0, 0);
681         removeModes = modesDelta.section('-', 1);
682     }
683     else {
684         addModes = modesDelta;
685     }
686
687     addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
688     if (currentModes.isEmpty())
689         removeModes = QString();
690     else
691         removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
692
693     if (addModes.isEmpty() && removeModes.isEmpty())
694         return;
695
696     if (!addModes.isEmpty())
697         addModes = '+' + addModes;
698     if (!removeModes.isEmpty())
699         removeModes = '-' + removeModes;
700
701     // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
702     putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
703 }
704
705
706 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
707 {
708     QString addModes;
709     QString removeModes;
710     bool addMode = true;
711
712     for (int i = 0; i < requestedModes.length(); i++) {
713         if (requestedModes[i] == '+') {
714             addMode = true;
715             continue;
716         }
717         if (requestedModes[i] == '-') {
718             addMode = false;
719             continue;
720         }
721         if (addMode) {
722             addModes += requestedModes[i];
723         }
724         else {
725             removeModes += requestedModes[i];
726         }
727     }
728
729     QString addModesOld = _requestedUserModes.section('-', 0, 0);
730     QString removeModesOld = _requestedUserModes.section('-', 1);
731
732     addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
733     addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
734     addModes += addModesOld;
735
736     removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
737     removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
738     removeModes += removeModesOld;
739
740     _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
741 }
742
743
744 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
745 {
746     QString persistentUserModes = Core::userModes(userId(), networkId());
747
748     QString requestedAdd = _requestedUserModes.section('-', 0, 0);
749     QString requestedRemove = _requestedUserModes.section('-', 1);
750
751     QString persistentAdd, persistentRemove;
752     if (persistentUserModes.contains('-')) {
753         persistentAdd = persistentUserModes.section('-', 0, 0);
754         persistentRemove = persistentUserModes.section('-', 1);
755     }
756     else {
757         persistentAdd = persistentUserModes;
758     }
759
760     // remove modes we didn't issue
761     if (requestedAdd.isEmpty())
762         addModes = QString();
763     else
764         addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
765
766     if (requestedRemove.isEmpty())
767         removeModes = QString();
768     else
769         removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
770
771     // deduplicate
772     persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
773     persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
774
775     // update
776     persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
777     persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
778
779     // update issued mode list
780     requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
781     requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
782     _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
783
784     persistentAdd += addModes;
785     persistentRemove += removeModes;
786     Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
787 }
788
789
790 void CoreNetwork::resetPersistentModes()
791 {
792     _requestedUserModes = QString('-');
793     Core::setUserModes(userId(), networkId(), QString());
794 }
795
796
797 void CoreNetwork::setUseAutoReconnect(bool use)
798 {
799     Network::setUseAutoReconnect(use);
800     if (!use)
801         _autoReconnectTimer.stop();
802 }
803
804
805 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
806 {
807     Network::setAutoReconnectInterval(interval);
808     _autoReconnectTimer.setInterval(interval * 1000);
809 }
810
811
812 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
813 {
814     Network::setAutoReconnectRetries(retries);
815     if (_autoReconnectCount != 0) {
816         if (unlimitedReconnectRetries())
817             _autoReconnectCount = -1;
818         else
819             _autoReconnectCount = autoReconnectRetries();
820     }
821 }
822
823
824 void CoreNetwork::doAutoReconnect()
825 {
826     if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
827         qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
828         return;
829     }
830     if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
831         _autoReconnectCount--;  // -2 means we delay the next reconnect
832     connectToIrc(true);
833 }
834
835
836 void CoreNetwork::sendPing()
837 {
838     uint now = QDateTime::currentDateTime().toTime_t();
839     if (_pingCount != 0) {
840         qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
841                  << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
842     }
843     if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
844         // the second check compares the actual elapsed time since the last ping and the pingTimer interval
845         // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
846         // and unable to even handle a ping answer. So we ignore those misses.
847         disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
848     }
849     else {
850         _lastPingTime = now;
851         _pingCount++;
852         // Don't send pings until the network is initialized
853         if(_sendPings)
854             userInputHandler()->handlePing(BufferInfo(), QString());
855     }
856 }
857
858
859 void CoreNetwork::enablePingTimeout(bool enable)
860 {
861     if (!enable)
862         disablePingTimeout();
863     else {
864         resetPingTimeout();
865         if (networkConfig()->pingTimeoutEnabled())
866             _pingTimer.start();
867     }
868 }
869
870
871 void CoreNetwork::disablePingTimeout()
872 {
873     _pingTimer.stop();
874     _sendPings = false;
875     resetPingTimeout();
876 }
877
878
879 void CoreNetwork::setPingInterval(int interval)
880 {
881     _pingTimer.setInterval(interval * 1000);
882 }
883
884 /******** IRCv3 Capability Negotiation ********/
885
886 void CoreNetwork::serverCapAdded(const QString &capability)
887 {
888     // Check if it's a known capability; if so, add it to the list
889     // Handle special cases first
890     if (capability == IrcCap::SASL) {
891         // Only request SASL if it's enabled
892         if (networkInfo().useSasl)
893             queueCap(capability);
894     } else if (IrcCap::knownCaps.contains(capability)) {
895         // Handling for general known capabilities
896         queueCap(capability);
897     }
898 }
899
900 void CoreNetwork::serverCapAcknowledged(const QString &capability)
901 {
902     // This may be called multiple times in certain situations.
903
904     // Handle core-side configuration
905     if (capability == IrcCap::AWAY_NOTIFY) {
906         // away-notify enabled, stop the autoWho timers, handle manually
907         setAutoWhoEnabled(false);
908     }
909
910     // Handle capabilities that require further messages sent to the IRC server
911     // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
912     if (capability == IrcCap::SASL) {
913         // If SASL mechanisms specified, limit to what's accepted for authentication
914         // if the current identity has a cert set, use SASL EXTERNAL
915         // FIXME use event
916 #ifdef HAVE_SSL
917         if (!identityPtr()->sslCert().isNull()) {
918             if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::EXTERNAL)) {
919                 // EXTERNAL authentication supported, send request
920                 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
921             } else {
922                 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
923                            tr("SASL EXTERNAL authentication not supported"));
924                 sendNextCap();
925             }
926         } else {
927 #endif
928             if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::PLAIN)) {
929                 // PLAIN authentication supported, send request
930                 // Only working with PLAIN atm, blowfish later
931                 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
932             } else {
933                 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
934                            tr("SASL PLAIN authentication not supported"));
935                 sendNextCap();
936             }
937 #ifdef HAVE_SSL
938         }
939 #endif
940     }
941 }
942
943 void CoreNetwork::serverCapRemoved(const QString &capability)
944 {
945     // This may be called multiple times in certain situations.
946
947     // Handle special cases here
948     if (capability == IrcCap::AWAY_NOTIFY) {
949         // away-notify disabled, enable autoWho according to configuration
950         setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
951     }
952 }
953
954 void CoreNetwork::queueCap(const QString &capability)
955 {
956     // IRCv3 specs all use lowercase capability names
957     QString _capLowercase = capability.toLower();
958     if (!_capsQueued.contains(_capLowercase)) {
959         _capsQueued.append(_capLowercase);
960     }
961 }
962
963 QString CoreNetwork::takeQueuedCap()
964 {
965     if (!_capsQueued.empty()) {
966         return _capsQueued.takeFirst();
967     } else {
968         return QString();
969     }
970 }
971
972 void CoreNetwork::beginCapNegotiation()
973 {
974     // Don't begin negotiation if no capabilities are queued to request
975     if (!capNegotiationInProgress())
976         return;
977
978     _capNegotiationActive = true;
979     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
980                tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
981     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
982                tr("Negotiating capabilities (requesting: %1)...").arg(_capsQueued.join(", ")));
983     sendNextCap();
984 }
985
986 void CoreNetwork::sendNextCap()
987 {
988     if (capNegotiationInProgress()) {
989         // Request the next capability and remove it from the list
990         // Handle one at a time so one capability failing won't NAK all of 'em
991         putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCap())));
992     } else {
993         // No pending desired capabilities, capability negotiation finished
994         // If SASL requested but not available, print a warning
995         if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
996             displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
997                        tr("SASL authentication currently not supported by server"));
998
999         if (_capNegotiationActive) {
1000             displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1001                    tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1002             _capNegotiationActive = false;
1003         }
1004
1005         // If nick registration is already complete, CAP END is not required
1006         if (!_capInitialNegotiationEnded) {
1007             putRawLine(serverEncode(QString("CAP END")));
1008             _capInitialNegotiationEnded = true;
1009         }
1010     }
1011 }
1012
1013 /******** AutoWHO ********/
1014
1015 void CoreNetwork::startAutoWhoCycle()
1016 {
1017     if (!_autoWhoQueue.isEmpty()) {
1018         _autoWhoCycleTimer.stop();
1019         return;
1020     }
1021     _autoWhoQueue = channels();
1022 }
1023
1024 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1025 {
1026     // Prepend so these new channels/nicks are the first to be checked
1027     // Don't allow duplicates
1028     if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1029         _autoWhoQueue.prepend(channelOrNick.toLower());
1030     }
1031     if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1032         // When away-notify is active, the timer's stopped.  Start a new cycle to who this channel.
1033         setAutoWhoEnabled(true);
1034     }
1035 }
1036
1037
1038 void CoreNetwork::setAutoWhoDelay(int delay)
1039 {
1040     _autoWhoTimer.setInterval(delay * 1000);
1041 }
1042
1043
1044 void CoreNetwork::setAutoWhoInterval(int interval)
1045 {
1046     _autoWhoCycleTimer.setInterval(interval * 1000);
1047 }
1048
1049
1050 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1051 {
1052     if (enabled && isConnected() && !_autoWhoTimer.isActive())
1053         _autoWhoTimer.start();
1054     else if (!enabled) {
1055         _autoWhoTimer.stop();
1056         _autoWhoCycleTimer.stop();
1057     }
1058 }
1059
1060
1061 void CoreNetwork::sendAutoWho()
1062 {
1063     // Don't send autowho if there are still some pending
1064     if (_autoWhoPending.count())
1065         return;
1066
1067     while (!_autoWhoQueue.isEmpty()) {
1068         QString chanOrNick = _autoWhoQueue.takeFirst();
1069         // Check if it's a known channel or nick
1070         IrcChannel *ircchan = ircChannel(chanOrNick);
1071         IrcUser *ircuser = ircUser(chanOrNick);
1072         if (ircchan) {
1073             // Apply channel limiting rules
1074             // If using away-notify, don't impose channel size limits in order to capture away
1075             // state of everyone.  Auto-who won't run on a timer so network impact is minimal.
1076             if (networkConfig()->autoWhoNickLimit() > 0
1077                 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1078                 && !capEnabled(IrcCap::AWAY_NOTIFY))
1079                 continue;
1080             _autoWhoPending[chanOrNick.toLower()]++;
1081         } else if (ircuser) {
1082             // Checking a nick, add it to the pending list
1083             _autoWhoPending[ircuser->nick().toLower()]++;
1084         } else {
1085             // Not a channel or a nick, skip it
1086             qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1087             continue;
1088         }
1089         if (supports("WHOX")) {
1090             // Use WHO extended to poll away users and/or user accounts
1091             // See http://faerion.sourceforge.net/doc/irc/whox.var
1092             // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1093             putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1094                                     .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1095         } else {
1096             putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1097         }
1098         break;
1099     }
1100
1101     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1102         && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1103         // Timer was stopped, means a new cycle is due immediately
1104         // Don't run a new cycle if using away-notify; server will notify as appropriate
1105         _autoWhoCycleTimer.start();
1106         startAutoWhoCycle();
1107     } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1108         // Don't run another who cycle if away-notify is enabled
1109         _autoWhoCycleTimer.stop();
1110     }
1111 }
1112
1113
1114 #ifdef HAVE_SSL
1115 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1116 {
1117     Q_UNUSED(sslErrors)
1118     socket.ignoreSslErrors();
1119     // TODO errorhandling
1120 }
1121
1122
1123 #endif  // HAVE_SSL
1124
1125 void CoreNetwork::fillBucketAndProcessQueue()
1126 {
1127     if (_tokenBucket < _burstSize) {
1128         _tokenBucket++;
1129     }
1130
1131     while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1132         writeToSocket(_msgQueue.takeFirst());
1133     }
1134 }
1135
1136
1137 void CoreNetwork::writeToSocket(const QByteArray &data)
1138 {
1139     socket.write(data);
1140     socket.write("\r\n");
1141     _tokenBucket--;
1142 }
1143
1144
1145 Network::Server CoreNetwork::usedServer() const
1146 {
1147     if (_lastUsedServerIndex < serverList().count())
1148         return serverList()[_lastUsedServerIndex];
1149
1150     if (!serverList().isEmpty())
1151         return serverList()[0];
1152
1153     return Network::Server();
1154 }
1155
1156
1157 void CoreNetwork::requestConnect() const
1158 {
1159     if (connectionState() != Disconnected) {
1160         qWarning() << "Requesting connect while already being connected!";
1161         return;
1162     }
1163     QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1164 }
1165
1166
1167 void CoreNetwork::requestDisconnect() const
1168 {
1169     if (connectionState() == Disconnected) {
1170         qWarning() << "Requesting disconnect while not being connected!";
1171         return;
1172     }
1173     userInputHandler()->handleQuit(BufferInfo(), QString());
1174 }
1175
1176
1177 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1178 {
1179     Network::Server currentServer = usedServer();
1180     setNetworkInfo(info);
1181     Core::updateNetwork(coreSession()->user(), info);
1182
1183     // the order of the servers might have changed,
1184     // so we try to find the previously used server
1185     _lastUsedServerIndex = 0;
1186     for (int i = 0; i < serverList().count(); i++) {
1187         Network::Server server = serverList()[i];
1188         if (server.host == currentServer.host && server.port == currentServer.port) {
1189             _lastUsedServerIndex = i;
1190             break;
1191         }
1192     }
1193 }
1194
1195
1196 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1197 {
1198     QString wrkMsg(message);
1199     QList<QList<QByteArray>> msgsToSend;
1200
1201     // do while (wrkMsg.size() > 0)
1202     do {
1203         // First, check to see if the whole message can be sent at once.  The
1204         // cmdGenerator function is passed in by the caller and is used to encode
1205         // and encrypt (if applicable) the message, since different callers might
1206         // want to use different encoding or encode different values.
1207         int splitPos = wrkMsg.size();
1208         QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1209         int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1210
1211         if (initialOverrun) {
1212             // If the message was too long to be sent, first try splitting it along
1213             // word boundaries with QTextBoundaryFinder.
1214             QString splitMsg(wrkMsg);
1215             QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1216             qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1217             QList<QByteArray> splitMsgEnc;
1218             int overrun = initialOverrun;
1219
1220             while (overrun) {
1221                 splitPos = qtbf.toPreviousBoundary();
1222
1223                 // splitPos==-1 means the QTBF couldn't find a split point at all and
1224                 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1225                 // the string.  Neither one of these works for us.
1226                 if (splitPos > 0) {
1227                     // If a split point could be found, split the message there, calculate the
1228                     // overrun, and continue with the loop.
1229                     splitMsg = splitMsg.left(splitPos);
1230                     splitMsgEnc = cmdGenerator(splitMsg);
1231                     overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1232                 }
1233                 else {
1234                     // If a split point could not be found (the beginning of the message
1235                     // is reached without finding a split point short enough to send) and we
1236                     // are still in Word mode, switch to Grapheme mode.  We also need to restore
1237                     // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1238                     // the previous attempt to find a split point.
1239                     if (qtbf.type() == QTextBoundaryFinder::Word) {
1240                         splitMsg = wrkMsg;
1241                         splitPos = splitMsg.size();
1242                         QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1243                         graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1244                         qtbf = graphemeQtbf;
1245                     }
1246                     else {
1247                         // If the QTBF fails to find a split point in Grapheme mode, we give up.
1248                         // This should never happen, but it should be handled anyway.
1249                         qWarning() << "Unexpected failure to split message!";
1250                         return msgsToSend;
1251                     }
1252                 }
1253             }
1254
1255             // Once a message of sendable length has been found, remove it from the wrkMsg and
1256             // add it to the list of messages to be sent.
1257             wrkMsg.remove(0, splitPos);
1258             msgsToSend.append(splitMsgEnc);
1259         }
1260         else{
1261             // If the entire remaining message is short enough to be sent all at once, remove
1262             // it from the wrkMsg and add it to the list of messages to be sent.
1263             wrkMsg.remove(0, splitPos);
1264             msgsToSend.append(initialSplitMsgEnc);
1265         }
1266     } while (wrkMsg.size() > 0);
1267
1268     return msgsToSend;
1269 }