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