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