common: Allow skipping negotiation of IRCv3 caps
[quassel.git] / src / core / corenetwork.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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 <algorithm>
24
25 #include <QDebug>
26 #include <QHostInfo>
27 #include <QTextBoundaryFinder>
28
29 #include "core.h"
30 #include "coreidentity.h"
31 #include "corenetworkconfig.h"
32 #include "coresession.h"
33 #include "coreuserinputhandler.h"
34 #include "ircencoder.h"
35 #include "irccap.h"
36 #include "irctag.h"
37 #include "networkevent.h"
38
39 CoreNetwork::CoreNetwork(const NetworkId& networkid, CoreSession* session)
40     : Network(networkid, session)
41     , _coreSession(session)
42     , _userInputHandler(new CoreUserInputHandler(this))
43     , _metricsServer(Core::instance()->metricsServer())
44     , _autoReconnectCount(0)
45     , _quitRequested(false)
46     , _disconnectExpected(false)
47     , _previousConnectionAttemptFailed(false)
48     , _lastUsedServerIndex(0)
49     , _requestedUserModes('-')
50 {
51     // Check if raw IRC logging is enabled
52     _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
53     _debugLogRawNetId = Quassel::optionValue("debug-irc-id").toInt();
54
55     _autoReconnectTimer.setSingleShot(true);
56     connect(&_socketCloseTimer, &QTimer::timeout, this, &CoreNetwork::onSocketCloseTimeout);
57
58     setPingInterval(networkConfig()->pingInterval());
59     connect(&_pingTimer, &QTimer::timeout, this, &CoreNetwork::sendPing);
60
61     setAutoWhoDelay(networkConfig()->autoWhoDelay());
62     setAutoWhoInterval(networkConfig()->autoWhoInterval());
63
64     QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
65     for (const QString& chan : channels.keys()) {
66         _channelKeys[chan.toLower()] = channels[chan];
67     }
68
69     QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
70     for (const QString& buffer : bufferCiphers.keys()) {
71         storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
72     }
73
74     connect(networkConfig(), &NetworkConfig::pingTimeoutEnabledSet, this, &CoreNetwork::enablePingTimeout);
75     connect(networkConfig(), &NetworkConfig::pingIntervalSet, this, &CoreNetwork::setPingInterval);
76     connect(networkConfig(), &NetworkConfig::autoWhoEnabledSet, this, &CoreNetwork::setAutoWhoEnabled);
77     connect(networkConfig(), &NetworkConfig::autoWhoIntervalSet, this, &CoreNetwork::setAutoWhoInterval);
78     connect(networkConfig(), &NetworkConfig::autoWhoDelaySet, this, &CoreNetwork::setAutoWhoDelay);
79
80     connect(&_autoReconnectTimer, &QTimer::timeout, this, &CoreNetwork::doAutoReconnect);
81     connect(&_autoWhoTimer, &QTimer::timeout, this, &CoreNetwork::sendAutoWho);
82     connect(&_autoWhoCycleTimer, &QTimer::timeout, this, &CoreNetwork::startAutoWhoCycle);
83     connect(&_tokenBucketTimer, &QTimer::timeout, this, &CoreNetwork::checkTokenBucket);
84
85     connect(&socket, &QAbstractSocket::connected, this, &CoreNetwork::onSocketInitialized);
86     connect(&socket, selectOverload<QAbstractSocket::SocketError>(&QAbstractSocket::error), this, &CoreNetwork::onSocketError);
87     connect(&socket, &QAbstractSocket::stateChanged, this, &CoreNetwork::onSocketStateChanged);
88     connect(&socket, &QIODevice::readyRead, this, &CoreNetwork::onSocketHasData);
89     connect(&socket, &QSslSocket::encrypted, this, &CoreNetwork::onSocketInitialized);
90     connect(&socket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &CoreNetwork::onSslErrors);
91     connect(this, &CoreNetwork::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
92
93     // Custom rate limiting
94     // These react to the user changing settings in the client
95     connect(this, &Network::useCustomMessageRateSet, this, &CoreNetwork::updateRateLimiting);
96     connect(this, &Network::messageRateBurstSizeSet, this, &CoreNetwork::updateRateLimiting);
97     connect(this, &Network::messageRateDelaySet, this, &CoreNetwork::updateRateLimiting);
98     connect(this, &Network::unlimitedMessageRateSet, this, &CoreNetwork::updateRateLimiting);
99
100     // IRCv3 capability handling
101     // These react to CAP messages from the server
102     connect(this, &Network::capAdded, this, &CoreNetwork::serverCapAdded);
103     connect(this, &Network::capAcknowledged, this, &CoreNetwork::serverCapAcknowledged);
104     connect(this, &Network::capRemoved, this, &CoreNetwork::serverCapRemoved);
105
106     if (Quassel::isOptionSet("oidentd")) {
107         connect(this, &CoreNetwork::socketInitialized, Core::instance()->oidentdConfigGenerator(), &OidentdConfigGenerator::addSocket);
108         connect(this, &CoreNetwork::socketDisconnected, Core::instance()->oidentdConfigGenerator(), &OidentdConfigGenerator::removeSocket);
109     }
110
111     if (Quassel::isOptionSet("ident-daemon")) {
112         connect(this, &CoreNetwork::socketInitialized, Core::instance()->identServer(), &IdentServer::addSocket);
113         connect(this, &CoreNetwork::socketDisconnected, Core::instance()->identServer(), &IdentServer::removeSocket);
114     }
115 }
116
117 CoreNetwork::~CoreNetwork()
118 {
119     // Ensure we don't get any more signals from the socket while shutting down
120     disconnect(&socket, nullptr, this, nullptr);
121     if (!forceDisconnect()) {
122         qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
123             .arg(networkName())
124             .arg(networkId().toInt())
125             .arg(userId().toInt());
126     }
127 }
128
129 bool CoreNetwork::forceDisconnect(int msecs)
130 {
131     if (socket.state() == QAbstractSocket::UnconnectedState) {
132         // Socket already disconnected.
133         return true;
134     }
135     // Request a socket-level disconnect if not already happened
136     socket.disconnectFromHost();
137     if (socket.state() != QAbstractSocket::UnconnectedState) {
138         return socket.waitForDisconnected(msecs);
139     }
140     return true;
141 }
142
143 QString CoreNetwork::channelDecode(const QString& bufferName, const QByteArray& string) const
144 {
145     if (!bufferName.isEmpty()) {
146         IrcChannel* channel = ircChannel(bufferName);
147         if (channel)
148             return channel->decodeString(string);
149     }
150     return decodeString(string);
151 }
152
153 QString CoreNetwork::userDecode(const QString& userNick, const QByteArray& string) const
154 {
155     IrcUser* user = ircUser(userNick);
156     if (user)
157         return user->decodeString(string);
158     return decodeString(string);
159 }
160
161 QByteArray CoreNetwork::channelEncode(const QString& bufferName, const QString& string) const
162 {
163     if (!bufferName.isEmpty()) {
164         IrcChannel* channel = ircChannel(bufferName);
165         if (channel)
166             return channel->encodeString(string);
167     }
168     return encodeString(string);
169 }
170
171 QByteArray CoreNetwork::userEncode(const QString& userNick, const QString& string) const
172 {
173     IrcUser* user = ircUser(userNick);
174     if (user)
175         return user->encodeString(string);
176     return encodeString(string);
177 }
178
179 void CoreNetwork::connectToIrc(bool reconnecting)
180 {
181     if (_shuttingDown) {
182         return;
183     }
184
185     if (Core::instance()->identServer()) {
186         _socketId = Core::instance()->identServer()->addWaitingSocket();
187     }
188
189     if (_metricsServer) {
190         _metricsServer->addNetwork(userId());
191     }
192
193     if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
194         _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
195         if (unlimitedReconnectRetries())
196             _autoReconnectCount = -1;
197         else
198             _autoReconnectCount = autoReconnectRetries();
199     }
200     if (serverList().isEmpty()) {
201         qWarning() << "Server list empty, ignoring connect request!";
202         return;
203     }
204     CoreIdentity* identity = identityPtr();
205     if (!identity) {
206         qWarning() << "Invalid identity configures, ignoring connect request!";
207         return;
208     }
209
210     // cleaning up old quit reason
211     _quitReason.clear();
212
213     // Reset capability negotiation tracking, also handling server changes during reconnect
214     _capsQueuedIndividual.clear();
215     _capsQueuedBundled.clear();
216     clearCaps();
217     _capNegotiationActive = false;
218     _capInitialNegotiationEnded = false;
219
220     // use a random server?
221     if (useRandomServer()) {
222         _lastUsedServerIndex = qrand() % serverList().size();
223     }
224     else if (_previousConnectionAttemptFailed) {
225         // cycle to next server if previous connection attempt failed
226         _previousConnectionAttemptFailed = false;
227         showMessage(NetworkInternalMessage(
228             Message::Server,
229             BufferInfo::StatusBuffer,
230             "",
231             tr("Connection failed. Cycling to next server...")
232         ));
233         if (++_lastUsedServerIndex >= serverList().size()) {
234             _lastUsedServerIndex = 0;
235         }
236     }
237     else {
238         // Start out with the top server in the list
239         _lastUsedServerIndex = 0;
240     }
241
242     Server server = usedServer();
243     displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
244     showMessage(NetworkInternalMessage(
245         Message::Server,
246         BufferInfo::StatusBuffer,
247         "",
248         tr("Connecting to %1:%2...").arg(server.host).arg(server.port)
249     ));
250
251     if (server.useProxy) {
252         QNetworkProxy proxy((QNetworkProxy::ProxyType) server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
253         socket.setProxy(proxy);
254     }
255     else {
256         socket.setProxy(QNetworkProxy::NoProxy);
257     }
258
259     enablePingTimeout();
260
261     // Reset tracking for valid timestamps in PONG replies
262     setPongTimestampValid(false);
263
264     // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
265     // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
266     if (!server.useProxy) {
267         // Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
268         // hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
269         QHostInfo::fromName(server.host);
270     }
271     if (server.useSsl) {
272         CoreIdentity* identity = identityPtr();
273         if (identity) {
274             socket.setLocalCertificate(identity->sslCert());
275             socket.setPrivateKey(identity->sslKey());
276         }
277         socket.connectToHostEncrypted(server.host, server.port);
278     }
279     else {
280         socket.connectToHost(server.host, server.port);
281     }
282 }
283
284 void CoreNetwork::disconnectFromIrc(bool requested, const QString& reason, bool withReconnect)
285 {
286     // Disconnecting from the network, should expect a socket close or error
287     _disconnectExpected = true;
288     _quitRequested = requested;  // see socketDisconnected();
289     if (!withReconnect) {
290         _autoReconnectTimer.stop();
291         _autoReconnectCount = 0;  // prohibiting auto reconnect
292     }
293     disablePingTimeout();
294     _msgQueue.clear();
295     if (_metricsServer) {
296         _metricsServer->messageQueue(userId(), 0);
297     }
298
299     IrcUser* me_ = me();
300     if (me_) {
301         QString awayMsg;
302         if (me_->isAway())
303             awayMsg = me_->awayMessage();
304         Core::setAwayMessage(userId(), networkId(), awayMsg);
305     }
306
307     if (reason.isEmpty() && identityPtr())
308         _quitReason = identityPtr()->quitReason();
309     else
310         _quitReason = reason;
311
312     showMessage(NetworkInternalMessage(
313         Message::Server,
314         BufferInfo::StatusBuffer,
315         "",
316         tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason)
317     ));
318     if (socket.state() == QAbstractSocket::UnconnectedState) {
319         onSocketDisconnected();
320     }
321     else {
322         if (socket.state() == QAbstractSocket::ConnectedState) {
323             // If shutting down, prioritize the QUIT command
324             userInputHandler()->issueQuit(_quitReason, _shuttingDown);
325         }
326         else {
327             socket.close();
328         }
329         if (socket.state() != QAbstractSocket::UnconnectedState) {
330             // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
331             _socketCloseTimer.start(10000);
332         }
333     }
334 }
335
336 void CoreNetwork::onSocketCloseTimeout()
337 {
338     qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
339         .arg(networkName())
340         .arg(networkId().toInt())
341         .arg(userId().toInt());
342     socket.abort();
343 }
344
345 void CoreNetwork::shutdown()
346 {
347     _shuttingDown = true;
348     disconnectFromIrc(false, {}, false);
349 }
350
351 void CoreNetwork::userInput(const BufferInfo& buf, QString msg)
352 {
353     userInputHandler()->handleUserInput(buf, msg);
354 }
355
356 void CoreNetwork::putRawLine(const QByteArray& s, bool prepend)
357 {
358     if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.isEmpty())) {
359         // If there's tokens remaining, ...
360         // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
361         // Send the message now.
362         writeToSocket(s);
363     }
364     else {
365         // Otherwise, queue the message for later
366         if (prepend) {
367             // Jump to the start, skipping other messages
368             _msgQueue.prepend(s);
369         }
370         else {
371             // Add to back, waiting in order
372             _msgQueue.append(s);
373         }
374         if (_metricsServer) {
375             _metricsServer->messageQueue(userId(), _msgQueue.size());
376         }
377     }
378 }
379
380 void CoreNetwork::putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString>& tags, bool prepend)
381 {
382     putRawLine(IrcEncoder::writeMessage(tags, prefix, cmd, params), prepend);
383 }
384
385 void CoreNetwork::putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString>& tags, bool prependAll)
386 {
387     QListIterator<QList<QByteArray>> i(params);
388     while (i.hasNext()) {
389         QList<QByteArray> msg = i.next();
390         putCmd(cmd, msg, prefix, tags, prependAll);
391     }
392 }
393
394 void CoreNetwork::setChannelJoined(const QString& channel)
395 {
396     queueAutoWhoOneshot(channel);  // check this new channel first
397
398     Core::setChannelPersistent(userId(), networkId(), channel, true);
399     Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
400 }
401
402 void CoreNetwork::setChannelParted(const QString& channel)
403 {
404     removeChannelKey(channel);
405     _autoWhoQueue.removeAll(channel.toLower());
406     _autoWhoPending.remove(channel.toLower());
407
408     Core::setChannelPersistent(userId(), networkId(), channel, false);
409 }
410
411 void CoreNetwork::addChannelKey(const QString& channel, const QString& key)
412 {
413     if (key.isEmpty()) {
414         removeChannelKey(channel);
415     }
416     else {
417         _channelKeys[channel.toLower()] = key;
418     }
419 }
420
421 void CoreNetwork::removeChannelKey(const QString& channel)
422 {
423     _channelKeys.remove(channel.toLower());
424 }
425
426 #ifdef HAVE_QCA2
427 Cipher* CoreNetwork::cipher(const QString& target)
428 {
429     if (target.isEmpty())
430         return nullptr;
431
432     if (!Cipher::neededFeaturesAvailable())
433         return nullptr;
434
435     auto* channel = qobject_cast<CoreIrcChannel*>(ircChannel(target));
436     if (channel) {
437         return channel->cipher();
438     }
439     auto* user = qobject_cast<CoreIrcUser*>(ircUser(target));
440     if (user) {
441         return user->cipher();
442     }
443     else if (!isChannelName(target)) {
444         return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
445     }
446     return nullptr;
447 }
448
449 QByteArray CoreNetwork::cipherKey(const QString& target) const
450 {
451     auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
452     if (c)
453         return c->cipher()->key();
454
455     auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
456     if (u)
457         return u->cipher()->key();
458
459     return QByteArray();
460 }
461
462 void CoreNetwork::setCipherKey(const QString& target, const QByteArray& key)
463 {
464     auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
465     if (c) {
466         c->setEncrypted(c->cipher()->setKey(key));
467         coreSession()->setBufferCipher(networkId(), target, key);
468         return;
469     }
470
471     auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
472     if (!u && !isChannelName(target))
473         u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
474
475     if (u) {
476         u->setEncrypted(u->cipher()->setKey(key));
477         coreSession()->setBufferCipher(networkId(), target, key);
478         return;
479     }
480 }
481
482 bool CoreNetwork::cipherUsesCBC(const QString& target)
483 {
484     auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
485     if (c)
486         return c->cipher()->usesCBC();
487     auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
488     if (u)
489         return u->cipher()->usesCBC();
490
491     return false;
492 }
493 #endif /* HAVE_QCA2 */
494
495 bool CoreNetwork::setAutoWhoDone(const QString& name)
496 {
497     QString chanOrNick = name.toLower();
498     if (_autoWhoPending.value(chanOrNick, 0) <= 0)
499         return false;
500     if (--_autoWhoPending[chanOrNick] <= 0)
501         _autoWhoPending.remove(chanOrNick);
502     return true;
503 }
504
505 void CoreNetwork::setMyNick(const QString& mynick)
506 {
507     Network::setMyNick(mynick);
508     if (connectionState() == Network::Initializing)
509         networkInitialized();
510 }
511
512 void CoreNetwork::onSocketHasData()
513 {
514     while (socket.canReadLine()) {
515         QByteArray s = socket.readLine();
516         if (_metricsServer) {
517             _metricsServer->receiveDataNetwork(userId(), s.size());
518         }
519         if (s.endsWith("\r\n"))
520             s.chop(2);
521         else if (s.endsWith("\n"))
522             s.chop(1);
523         NetworkDataEvent* event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
524         event->setTimestamp(QDateTime::currentDateTimeUtc());
525         emit newEvent(event);
526     }
527 }
528
529 void CoreNetwork::onSocketError(QAbstractSocket::SocketError error)
530 {
531     // Ignore socket closed errors if expected
532     if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
533         return;
534     }
535
536     _previousConnectionAttemptFailed = true;
537     qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
538     emit connectionError(socket.errorString());
539     showMessage(NetworkInternalMessage(
540         Message::Error,
541         BufferInfo::StatusBuffer,
542         "",
543         tr("Connection failure: %1").arg(socket.errorString())
544     ));
545     emitConnectionError(socket.errorString());
546     if (socket.state() < QAbstractSocket::ConnectedState) {
547         onSocketDisconnected();
548     }
549 }
550
551 void CoreNetwork::onSocketInitialized()
552 {
553     CoreIdentity* identity = identityPtr();
554     if (!identity) {
555         qCritical() << "Identity invalid!";
556         disconnectFromIrc();
557         return;
558     }
559
560     Server server = usedServer();
561
562     // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
563     // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
564     if (!server.useSsl || !socket.isEncrypted()) {
565         emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
566     }
567
568     if (server.useSsl && !socket.isEncrypted()) {
569         // We'll finish setup once we're encrypted, and called again
570         return;
571     }
572
573     socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
574
575     // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
576     // capability negotiation.  networkInitialized() will call updateRateLimiting() without the
577     // force flag to apply user preferences.  When making changes, ensure that this still happens!
578     // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
579     // server receive queue and cause a kill.  "Shouldn't" being the operative word; the real world
580     // is a scary place.
581     updateRateLimiting(true);
582     // Fill up the token bucket as we're connecting from scratch
583     resetTokenBucket();
584
585     // Request capabilities as per IRCv3.2 specifications
586     // Older servers should ignore this; newer servers won't downgrade to RFC1459
587     showMessage(NetworkInternalMessage(
588         Message::Server,
589         BufferInfo::StatusBuffer,
590         "",
591         tr("Requesting capability list...")
592     ));
593     putRawLine(serverEncode(QString("CAP LS 302")));
594
595     if (!server.password.isEmpty()) {
596         putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
597     }
598     QString nick;
599     if (identity->nicks().isEmpty()) {
600         nick = "quassel";
601         qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
602     }
603     else {
604         nick = identity->nicks()[0];
605     }
606     putRawLine(serverEncode(QString("NICK %1").arg(nick)));
607     // Only allow strict-compliant idents when strict mode is enabled
608     putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(coreSession()->strictCompliantIdent(identity), identity->realName())));
609 }
610
611 void CoreNetwork::onSocketDisconnected()
612 {
613     disablePingTimeout();
614     _msgQueue.clear();
615     if (_metricsServer) {
616         _metricsServer->messageQueue(userId(), 0);
617     }
618
619     _autoWhoCycleTimer.stop();
620     _autoWhoTimer.stop();
621     _autoWhoQueue.clear();
622     _autoWhoPending.clear();
623
624     _socketCloseTimer.stop();
625
626     _tokenBucketTimer.stop();
627
628     IrcUser* me_ = me();
629     if (me_) {
630         for (const QString& channel : me_->channels()) {
631             showMessage(NetworkInternalMessage(
632                 Message::Quit,
633                 BufferInfo::ChannelBuffer,
634                 channel,
635                 _quitReason, me_->hostmask()
636             ));
637         }
638     }
639
640     setConnected(false);
641     emit disconnected(networkId());
642     emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
643     // Reset disconnect expectations
644     _disconnectExpected = false;
645     if (_quitRequested) {
646         _quitRequested = false;
647         setConnectionState(Network::Disconnected);
648         Core::setNetworkConnected(userId(), networkId(), false);
649     }
650     else if (_autoReconnectCount != 0) {
651         setConnectionState(Network::Reconnecting);
652         if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
653             doAutoReconnect();  // first try is immediate
654         else
655             _autoReconnectTimer.start();
656     }
657
658     if (_metricsServer) {
659         _metricsServer->removeNetwork(userId());
660     }
661 }
662
663 void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState)
664 {
665     Network::ConnectionState state;
666     switch (socketState) {
667     case QAbstractSocket::UnconnectedState:
668         state = Network::Disconnected;
669         onSocketDisconnected();
670         break;
671     case QAbstractSocket::HostLookupState:
672     case QAbstractSocket::ConnectingState:
673         state = Network::Connecting;
674         break;
675     case QAbstractSocket::ConnectedState:
676         state = Network::Initializing;
677         break;
678     case QAbstractSocket::ClosingState:
679         state = Network::Disconnecting;
680         break;
681     default:
682         state = Network::Disconnected;
683     }
684     setConnectionState(state);
685 }
686
687 void CoreNetwork::networkInitialized()
688 {
689     setConnectionState(Network::Initialized);
690     setConnected(true);
691     _disconnectExpected = false;
692     _quitRequested = false;
693
694     // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
695     // flag used for initial registration and capability negotiation.
696     updateRateLimiting();
697
698     if (useAutoReconnect()) {
699         // reset counter
700         _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
701     }
702
703     // restore away state
704     QString awayMsg = Core::awayMessage(userId(), networkId());
705     if (!awayMsg.isEmpty()) {
706         // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
707         // '%%%%%%%%' -> '%%%%'  If processed again, it'd result in '%%'.
708         userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
709     }
710
711     sendPerform();
712
713     _sendPings = true;
714
715     if (networkConfig()->autoWhoEnabled()) {
716         _autoWhoCycleTimer.start();
717         _autoWhoTimer.start();
718         startAutoWhoCycle();  // FIXME wait for autojoin to be completed
719     }
720
721     Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer);  // create status buffer
722     Core::setNetworkConnected(userId(), networkId(), true);
723 }
724
725 void CoreNetwork::sendPerform()
726 {
727     BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
728
729     // do auto identify
730     if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
731         userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
732     }
733
734     // restore old user modes if server default mode is set.
735     IrcUser* me_ = me();
736     if (me_) {
737         if (!me_->userModes().isEmpty()) {
738             restoreUserModes();
739         }
740         else {
741             connect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
742             connect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
743         }
744     }
745
746     // send perform list
747     for (const QString& line : perform()) {
748         if (!line.isEmpty())
749             userInput(statusBuf, line);
750     }
751
752     // rejoin channels we've been in
753     if (rejoinChannels()) {
754         QStringList channels, keys;
755         for (const QString& chan : coreSession()->persistentChannels(networkId()).keys()) {
756             QString key = channelKey(chan);
757             if (!key.isEmpty()) {
758                 channels.prepend(chan);
759                 keys.prepend(key);
760             }
761             else {
762                 channels.append(chan);
763             }
764         }
765         QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
766         if (!joinString.isEmpty())
767             userInputHandler()->handleJoin(statusBuf, joinString);
768     }
769 }
770
771 void CoreNetwork::restoreUserModes()
772 {
773     IrcUser* me_ = me();
774     Q_ASSERT(me_);
775
776     disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
777     disconnect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
778
779     QString modesDelta = Core::userModes(userId(), networkId());
780     QString currentModes = me_->userModes();
781
782     QString addModes, removeModes;
783     if (modesDelta.contains('-')) {
784         addModes = modesDelta.section('-', 0, 0);
785         removeModes = modesDelta.section('-', 1);
786     }
787     else {
788         addModes = modesDelta;
789     }
790
791     addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
792     if (currentModes.isEmpty())
793         removeModes = QString();
794     else
795         removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
796
797     if (addModes.isEmpty() && removeModes.isEmpty())
798         return;
799
800     if (!addModes.isEmpty())
801         addModes = '+' + addModes;
802     if (!removeModes.isEmpty())
803         removeModes = '-' + removeModes;
804
805     // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
806     putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
807 }
808
809 void CoreNetwork::updateIssuedModes(const QString& requestedModes)
810 {
811     QString addModes;
812     QString removeModes;
813     bool addMode = true;
814
815     for (auto requestedMode : requestedModes) {
816         if (requestedMode == '+') {
817             addMode = true;
818             continue;
819         }
820         if (requestedMode == '-') {
821             addMode = false;
822             continue;
823         }
824         if (addMode) {
825             addModes += requestedMode;
826         }
827         else {
828             removeModes += requestedMode;
829         }
830     }
831
832     QString addModesOld = _requestedUserModes.section('-', 0, 0);
833     QString removeModesOld = _requestedUserModes.section('-', 1);
834
835     addModes.remove(QRegExp(QString("[%1]").arg(addModesOld)));     // deduplicate
836     addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes)));  // update
837     addModes += addModesOld;
838
839     removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld)));  // deduplicate
840     removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes)));     // update
841     removeModes += removeModesOld;
842
843     _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
844 }
845
846 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
847 {
848     QString persistentUserModes = Core::userModes(userId(), networkId());
849
850     QString requestedAdd = _requestedUserModes.section('-', 0, 0);
851     QString requestedRemove = _requestedUserModes.section('-', 1);
852
853     QString persistentAdd, persistentRemove;
854     if (persistentUserModes.contains('-')) {
855         persistentAdd = persistentUserModes.section('-', 0, 0);
856         persistentRemove = persistentUserModes.section('-', 1);
857     }
858     else {
859         persistentAdd = persistentUserModes;
860     }
861
862     // remove modes we didn't issue
863     if (requestedAdd.isEmpty())
864         addModes = QString();
865     else
866         addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
867
868     if (requestedRemove.isEmpty())
869         removeModes = QString();
870     else
871         removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
872
873     // deduplicate
874     persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
875     persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
876
877     // update
878     persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
879     persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
880
881     // update issued mode list
882     requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
883     requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
884     _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
885
886     persistentAdd += addModes;
887     persistentRemove += removeModes;
888     Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
889 }
890
891 void CoreNetwork::resetPersistentModes()
892 {
893     _requestedUserModes = QString('-');
894     Core::setUserModes(userId(), networkId(), QString());
895 }
896
897 void CoreNetwork::setUseAutoReconnect(bool use)
898 {
899     Network::setUseAutoReconnect(use);
900     if (!use)
901         _autoReconnectTimer.stop();
902 }
903
904 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
905 {
906     Network::setAutoReconnectInterval(interval);
907     _autoReconnectTimer.setInterval(interval * 1000);
908 }
909
910 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
911 {
912     Network::setAutoReconnectRetries(retries);
913     if (_autoReconnectCount != 0) {
914         if (unlimitedReconnectRetries())
915             _autoReconnectCount = -1;
916         else
917             _autoReconnectCount = autoReconnectRetries();
918     }
919 }
920
921 void CoreNetwork::doAutoReconnect()
922 {
923     if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
924         qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
925         return;
926     }
927     if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
928         _autoReconnectCount--;  // -2 means we delay the next reconnect
929     connectToIrc(true);
930 }
931
932 void CoreNetwork::sendPing()
933 {
934     qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
935     if (_pingCount != 0) {
936         qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
937                  << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
938     }
939     if ((int) _pingCount >= networkConfig()->maxPingCount() && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
940         // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
941         // However, to reduce the risk of breaking things by changing past behavior, we still allow
942         // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
943         //
944         // the second check compares the actual elapsed time since the last ping and the pingTimer interval
945         // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
946         // and unable to even handle a ping answer. So we ignore those misses.
947         disconnectFromIrc(false,
948                           QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000),
949                           true /* withReconnect */);
950     }
951     else {
952         _lastPingTime = now;
953         _pingCount++;
954         // Don't send pings until the network is initialized
955         if (_sendPings) {
956             // Mark as waiting for a reply
957             _pongReplyPending = true;
958             // Send default timestamp ping
959             userInputHandler()->handlePing(BufferInfo(), QString());
960         }
961     }
962 }
963
964 void CoreNetwork::enablePingTimeout(bool enable)
965 {
966     if (!enable)
967         disablePingTimeout();
968     else {
969         resetPingTimeout();
970         resetPongReplyPending();
971         if (networkConfig()->pingTimeoutEnabled())
972             _pingTimer.start();
973     }
974 }
975
976 void CoreNetwork::disablePingTimeout()
977 {
978     _pingTimer.stop();
979     _sendPings = false;
980     resetPingTimeout();
981     resetPongReplyPending();
982 }
983
984 void CoreNetwork::setPingInterval(int interval)
985 {
986     _pingTimer.setInterval(interval * 1000);
987 }
988
989 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
990 {
991     _pongTimestampValid = validTimestamp;
992 }
993
994 /******** Custom Rate Limiting ********/
995
996 void CoreNetwork::updateRateLimiting(bool forceUnlimited)
997 {
998     // Verify and apply custom rate limiting options, always resetting the delay and burst size
999     // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
1000     // this may be called while connected to a server.
1001
1002     if (useCustomMessageRate() || forceUnlimited) {
1003         // Custom message rates enabled, or chosen by means of forcing unlimited.  Let's go for it!
1004
1005         _messageDelay = messageRateDelay();
1006
1007         _burstSize = messageRateBurstSize();
1008         if (_burstSize < 1) {
1009             qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" << _burstSize;
1010             // Can't go slower than one message at a time
1011             _burstSize = 1;
1012         }
1013
1014         if (_tokenBucket > _burstSize) {
1015             // Don't let the token bucket exceed the maximum
1016             _tokenBucket = _burstSize;
1017             // To fill up the token bucket, use resetRateLimiting().  Don't do that here, otherwise
1018             // changing the rate-limit settings while connected to a server will incorrectly reset
1019             // the token bucket.
1020         }
1021
1022         // Toggle the timer according to whether or not rate limiting is enabled
1023         // If we're here, either useCustomMessageRate or forceUnlimited is true.  Thus, the logic is
1024         // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1025         // Override user preferences if called with force unlimited, only used during connect.
1026         _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1027         if (_skipMessageRates) {
1028             // If the message queue already contains messages, they need sent before disabling the
1029             // timer.  Set the timer to a rapid pace and let it disable itself.
1030             if (!_msgQueue.isEmpty()) {
1031                 qDebug() << "Outgoing message queue contains messages while disabling rate "
1032                             "limiting.  Sending remaining queued messages...";
1033                 // Promptly run the timer again to clear the messages.  Rate limiting is disabled,
1034                 // so nothing should cause this to block.. in theory.  However, don't directly call
1035                 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1036                 //
1037                 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1038                 // Hesitant to change it without a wide variety of situations to verify behavior.
1039                 _tokenBucketTimer.start(100);
1040             }
1041             else {
1042                 // No rate limiting, disable the timer
1043                 _tokenBucketTimer.stop();
1044             }
1045         }
1046         else {
1047             // Rate limiting enabled, enable the timer
1048             _tokenBucketTimer.start(_messageDelay);
1049         }
1050     }
1051     else {
1052         // Custom message rates disabled.  Go for the default.
1053
1054         _skipMessageRates = false;  // Enable rate-limiting by default
1055         _messageDelay = 2200;       // This seems to be a safe value (2.2 seconds delay)
1056         _burstSize = 5;             // 5 messages at once
1057         if (_tokenBucket > _burstSize) {
1058             // TokenBucket to avoid sending too much at once.  Don't let the token bucket exceed the
1059             // maximum.
1060             _tokenBucket = _burstSize;
1061             // To fill up the token bucket, use resetRateLimiting().  Don't do that here, otherwise
1062             // changing the rate-limit settings while connected to a server will incorrectly reset
1063             // the token bucket.
1064         }
1065         // Rate limiting enabled, enable the timer
1066         _tokenBucketTimer.start(_messageDelay);
1067     }
1068 }
1069
1070 void CoreNetwork::resetTokenBucket()
1071 {
1072     // Fill up the token bucket to the maximum
1073     _tokenBucket = _burstSize;
1074 }
1075
1076 /******** IRCv3 Capability Negotiation ********/
1077
1078 void CoreNetwork::serverCapAdded(const QString& capability)
1079 {
1080     // Exclude skipped capabilities
1081     if (skipCaps().contains(capability)) {
1082         return;
1083     }
1084
1085     // Check if it's a known capability; if so, add it to the list
1086     // Handle special cases first
1087     if (capability == IrcCap::SASL) {
1088         // Only request SASL if it's enabled
1089         if (networkInfo().useSasl)
1090             queueCap(capability);
1091     }
1092     else if (IrcCap::knownCaps.contains(capability)) {
1093         // Handling for general known capabilities
1094         queueCap(capability);
1095     }
1096 }
1097
1098 void CoreNetwork::serverCapAcknowledged(const QString& capability)
1099 {
1100     // This may be called multiple times in certain situations.
1101
1102     // Handle core-side configuration
1103     if (capability == IrcCap::AWAY_NOTIFY) {
1104         // away-notify enabled, stop the autoWho timers, handle manually
1105         setAutoWhoEnabled(false);
1106     }
1107
1108     // Handle capabilities that require further messages sent to the IRC server
1109     // If you change this list, ALSO change the list in CoreNetwork::capsRequiringConfiguration
1110     if (capability == IrcCap::SASL) {
1111         // If SASL mechanisms specified, limit to what's accepted for authentication
1112         // if the current identity has a cert set, use SASL EXTERNAL
1113         // FIXME use event
1114         if (!identityPtr()->sslCert().isNull()) {
1115             if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1116                 // EXTERNAL authentication supported, send request
1117                 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1118             }
1119             else {
1120                 showMessage(NetworkInternalMessage(
1121                     Message::Error,
1122                     BufferInfo::StatusBuffer,
1123                     "",
1124                     tr("SASL EXTERNAL authentication not supported")
1125                 ));
1126                 sendNextCap();
1127             }
1128         }
1129         else {
1130             if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1131                 // PLAIN authentication supported, send request
1132                 // Only working with PLAIN atm, blowfish later
1133                 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1134             }
1135             else {
1136                 showMessage(NetworkInternalMessage(
1137                     Message::Error,
1138                     BufferInfo::StatusBuffer,
1139                     "",
1140                     tr("SASL PLAIN authentication not supported")
1141                 ));
1142                 sendNextCap();
1143             }
1144         }
1145     }
1146 }
1147
1148 void CoreNetwork::serverCapRemoved(const QString& capability)
1149 {
1150     // This may be called multiple times in certain situations.
1151
1152     // Handle special cases here
1153     if (capability == IrcCap::AWAY_NOTIFY) {
1154         // away-notify disabled, enable autoWho according to configuration
1155         setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1156     }
1157 }
1158
1159 void CoreNetwork::queueCap(const QString& capability)
1160 {
1161     // IRCv3 specs all use lowercase capability names
1162     QString _capLowercase = capability.toLower();
1163
1164     if (capsRequiringConfiguration.contains(_capLowercase)) {
1165         // The capability requires additional configuration before being acknowledged (e.g. SASL),
1166         // so we should negotiate it separately from all other capabilities.  Otherwise new
1167         // capabilities will be requested while still configuring the previous one.
1168         if (!_capsQueuedIndividual.contains(_capLowercase)) {
1169             _capsQueuedIndividual.append(_capLowercase);
1170         }
1171     }
1172     else {
1173         // The capability doesn't need any special configuration, so it should be safe to try
1174         // bundling together with others.  "Should" being the imperative word, as IRC servers can do
1175         // anything.
1176         if (!_capsQueuedBundled.contains(_capLowercase)) {
1177             _capsQueuedBundled.append(_capLowercase);
1178         }
1179     }
1180 }
1181
1182 QString CoreNetwork::takeQueuedCaps()
1183 {
1184     // Clear the record of the most recently negotiated capability bundle.  Does nothing if the list
1185     // is empty.
1186     _capsQueuedLastBundle.clear();
1187
1188     // First, negotiate all the standalone capabilities that require additional configuration.
1189     if (!_capsQueuedIndividual.empty()) {
1190         // We have an individual capability available.  Take the first and pass it back.
1191         return _capsQueuedIndividual.takeFirst();
1192     }
1193     else if (!_capsQueuedBundled.empty()) {
1194         // We have capabilities available that can be grouped.  Try to fit in as many as within the
1195         // maximum length.
1196         // See CoreNetwork::maxCapRequestLength
1197
1198         // Response must have at least one capability regardless of max length for anything to
1199         // happen.
1200         QString capBundle = _capsQueuedBundled.takeFirst();
1201         QString nextCap("");
1202         while (!_capsQueuedBundled.empty()) {
1203             // As long as capabilities remain, get the next...
1204             nextCap = _capsQueuedBundled.first();
1205             if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1206                 // [capability + 1 for a space + this new capability] fit within length limits
1207                 // Add it to formatted list
1208                 capBundle.append(" " + nextCap);
1209                 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1210                 _capsQueuedLastBundle.append(nextCap);
1211                 // Then remove it from the queue
1212                 _capsQueuedBundled.removeFirst();
1213             }
1214             else {
1215                 // We've reached the length limit for a single capability request, stop adding more
1216                 break;
1217             }
1218         }
1219         // Return this space-separated set of capabilities, removing any extra spaces
1220         return capBundle.trimmed();
1221     }
1222     else {
1223         // No capabilities left to negotiate, return an empty string.
1224         return QString();
1225     }
1226 }
1227
1228 void CoreNetwork::retryCapsIndividually()
1229 {
1230     // The most recent set of capabilities got denied by the IRC server.  As we don't know what got
1231     // denied, try each capability individually.
1232     if (_capsQueuedLastBundle.empty()) {
1233         // No most recently tried capability set, just return.
1234         return;
1235         // Note: there's little point in retrying individually requested caps during negotiation.
1236         // We know the individual capability was the one that failed, and it's not likely it'll
1237         // suddenly start working within a few seconds.  'cap-notify' provides a better system for
1238         // handling capability removal and addition.
1239     }
1240
1241     // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1242     // over efficiency.  If this becomes an issue, implement a binary splicing system instead,
1243     // keeping track of which halves of the group fail, dividing the set each time.
1244
1245     // Add most recently tried capability set to individual list, re-requesting them one at a time
1246     _capsQueuedIndividual.append(_capsQueuedLastBundle);
1247     // Warn of this issue to explain the slower login.  Servers usually shouldn't trigger this.
1248     showMessage(NetworkInternalMessage(
1249         Message::Server,
1250         BufferInfo::StatusBuffer,
1251         "",
1252         tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", "))
1253     ));
1254     // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1255     // need to remove them here.
1256     // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1257     // indefinitely.
1258     _capsQueuedLastBundle.clear();
1259 }
1260
1261 void CoreNetwork::beginCapNegotiation()
1262 {
1263     // Check if any available capabilities have been disabled
1264     QStringList capsSkipped;
1265     if (!skipCaps().isEmpty() && !caps().isEmpty()) {
1266         // Find the entries that are common to skipCaps() and caps().  This represents any
1267         // capabilities supported by the server that were skipped.
1268
1269         // Both skipCaps() and caps() are already lowercase
1270         // std::set_intersection requires sorted lists, and we can't modify the original lists.
1271         //
1272         // skipCaps() should already be sorted.  caps() is intentionally not sorted elsewhere so
1273         // Quassel can show the capabilities in the order transmitted by the network.
1274         auto sortedCaps = caps();
1275         sortedCaps.sort();
1276
1277         // Find the intersection between skipped caps and server-supplied caps
1278         std::set_intersection(skipCaps().cbegin(), skipCaps().cend(),
1279                               sortedCaps.cbegin(), sortedCaps.cend(),
1280                               std::back_inserter(capsSkipped));
1281     }
1282
1283     if (!capsPendingNegotiation()) {
1284         // No capabilities are queued for request, determine the reason why
1285         QString capStatusMsg;
1286         if (caps().empty()) {
1287             // The server doesn't provide any capabilities, but supports CAP LS
1288             capStatusMsg = tr("No capabilities available");
1289         }
1290         else if (capsEnabled().empty()) {
1291             // The server supports capabilities (caps() is not empty) but Quassel doesn't support
1292             // anything offered.  This should be uncommon.
1293             capStatusMsg =
1294                     tr("None of the capabilities provided by the server are supported (found: %1)")
1295                     .arg(caps().join(", "));
1296         }
1297         else {
1298             // Quassel has enabled some capabilities, but there are no further capabilities that can
1299             // be negotiated.
1300             // (E.g. the user has manually run "/cap ls 302" after initial negotiation.)
1301             capStatusMsg =
1302                     tr("No additional capabilities are supported (found: %1; currently enabled: %2)")
1303                     .arg(caps().join(", "), capsEnabled().join(", "));
1304         }
1305         // Inform the user of the situation
1306         showMessage(NetworkInternalMessage(
1307             Message::Server,
1308             BufferInfo::StatusBuffer,
1309             "",
1310             capStatusMsg
1311         ));
1312
1313         if (!capsSkipped.isEmpty()) {
1314             // Mention that some capabilities are skipped
1315             showMessage(NetworkInternalMessage(
1316                 Message::Server,
1317                 BufferInfo::StatusBuffer,
1318                 "",
1319                 tr("Quassel is configured to ignore some capabilities (skipped: %1)").arg(capsSkipped.join(", "))
1320             ));
1321         }
1322
1323         // End any ongoing capability negotiation, allowing connection to continue
1324         endCapNegotiation();
1325         return;
1326     }
1327
1328     _capNegotiationActive = true;
1329     showMessage(NetworkInternalMessage(
1330         Message::Server,
1331         BufferInfo::StatusBuffer,
1332         "",
1333         tr("Ready to negotiate (found: %1)").arg(caps().join(", "))
1334     ));
1335
1336     if (!capsSkipped.isEmpty()) {
1337         // Mention that some capabilities are skipped
1338         showMessage(NetworkInternalMessage(
1339             Message::Server,
1340             BufferInfo::StatusBuffer,
1341             "",
1342             tr("Quassel is configured to ignore some capabilities (skipped: %1)").arg(capsSkipped.join(", "))
1343         ));
1344     }
1345
1346     // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1347     // comma separator between the two if needed (both individual and bundled caps exist).
1348     QString queuedCapsDisplay = _capsQueuedIndividual.join(", ")
1349                                 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1350                                 + _capsQueuedBundled.join(", ");
1351     showMessage(NetworkInternalMessage(
1352         Message::Server,
1353         BufferInfo::StatusBuffer,
1354         "",
1355         tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay)
1356     ));
1357
1358     sendNextCap();
1359 }
1360
1361 void CoreNetwork::sendNextCap()
1362 {
1363     if (capsPendingNegotiation()) {
1364         // Request the next set of capabilities and remove them from the list
1365         putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1366     }
1367     else {
1368         // No pending desired capabilities, capability negotiation finished
1369         // If SASL requested but not available, print a warning
1370         if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1371             showMessage(NetworkInternalMessage(
1372                 Message::Error,
1373                 BufferInfo::StatusBuffer,
1374                 "",
1375                 tr("SASL authentication currently not supported by server")
1376             ));
1377
1378         if (_capNegotiationActive) {
1379             showMessage(NetworkInternalMessage(
1380                 Message::Server,
1381                 BufferInfo::StatusBuffer,
1382                 "",
1383                 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", "))
1384             ));
1385             _capNegotiationActive = false;
1386         }
1387
1388         endCapNegotiation();
1389     }
1390 }
1391
1392 void CoreNetwork::endCapNegotiation()
1393 {
1394     // If nick registration is already complete, CAP END is not required
1395     if (!_capInitialNegotiationEnded) {
1396         putRawLine(serverEncode(QString("CAP END")));
1397         _capInitialNegotiationEnded = true;
1398     }
1399 }
1400
1401 /******** AutoWHO ********/
1402
1403 void CoreNetwork::startAutoWhoCycle()
1404 {
1405     if (!_autoWhoQueue.isEmpty()) {
1406         _autoWhoCycleTimer.stop();
1407         return;
1408     }
1409     _autoWhoQueue = channels();
1410 }
1411
1412 void CoreNetwork::queueAutoWhoOneshot(const QString& name)
1413 {
1414     // Prepend so these new channels/nicks are the first to be checked
1415     // Don't allow duplicates
1416     if (!_autoWhoQueue.contains(name.toLower())) {
1417         _autoWhoQueue.prepend(name.toLower());
1418     }
1419     if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1420         // When away-notify is active, the timer's stopped.  Start a new cycle to who this channel.
1421         setAutoWhoEnabled(true);
1422     }
1423 }
1424
1425 void CoreNetwork::setAutoWhoDelay(int delay)
1426 {
1427     _autoWhoTimer.setInterval(delay * 1000);
1428 }
1429
1430 void CoreNetwork::setAutoWhoInterval(int interval)
1431 {
1432     _autoWhoCycleTimer.setInterval(interval * 1000);
1433 }
1434
1435 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1436 {
1437     if (enabled && isConnected() && !_autoWhoTimer.isActive())
1438         _autoWhoTimer.start();
1439     else if (!enabled) {
1440         _autoWhoTimer.stop();
1441         _autoWhoCycleTimer.stop();
1442     }
1443 }
1444
1445 void CoreNetwork::sendAutoWho()
1446 {
1447     // Don't send autowho if there are still some pending
1448     if (_autoWhoPending.count())
1449         return;
1450
1451     while (!_autoWhoQueue.isEmpty()) {
1452         QString chanOrNick = _autoWhoQueue.takeFirst();
1453         // Check if it's a known channel or nick
1454         IrcChannel* ircchan = ircChannel(chanOrNick);
1455         IrcUser* ircuser = ircUser(chanOrNick);
1456         if (ircchan) {
1457             // Apply channel limiting rules
1458             // If using away-notify, don't impose channel size limits in order to capture away
1459             // state of everyone.  Auto-who won't run on a timer so network impact is minimal.
1460             if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1461                 && !capEnabled(IrcCap::AWAY_NOTIFY))
1462                 continue;
1463             _autoWhoPending[chanOrNick.toLower()]++;
1464         }
1465         else if (ircuser) {
1466             // Checking a nick, add it to the pending list
1467             _autoWhoPending[ircuser->nick().toLower()]++;
1468         }
1469         else {
1470             // Not a channel or a nick, skip it
1471             qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1472             continue;
1473         }
1474         if (supports("WHOX")) {
1475             // Use WHO extended to poll away users and/or user accounts
1476             // Explicitly only match on nickname ("n"), don't rely on server defaults
1477             //
1478             // WHO <nickname> n%chtsunfra,<unique_number>
1479             //
1480             // See http://faerion.sourceforge.net/doc/irc/whox.var
1481             // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1482             // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1483             putRawLine(serverEncode(
1484                 QString("WHO %1 n%chtsunfra,%2")
1485                     .arg(chanOrNick, QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))
1486             ));
1487         }
1488         else {
1489             // Fall back to normal WHO
1490             //
1491             // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1492             // hostmask, etc.  There's nothing we can do about that :(
1493             //
1494             // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1495             putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1496         }
1497         break;
1498     }
1499
1500     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1501         // Timer was stopped, means a new cycle is due immediately
1502         // Don't run a new cycle if using away-notify; server will notify as appropriate
1503         _autoWhoCycleTimer.start();
1504         startAutoWhoCycle();
1505     }
1506     else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1507         // Don't run another who cycle if away-notify is enabled
1508         _autoWhoCycleTimer.stop();
1509     }
1510 }
1511
1512 void CoreNetwork::onSslErrors(const QList<QSslError>& sslErrors)
1513 {
1514     Server server = usedServer();
1515     if (server.sslVerify) {
1516         // Treat the SSL error as a hard error
1517         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1518                                      "since verification is required");
1519         if (!sslErrors.empty()) {
1520             // Add the error reason if known
1521             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1522         }
1523         showMessage(NetworkInternalMessage(
1524             Message::Error,
1525             BufferInfo::StatusBuffer,
1526             "",
1527             sslErrorMessage
1528         ));
1529
1530         // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1531         // validity, network trouble, etc.
1532         disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1533     }
1534     else {
1535         // Treat the SSL error as a warning, continue to connect anyways
1536         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1537                                      "since verification is not required");
1538         if (!sslErrors.empty()) {
1539             // Add the error reason if known
1540             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1541         }
1542         showMessage(NetworkInternalMessage(
1543             Message::Info,
1544             BufferInfo::StatusBuffer,
1545             "",
1546             sslErrorMessage
1547         ));
1548
1549         // Proceed with the connection
1550         socket.ignoreSslErrors();
1551     }
1552 }
1553
1554 void CoreNetwork::checkTokenBucket()
1555 {
1556     if (_skipMessageRates) {
1557         if (_msgQueue.empty()) {
1558             // Message queue emptied; stop the timer and bail out
1559             _tokenBucketTimer.stop();
1560             return;
1561         }
1562         // Otherwise, we're emptying the queue, continue on as normal
1563     }
1564
1565     // Process whatever messages are pending
1566     fillBucketAndProcessQueue();
1567 }
1568
1569 void CoreNetwork::fillBucketAndProcessQueue()
1570 {
1571     // If there's less tokens than burst size, refill the token bucket by 1
1572     if (_tokenBucket < _burstSize) {
1573         _tokenBucket++;
1574     }
1575
1576     // As long as there's tokens available and messages remaining, sending messages from the queue
1577     while (!_msgQueue.empty() && _tokenBucket > 0) {
1578         writeToSocket(_msgQueue.takeFirst());
1579         if (_metricsServer) {
1580             _metricsServer->messageQueue(userId(), _msgQueue.size());
1581         }
1582     }
1583 }
1584
1585 void CoreNetwork::writeToSocket(const QByteArray& data)
1586 {
1587     // Log the message if enabled and network ID matches or allows all
1588     if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1589         // Include network ID
1590         qDebug() << "IRC net" << networkId() << ">>" << data;
1591     }
1592     socket.write(data);
1593     socket.write("\r\n");
1594     if (_metricsServer) {
1595         _metricsServer->transmitDataNetwork(userId(), data.size() + 2);
1596     }
1597     if (!_skipMessageRates) {
1598         // Only subtract from the token bucket if message rate limiting is enabled
1599         _tokenBucket--;
1600     }
1601 }
1602
1603 Network::Server CoreNetwork::usedServer() const
1604 {
1605     if (_lastUsedServerIndex < serverList().count())
1606         return serverList()[_lastUsedServerIndex];
1607
1608     if (!serverList().isEmpty())
1609         return serverList()[0];
1610
1611     return Network::Server();
1612 }
1613
1614 void CoreNetwork::requestConnect() const
1615 {
1616     if (_shuttingDown) {
1617         return;
1618     }
1619     if (connectionState() != Disconnected) {
1620         qWarning() << "Requesting connect while already being connected!";
1621         return;
1622     }
1623     QMetaObject::invokeMethod(const_cast<CoreNetwork*>(this), "connectToIrc", Qt::QueuedConnection);
1624 }
1625
1626 void CoreNetwork::requestDisconnect() const
1627 {
1628     if (_shuttingDown) {
1629         return;
1630     }
1631     if (connectionState() == Disconnected) {
1632         qWarning() << "Requesting disconnect while not being connected!";
1633         return;
1634     }
1635     userInputHandler()->handleQuit(BufferInfo(), QString());
1636 }
1637
1638 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info)
1639 {
1640     Network::Server currentServer = usedServer();
1641     setNetworkInfo(info);
1642     Core::updateNetwork(coreSession()->user(), info);
1643
1644     // the order of the servers might have changed,
1645     // so we try to find the previously used server
1646     _lastUsedServerIndex = 0;
1647     for (int i = 0; i < serverList().count(); i++) {
1648         Network::Server server = serverList()[i];
1649         if (server.host == currentServer.host && server.port == currentServer.port) {
1650             _lastUsedServerIndex = i;
1651             break;
1652         }
1653     }
1654 }
1655
1656 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString& cmd,
1657                                                    const QString& message,
1658                                                    const std::function<QList<QByteArray>(QString&)>& cmdGenerator)
1659 {
1660     QString wrkMsg(message);
1661     QList<QList<QByteArray>> msgsToSend;
1662
1663     // do while (wrkMsg.size() > 0)
1664     do {
1665         // First, check to see if the whole message can be sent at once.  The
1666         // cmdGenerator function is passed in by the caller and is used to encode
1667         // and encrypt (if applicable) the message, since different callers might
1668         // want to use different encoding or encode different values.
1669         int splitPos = wrkMsg.size();
1670         QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1671         int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1672
1673         if (initialOverrun) {
1674             // If the message was too long to be sent, first try splitting it along
1675             // word boundaries with QTextBoundaryFinder.
1676             QString splitMsg(wrkMsg);
1677             QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1678             qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1679             QList<QByteArray> splitMsgEnc;
1680             int overrun = initialOverrun;
1681
1682             while (overrun) {
1683                 splitPos = qtbf.toPreviousBoundary();
1684
1685                 // splitPos==-1 means the QTBF couldn't find a split point at all and
1686                 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1687                 // the string.  Neither one of these works for us.
1688                 if (splitPos > 0) {
1689                     // If a split point could be found, split the message there, calculate the
1690                     // overrun, and continue with the loop.
1691                     splitMsg = splitMsg.left(splitPos);
1692                     splitMsgEnc = cmdGenerator(splitMsg);
1693                     overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1694                 }
1695                 else {
1696                     // If a split point could not be found (the beginning of the message
1697                     // is reached without finding a split point short enough to send) and we
1698                     // are still in Word mode, switch to Grapheme mode.  We also need to restore
1699                     // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1700                     // the previous attempt to find a split point.
1701                     if (qtbf.type() == QTextBoundaryFinder::Word) {
1702                         splitMsg = wrkMsg;
1703                         splitPos = splitMsg.size();
1704                         QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1705                         graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1706                         qtbf = graphemeQtbf;
1707                     }
1708                     else {
1709                         // If the QTBF fails to find a split point in Grapheme mode, we give up.
1710                         // This should never happen, but it should be handled anyway.
1711                         qWarning() << "Unexpected failure to split message!";
1712                         return msgsToSend;
1713                     }
1714                 }
1715             }
1716
1717             // Once a message of sendable length has been found, remove it from the wrkMsg and
1718             // add it to the list of messages to be sent.
1719             wrkMsg.remove(0, splitPos);
1720             msgsToSend.append(splitMsgEnc);
1721         }
1722         else {
1723             // If the entire remaining message is short enough to be sent all at once, remove
1724             // it from the wrkMsg and add it to the list of messages to be sent.
1725             wrkMsg.remove(0, splitPos);
1726             msgsToSend.append(initialSplitMsgEnc);
1727         }
1728     } while (wrkMsg.size() > 0);
1729
1730     return msgsToSend;
1731 }