cmake: avoid de-duplication of user's CXXFLAGS
[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 (useSasl()) {
1090             queueCap(capability);
1091         }
1092     }
1093     else if (IrcCap::knownCaps.contains(capability)) {
1094         // Handling for general known capabilities
1095         queueCap(capability);
1096     }
1097 }
1098
1099 void CoreNetwork::serverCapAcknowledged(const QString& capability)
1100 {
1101     // This may be called multiple times in certain situations.
1102
1103     // Handle core-side configuration
1104     if (capability == IrcCap::AWAY_NOTIFY) {
1105         // away-notify enabled, stop the autoWho timers, handle manually
1106         setAutoWhoEnabled(false);
1107     }
1108
1109     // Handle capabilities that require further messages sent to the IRC server
1110     // If you change this list, ALSO change the list in CoreNetwork::capsRequiringConfiguration
1111     if (capability == IrcCap::SASL) {
1112         // If SASL mechanisms specified, limit to what's accepted for authentication
1113         // if the current identity has a cert set, use SASL EXTERNAL
1114         // FIXME use event
1115         if (!identityPtr()->sslCert().isNull()) {
1116             if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1117                 // EXTERNAL authentication supported, send request
1118                 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1119             }
1120             else {
1121                 showMessage(NetworkInternalMessage(
1122                     Message::Error,
1123                     BufferInfo::StatusBuffer,
1124                     "",
1125                     tr("SASL EXTERNAL authentication not supported")
1126                 ));
1127                 sendNextCap();
1128             }
1129         }
1130         else {
1131             if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1132                 // PLAIN authentication supported, send request
1133                 // Only working with PLAIN atm, blowfish later
1134                 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1135             }
1136             else {
1137                 showMessage(NetworkInternalMessage(
1138                     Message::Error,
1139                     BufferInfo::StatusBuffer,
1140                     "",
1141                     tr("SASL PLAIN authentication not supported")
1142                 ));
1143                 sendNextCap();
1144             }
1145         }
1146     }
1147 }
1148
1149 void CoreNetwork::serverCapRemoved(const QString& capability)
1150 {
1151     // This may be called multiple times in certain situations.
1152
1153     // Handle special cases here
1154     if (capability == IrcCap::AWAY_NOTIFY) {
1155         // away-notify disabled, enable autoWho according to configuration
1156         setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1157     }
1158 }
1159
1160 void CoreNetwork::queueCap(const QString& capability)
1161 {
1162     // IRCv3 specs all use lowercase capability names
1163     QString _capLowercase = capability.toLower();
1164
1165     if (capsRequiringConfiguration.contains(_capLowercase)) {
1166         // The capability requires additional configuration before being acknowledged (e.g. SASL),
1167         // so we should negotiate it separately from all other capabilities.  Otherwise new
1168         // capabilities will be requested while still configuring the previous one.
1169         if (!_capsQueuedIndividual.contains(_capLowercase)) {
1170             _capsQueuedIndividual.append(_capLowercase);
1171         }
1172     }
1173     else {
1174         // The capability doesn't need any special configuration, so it should be safe to try
1175         // bundling together with others.  "Should" being the imperative word, as IRC servers can do
1176         // anything.
1177         if (!_capsQueuedBundled.contains(_capLowercase)) {
1178             _capsQueuedBundled.append(_capLowercase);
1179         }
1180     }
1181 }
1182
1183 QString CoreNetwork::takeQueuedCaps()
1184 {
1185     // Clear the record of the most recently negotiated capability bundle.  Does nothing if the list
1186     // is empty.
1187     _capsQueuedLastBundle.clear();
1188
1189     // First, negotiate all the standalone capabilities that require additional configuration.
1190     if (!_capsQueuedIndividual.empty()) {
1191         // We have an individual capability available.  Take the first and pass it back.
1192         return _capsQueuedIndividual.takeFirst();
1193     }
1194     else if (!_capsQueuedBundled.empty()) {
1195         // We have capabilities available that can be grouped.  Try to fit in as many as within the
1196         // maximum length.
1197         // See CoreNetwork::maxCapRequestLength
1198
1199         // Response must have at least one capability regardless of max length for anything to
1200         // happen.
1201         QString capBundle = _capsQueuedBundled.takeFirst();
1202         QString nextCap("");
1203         while (!_capsQueuedBundled.empty()) {
1204             // As long as capabilities remain, get the next...
1205             nextCap = _capsQueuedBundled.first();
1206             if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1207                 // [capability + 1 for a space + this new capability] fit within length limits
1208                 // Add it to formatted list
1209                 capBundle.append(" " + nextCap);
1210                 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1211                 _capsQueuedLastBundle.append(nextCap);
1212                 // Then remove it from the queue
1213                 _capsQueuedBundled.removeFirst();
1214             }
1215             else {
1216                 // We've reached the length limit for a single capability request, stop adding more
1217                 break;
1218             }
1219         }
1220         // Return this space-separated set of capabilities, removing any extra spaces
1221         return capBundle.trimmed();
1222     }
1223     else {
1224         // No capabilities left to negotiate, return an empty string.
1225         return QString();
1226     }
1227 }
1228
1229 void CoreNetwork::retryCapsIndividually()
1230 {
1231     // The most recent set of capabilities got denied by the IRC server.  As we don't know what got
1232     // denied, try each capability individually.
1233     if (_capsQueuedLastBundle.empty()) {
1234         // No most recently tried capability set, just return.
1235         return;
1236         // Note: there's little point in retrying individually requested caps during negotiation.
1237         // We know the individual capability was the one that failed, and it's not likely it'll
1238         // suddenly start working within a few seconds.  'cap-notify' provides a better system for
1239         // handling capability removal and addition.
1240     }
1241
1242     // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1243     // over efficiency.  If this becomes an issue, implement a binary splicing system instead,
1244     // keeping track of which halves of the group fail, dividing the set each time.
1245
1246     // Add most recently tried capability set to individual list, re-requesting them one at a time
1247     _capsQueuedIndividual.append(_capsQueuedLastBundle);
1248     // Warn of this issue to explain the slower login.  Servers usually shouldn't trigger this.
1249     showMessage(NetworkInternalMessage(
1250         Message::Server,
1251         BufferInfo::StatusBuffer,
1252         "",
1253         tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", "))
1254     ));
1255     // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1256     // need to remove them here.
1257     // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1258     // indefinitely.
1259     _capsQueuedLastBundle.clear();
1260 }
1261
1262 void CoreNetwork::beginCapNegotiation()
1263 {
1264     // Check if any available capabilities have been disabled
1265     QStringList capsSkipped;
1266     if (!skipCaps().isEmpty() && !caps().isEmpty()) {
1267         // Find the entries that are common to skipCaps() and caps().  This represents any
1268         // capabilities supported by the server that were skipped.
1269
1270         // Both skipCaps() and caps() are already lowercase
1271         // std::set_intersection requires sorted lists, and we can't modify the original lists.
1272         //
1273         // skipCaps() should already be sorted.  caps() is intentionally not sorted elsewhere so
1274         // Quassel can show the capabilities in the order transmitted by the network.
1275         auto sortedCaps = caps();
1276         sortedCaps.sort();
1277
1278         // Find the intersection between skipped caps and server-supplied caps
1279         std::set_intersection(skipCaps().cbegin(), skipCaps().cend(),
1280                               sortedCaps.cbegin(), sortedCaps.cend(),
1281                               std::back_inserter(capsSkipped));
1282     }
1283
1284     if (!capsPendingNegotiation()) {
1285         // No capabilities are queued for request, determine the reason why
1286         QString capStatusMsg;
1287         if (caps().empty()) {
1288             // The server doesn't provide any capabilities, but supports CAP LS
1289             capStatusMsg = tr("No capabilities available");
1290         }
1291         else if (capsEnabled().empty()) {
1292             // The server supports capabilities (caps() is not empty) but Quassel doesn't support
1293             // anything offered.  This should be uncommon.
1294             capStatusMsg =
1295                     tr("None of the capabilities provided by the server are supported (found: %1)")
1296                     .arg(caps().join(", "));
1297         }
1298         else {
1299             // Quassel has enabled some capabilities, but there are no further capabilities that can
1300             // be negotiated.
1301             // (E.g. the user has manually run "/cap ls 302" after initial negotiation.)
1302             capStatusMsg =
1303                     tr("No additional capabilities are supported (found: %1; currently enabled: %2)")
1304                     .arg(caps().join(", "), capsEnabled().join(", "));
1305         }
1306         // Inform the user of the situation
1307         showMessage(NetworkInternalMessage(
1308             Message::Server,
1309             BufferInfo::StatusBuffer,
1310             "",
1311             capStatusMsg
1312         ));
1313
1314         if (!capsSkipped.isEmpty()) {
1315             // Mention that some capabilities are skipped
1316             showMessage(NetworkInternalMessage(
1317                 Message::Server,
1318                 BufferInfo::StatusBuffer,
1319                 "",
1320                 tr("Quassel is configured to ignore some capabilities (skipped: %1)").arg(capsSkipped.join(", "))
1321             ));
1322         }
1323
1324         // End any ongoing capability negotiation, allowing connection to continue
1325         endCapNegotiation();
1326         return;
1327     }
1328
1329     _capNegotiationActive = true;
1330     showMessage(NetworkInternalMessage(
1331         Message::Server,
1332         BufferInfo::StatusBuffer,
1333         "",
1334         tr("Ready to negotiate (found: %1)").arg(caps().join(", "))
1335     ));
1336
1337     if (!capsSkipped.isEmpty()) {
1338         // Mention that some capabilities are skipped
1339         showMessage(NetworkInternalMessage(
1340             Message::Server,
1341             BufferInfo::StatusBuffer,
1342             "",
1343             tr("Quassel is configured to ignore some capabilities (skipped: %1)").arg(capsSkipped.join(", "))
1344         ));
1345     }
1346
1347     // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1348     // comma separator between the two if needed (both individual and bundled caps exist).
1349     QString queuedCapsDisplay = _capsQueuedIndividual.join(", ")
1350                                 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1351                                 + _capsQueuedBundled.join(", ");
1352     showMessage(NetworkInternalMessage(
1353         Message::Server,
1354         BufferInfo::StatusBuffer,
1355         "",
1356         tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay)
1357     ));
1358
1359     sendNextCap();
1360 }
1361
1362 void CoreNetwork::sendNextCap()
1363 {
1364     if (capsPendingNegotiation()) {
1365         // Request the next set of capabilities and remove them from the list
1366         putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1367     }
1368     else {
1369         // No pending desired capabilities, capability negotiation finished
1370         // If SASL requested but not available, print a warning
1371         if (useSasl() && !capEnabled(IrcCap::SASL))
1372             showMessage(NetworkInternalMessage(
1373                 Message::Error,
1374                 BufferInfo::StatusBuffer,
1375                 "",
1376                 tr("SASL authentication currently not supported by server")
1377             ));
1378
1379         if (_capNegotiationActive) {
1380             showMessage(NetworkInternalMessage(
1381                 Message::Server,
1382                 BufferInfo::StatusBuffer,
1383                 "",
1384                 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", "))
1385             ));
1386             _capNegotiationActive = false;
1387         }
1388
1389         endCapNegotiation();
1390     }
1391 }
1392
1393 void CoreNetwork::endCapNegotiation()
1394 {
1395     // If nick registration is already complete, CAP END is not required
1396     if (!_capInitialNegotiationEnded) {
1397         putRawLine(serverEncode(QString("CAP END")));
1398         _capInitialNegotiationEnded = true;
1399     }
1400 }
1401
1402 /******** AutoWHO ********/
1403
1404 void CoreNetwork::startAutoWhoCycle()
1405 {
1406     if (!_autoWhoQueue.isEmpty()) {
1407         _autoWhoCycleTimer.stop();
1408         return;
1409     }
1410     _autoWhoQueue = channels();
1411 }
1412
1413 void CoreNetwork::queueAutoWhoOneshot(const QString& name)
1414 {
1415     // Prepend so these new channels/nicks are the first to be checked
1416     // Don't allow duplicates
1417     if (!_autoWhoQueue.contains(name.toLower())) {
1418         _autoWhoQueue.prepend(name.toLower());
1419     }
1420     if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1421         // When away-notify is active, the timer's stopped.  Start a new cycle to who this channel.
1422         setAutoWhoEnabled(true);
1423     }
1424 }
1425
1426 void CoreNetwork::setAutoWhoDelay(int delay)
1427 {
1428     _autoWhoTimer.setInterval(delay * 1000);
1429 }
1430
1431 void CoreNetwork::setAutoWhoInterval(int interval)
1432 {
1433     _autoWhoCycleTimer.setInterval(interval * 1000);
1434 }
1435
1436 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1437 {
1438     if (enabled && isConnected() && !_autoWhoTimer.isActive())
1439         _autoWhoTimer.start();
1440     else if (!enabled) {
1441         _autoWhoTimer.stop();
1442         _autoWhoCycleTimer.stop();
1443     }
1444 }
1445
1446 void CoreNetwork::sendAutoWho()
1447 {
1448     // Don't send autowho if there are still some pending
1449     if (_autoWhoPending.count())
1450         return;
1451
1452     while (!_autoWhoQueue.isEmpty()) {
1453         QString chanOrNick = _autoWhoQueue.takeFirst();
1454         // Check if it's a known channel or nick
1455         IrcChannel* ircchan = ircChannel(chanOrNick);
1456         IrcUser* ircuser = ircUser(chanOrNick);
1457         if (ircchan) {
1458             // Apply channel limiting rules
1459             // If using away-notify, don't impose channel size limits in order to capture away
1460             // state of everyone.  Auto-who won't run on a timer so network impact is minimal.
1461             if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1462                 && !capEnabled(IrcCap::AWAY_NOTIFY))
1463                 continue;
1464             _autoWhoPending[chanOrNick.toLower()]++;
1465         }
1466         else if (ircuser) {
1467             // Checking a nick, add it to the pending list
1468             _autoWhoPending[ircuser->nick().toLower()]++;
1469         }
1470         else {
1471             // Not a channel or a nick, skip it
1472             qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1473             continue;
1474         }
1475         if (supports("WHOX")) {
1476             // Use WHO extended to poll away users and/or user accounts
1477             // Explicitly only match on nickname ("n"), don't rely on server defaults
1478             //
1479             // WHO <nickname> n%chtsunfra,<unique_number>
1480             //
1481             // See http://faerion.sourceforge.net/doc/irc/whox.var
1482             // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1483             // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1484             putRawLine(serverEncode(
1485                 QString("WHO %1 n%chtsunfra,%2")
1486                     .arg(chanOrNick, QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))
1487             ));
1488         }
1489         else {
1490             // Fall back to normal WHO
1491             //
1492             // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1493             // hostmask, etc.  There's nothing we can do about that :(
1494             //
1495             // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1496             putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1497         }
1498         break;
1499     }
1500
1501     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1502         // Timer was stopped, means a new cycle is due immediately
1503         // Don't run a new cycle if using away-notify; server will notify as appropriate
1504         _autoWhoCycleTimer.start();
1505         startAutoWhoCycle();
1506     }
1507     else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1508         // Don't run another who cycle if away-notify is enabled
1509         _autoWhoCycleTimer.stop();
1510     }
1511 }
1512
1513 void CoreNetwork::onSslErrors(const QList<QSslError>& sslErrors)
1514 {
1515     Server server = usedServer();
1516     if (server.sslVerify) {
1517         // Treat the SSL error as a hard error
1518         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1519                                      "since verification is required");
1520         if (!sslErrors.empty()) {
1521             // Add the error reason if known
1522             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1523         }
1524         showMessage(NetworkInternalMessage(
1525             Message::Error,
1526             BufferInfo::StatusBuffer,
1527             "",
1528             sslErrorMessage
1529         ));
1530
1531         // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1532         // validity, network trouble, etc.
1533         disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1534     }
1535     else {
1536         // Treat the SSL error as a warning, continue to connect anyways
1537         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1538                                      "since verification is not required");
1539         if (!sslErrors.empty()) {
1540             // Add the error reason if known
1541             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1542         }
1543         showMessage(NetworkInternalMessage(
1544             Message::Info,
1545             BufferInfo::StatusBuffer,
1546             "",
1547             sslErrorMessage
1548         ));
1549
1550         // Proceed with the connection
1551         socket.ignoreSslErrors();
1552     }
1553 }
1554
1555 void CoreNetwork::checkTokenBucket()
1556 {
1557     if (_skipMessageRates) {
1558         if (_msgQueue.empty()) {
1559             // Message queue emptied; stop the timer and bail out
1560             _tokenBucketTimer.stop();
1561             return;
1562         }
1563         // Otherwise, we're emptying the queue, continue on as normal
1564     }
1565
1566     // Process whatever messages are pending
1567     fillBucketAndProcessQueue();
1568 }
1569
1570 void CoreNetwork::fillBucketAndProcessQueue()
1571 {
1572     // If there's less tokens than burst size, refill the token bucket by 1
1573     if (_tokenBucket < _burstSize) {
1574         _tokenBucket++;
1575     }
1576
1577     // As long as there's tokens available and messages remaining, sending messages from the queue
1578     while (!_msgQueue.empty() && _tokenBucket > 0) {
1579         writeToSocket(_msgQueue.takeFirst());
1580         if (_metricsServer) {
1581             _metricsServer->messageQueue(userId(), _msgQueue.size());
1582         }
1583     }
1584 }
1585
1586 void CoreNetwork::writeToSocket(const QByteArray& data)
1587 {
1588     // Log the message if enabled and network ID matches or allows all
1589     if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1590         // Include network ID
1591         qDebug() << "IRC net" << networkId() << ">>" << data;
1592     }
1593     socket.write(data);
1594     socket.write("\r\n");
1595     if (_metricsServer) {
1596         _metricsServer->transmitDataNetwork(userId(), data.size() + 2);
1597     }
1598     if (!_skipMessageRates) {
1599         // Only subtract from the token bucket if message rate limiting is enabled
1600         _tokenBucket--;
1601     }
1602 }
1603
1604 Network::Server CoreNetwork::usedServer() const
1605 {
1606     if (_lastUsedServerIndex < serverList().count())
1607         return serverList()[_lastUsedServerIndex];
1608
1609     if (!serverList().isEmpty())
1610         return serverList()[0];
1611
1612     return Network::Server();
1613 }
1614
1615 void CoreNetwork::requestConnect() const
1616 {
1617     if (_shuttingDown) {
1618         return;
1619     }
1620     if (connectionState() != Disconnected) {
1621         qWarning() << "Requesting connect while already being connected!";
1622         return;
1623     }
1624     QMetaObject::invokeMethod(const_cast<CoreNetwork*>(this), "connectToIrc", Qt::QueuedConnection);
1625 }
1626
1627 void CoreNetwork::requestDisconnect() const
1628 {
1629     if (_shuttingDown) {
1630         return;
1631     }
1632     if (connectionState() == Disconnected) {
1633         qWarning() << "Requesting disconnect while not being connected!";
1634         return;
1635     }
1636     userInputHandler()->handleQuit(BufferInfo(), QString());
1637 }
1638
1639 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info)
1640 {
1641     Network::Server currentServer = usedServer();
1642     setNetworkInfo(info);
1643     Core::updateNetwork(coreSession()->user(), info);
1644
1645     // the order of the servers might have changed,
1646     // so we try to find the previously used server
1647     _lastUsedServerIndex = 0;
1648     for (int i = 0; i < serverList().count(); i++) {
1649         Network::Server server = serverList()[i];
1650         if (server.host == currentServer.host && server.port == currentServer.port) {
1651             _lastUsedServerIndex = i;
1652             break;
1653         }
1654     }
1655 }
1656
1657 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString& cmd,
1658                                                    const QString& message,
1659                                                    const std::function<QList<QByteArray>(QString&)>& cmdGenerator)
1660 {
1661     QString wrkMsg(message);
1662     QList<QList<QByteArray>> msgsToSend;
1663
1664     // do while (wrkMsg.size() > 0)
1665     do {
1666         // First, check to see if the whole message can be sent at once.  The
1667         // cmdGenerator function is passed in by the caller and is used to encode
1668         // and encrypt (if applicable) the message, since different callers might
1669         // want to use different encoding or encode different values.
1670         int splitPos = wrkMsg.size();
1671         QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1672         int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1673
1674         if (initialOverrun) {
1675             // If the message was too long to be sent, first try splitting it along
1676             // word boundaries with QTextBoundaryFinder.
1677             QString splitMsg(wrkMsg);
1678             QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1679             qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1680             QList<QByteArray> splitMsgEnc;
1681             int overrun = initialOverrun;
1682
1683             while (overrun) {
1684                 splitPos = qtbf.toPreviousBoundary();
1685
1686                 // splitPos==-1 means the QTBF couldn't find a split point at all and
1687                 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1688                 // the string.  Neither one of these works for us.
1689                 if (splitPos > 0) {
1690                     // If a split point could be found, split the message there, calculate the
1691                     // overrun, and continue with the loop.
1692                     splitMsg = splitMsg.left(splitPos);
1693                     splitMsgEnc = cmdGenerator(splitMsg);
1694                     overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1695                 }
1696                 else {
1697                     // If a split point could not be found (the beginning of the message
1698                     // is reached without finding a split point short enough to send) and we
1699                     // are still in Word mode, switch to Grapheme mode.  We also need to restore
1700                     // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1701                     // the previous attempt to find a split point.
1702                     if (qtbf.type() == QTextBoundaryFinder::Word) {
1703                         splitMsg = wrkMsg;
1704                         splitPos = splitMsg.size();
1705                         QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1706                         graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1707                         qtbf = graphemeQtbf;
1708                     }
1709                     else {
1710                         // If the QTBF fails to find a split point in Grapheme mode, we give up.
1711                         // This should never happen, but it should be handled anyway.
1712                         qWarning() << "Unexpected failure to split message!";
1713                         return msgsToSend;
1714                     }
1715                 }
1716             }
1717
1718             // Once a message of sendable length has been found, remove it from the wrkMsg and
1719             // add it to the list of messages to be sent.
1720             wrkMsg.remove(0, splitPos);
1721             msgsToSend.append(splitMsgEnc);
1722         }
1723         else {
1724             // If the entire remaining message is short enough to be sent all at once, remove
1725             // it from the wrkMsg and add it to the list of messages to be sent.
1726             wrkMsg.remove(0, splitPos);
1727             msgsToSend.append(initialSplitMsgEnc);
1728         }
1729     } while (wrkMsg.size() > 0);
1730
1731     return msgsToSend;
1732 }