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