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