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