1 /***************************************************************************
2 * Copyright (C) 2005-2020 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "corenetwork.h"
25 #include <QTextBoundaryFinder>
28 #include "coreidentity.h"
29 #include "corenetworkconfig.h"
30 #include "coresession.h"
31 #include "coreuserinputhandler.h"
32 #include "ircencoder.h"
35 #include "networkevent.h"
37 CoreNetwork::CoreNetwork(const NetworkId& networkid, CoreSession* session)
38 : Network(networkid, session)
39 , _coreSession(session)
40 , _userInputHandler(new CoreUserInputHandler(this))
41 , _metricsServer(Core::instance()->metricsServer())
42 , _autoReconnectCount(0)
43 , _quitRequested(false)
44 , _disconnectExpected(false)
45 , _previousConnectionAttemptFailed(false)
46 , _lastUsedServerIndex(0)
47 , _requestedUserModes('-')
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();
53 _autoReconnectTimer.setSingleShot(true);
54 connect(&_socketCloseTimer, &QTimer::timeout, this, &CoreNetwork::onSocketCloseTimeout);
56 setPingInterval(networkConfig()->pingInterval());
57 connect(&_pingTimer, &QTimer::timeout, this, &CoreNetwork::sendPing);
59 setAutoWhoDelay(networkConfig()->autoWhoDelay());
60 setAutoWhoInterval(networkConfig()->autoWhoInterval());
62 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
63 for (const QString& chan : channels.keys()) {
64 _channelKeys[chan.toLower()] = channels[chan];
67 QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
68 for (const QString& buffer : bufferCiphers.keys()) {
69 storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
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);
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);
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);
88 connect(&socket, &QSslSocket::encrypted, this, &CoreNetwork::onSocketInitialized);
89 connect(&socket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &CoreNetwork::onSslErrors);
91 connect(this, &CoreNetwork::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
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);
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);
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);
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);
117 CoreNetwork::~CoreNetwork()
119 // Ensure we don't get any more signals from the socket while shutting down
120 disconnect(&socket, nullptr, this, nullptr);
121 if (!forceDisconnect()) {
122 qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
124 .arg(networkId().toInt())
125 .arg(userId().toInt());
129 bool CoreNetwork::forceDisconnect(int msecs)
131 if (socket.state() == QAbstractSocket::UnconnectedState) {
132 // Socket already disconnected.
135 // Request a socket-level disconnect if not already happened
136 socket.disconnectFromHost();
137 if (socket.state() != QAbstractSocket::UnconnectedState) {
138 return socket.waitForDisconnected(msecs);
143 QString CoreNetwork::channelDecode(const QString& bufferName, const QByteArray& string) const
145 if (!bufferName.isEmpty()) {
146 IrcChannel* channel = ircChannel(bufferName);
148 return channel->decodeString(string);
150 return decodeString(string);
153 QString CoreNetwork::userDecode(const QString& userNick, const QByteArray& string) const
155 IrcUser* user = ircUser(userNick);
157 return user->decodeString(string);
158 return decodeString(string);
161 QByteArray CoreNetwork::channelEncode(const QString& bufferName, const QString& string) const
163 if (!bufferName.isEmpty()) {
164 IrcChannel* channel = ircChannel(bufferName);
166 return channel->encodeString(string);
168 return encodeString(string);
171 QByteArray CoreNetwork::userEncode(const QString& userNick, const QString& string) const
173 IrcUser* user = ircUser(userNick);
175 return user->encodeString(string);
176 return encodeString(string);
179 void CoreNetwork::connectToIrc(bool reconnecting)
185 if (Core::instance()->identServer()) {
186 _socketId = Core::instance()->identServer()->addWaitingSocket();
189 if (_metricsServer) {
190 _metricsServer->addNetwork(userId());
193 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
194 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
195 if (unlimitedReconnectRetries())
196 _autoReconnectCount = -1;
198 _autoReconnectCount = autoReconnectRetries();
200 if (serverList().isEmpty()) {
201 qWarning() << "Server list empty, ignoring connect request!";
204 CoreIdentity* identity = identityPtr();
206 qWarning() << "Invalid identity configures, ignoring connect request!";
210 // cleaning up old quit reason
213 // Reset capability negotiation tracking, also handling server changes during reconnect
214 _capsQueuedIndividual.clear();
215 _capsQueuedBundled.clear();
217 _capNegotiationActive = false;
218 _capInitialNegotiationEnded = false;
220 // use a random server?
221 if (useRandomServer()) {
222 _lastUsedServerIndex = qrand() % serverList().size();
224 else if (_previousConnectionAttemptFailed) {
225 // cycle to next server if previous connection attempt failed
226 _previousConnectionAttemptFailed = false;
227 showMessage(NetworkInternalMessage(
229 BufferInfo::StatusBuffer,
231 tr("Connection failed. Cycling to next server...")
233 if (++_lastUsedServerIndex >= serverList().size()) {
234 _lastUsedServerIndex = 0;
238 // Start out with the top server in the list
239 _lastUsedServerIndex = 0;
242 Server server = usedServer();
243 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
244 showMessage(NetworkInternalMessage(
246 BufferInfo::StatusBuffer,
248 tr("Connecting to %1:%2...").arg(server.host).arg(server.port)
251 if (server.useProxy) {
252 QNetworkProxy proxy((QNetworkProxy::ProxyType) server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
253 socket.setProxy(proxy);
256 socket.setProxy(QNetworkProxy::NoProxy);
261 // Reset tracking for valid timestamps in PONG replies
262 setPongTimestampValid(false);
264 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
265 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
266 if (!server.useProxy) {
267 // Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
268 // hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
269 QHostInfo::fromName(server.host);
273 CoreIdentity* identity = identityPtr();
275 socket.setLocalCertificate(identity->sslCert());
276 socket.setPrivateKey(identity->sslKey());
278 socket.connectToHostEncrypted(server.host, server.port);
281 socket.connectToHost(server.host, server.port);
284 socket.connectToHost(server.host, server.port);
288 void CoreNetwork::disconnectFromIrc(bool requested, const QString& reason, bool withReconnect)
290 // Disconnecting from the network, should expect a socket close or error
291 _disconnectExpected = true;
292 _quitRequested = requested; // see socketDisconnected();
293 if (!withReconnect) {
294 _autoReconnectTimer.stop();
295 _autoReconnectCount = 0; // prohibiting auto reconnect
297 disablePingTimeout();
299 if (_metricsServer) {
300 _metricsServer->messageQueue(userId(), 0);
307 awayMsg = me_->awayMessage();
308 Core::setAwayMessage(userId(), networkId(), awayMsg);
311 if (reason.isEmpty() && identityPtr())
312 _quitReason = identityPtr()->quitReason();
314 _quitReason = reason;
316 showMessage(NetworkInternalMessage(
318 BufferInfo::StatusBuffer,
320 tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason)
322 if (socket.state() == QAbstractSocket::UnconnectedState) {
323 onSocketDisconnected();
326 if (socket.state() == QAbstractSocket::ConnectedState) {
327 // If shutting down, prioritize the QUIT command
328 userInputHandler()->issueQuit(_quitReason, _shuttingDown);
333 if (socket.state() != QAbstractSocket::UnconnectedState) {
334 // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
335 _socketCloseTimer.start(10000);
340 void CoreNetwork::onSocketCloseTimeout()
342 qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
344 .arg(networkId().toInt())
345 .arg(userId().toInt());
349 void CoreNetwork::shutdown()
351 _shuttingDown = true;
352 disconnectFromIrc(false, {}, false);
355 void CoreNetwork::userInput(const BufferInfo& buf, QString msg)
357 userInputHandler()->handleUserInput(buf, msg);
360 void CoreNetwork::putRawLine(const QByteArray& s, bool prepend)
362 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.isEmpty())) {
363 // If there's tokens remaining, ...
364 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
365 // Send the message now.
369 // Otherwise, queue the message for later
371 // Jump to the start, skipping other messages
372 _msgQueue.prepend(s);
375 // Add to back, waiting in order
378 if (_metricsServer) {
379 _metricsServer->messageQueue(userId(), _msgQueue.size());
384 void CoreNetwork::putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString>& tags, bool prepend)
386 putRawLine(IrcEncoder::writeMessage(tags, prefix, cmd, params), prepend);
389 void CoreNetwork::putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString>& tags, bool prependAll)
391 QListIterator<QList<QByteArray>> i(params);
392 while (i.hasNext()) {
393 QList<QByteArray> msg = i.next();
394 putCmd(cmd, msg, prefix, tags, prependAll);
398 void CoreNetwork::setChannelJoined(const QString& channel)
400 queueAutoWhoOneshot(channel); // check this new channel first
402 Core::setChannelPersistent(userId(), networkId(), channel, true);
403 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
406 void CoreNetwork::setChannelParted(const QString& channel)
408 removeChannelKey(channel);
409 _autoWhoQueue.removeAll(channel.toLower());
410 _autoWhoPending.remove(channel.toLower());
412 Core::setChannelPersistent(userId(), networkId(), channel, false);
415 void CoreNetwork::addChannelKey(const QString& channel, const QString& key)
418 removeChannelKey(channel);
421 _channelKeys[channel.toLower()] = key;
425 void CoreNetwork::removeChannelKey(const QString& channel)
427 _channelKeys.remove(channel.toLower());
431 Cipher* CoreNetwork::cipher(const QString& target)
433 if (target.isEmpty())
436 if (!Cipher::neededFeaturesAvailable())
439 auto* channel = qobject_cast<CoreIrcChannel*>(ircChannel(target));
441 return channel->cipher();
443 auto* user = qobject_cast<CoreIrcUser*>(ircUser(target));
445 return user->cipher();
447 else if (!isChannelName(target)) {
448 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
453 QByteArray CoreNetwork::cipherKey(const QString& target) const
455 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
457 return c->cipher()->key();
459 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
461 return u->cipher()->key();
466 void CoreNetwork::setCipherKey(const QString& target, const QByteArray& key)
468 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
470 c->setEncrypted(c->cipher()->setKey(key));
471 coreSession()->setBufferCipher(networkId(), target, key);
475 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
476 if (!u && !isChannelName(target))
477 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
480 u->setEncrypted(u->cipher()->setKey(key));
481 coreSession()->setBufferCipher(networkId(), target, key);
486 bool CoreNetwork::cipherUsesCBC(const QString& target)
488 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
490 return c->cipher()->usesCBC();
491 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
493 return u->cipher()->usesCBC();
497 #endif /* HAVE_QCA2 */
499 bool CoreNetwork::setAutoWhoDone(const QString& name)
501 QString chanOrNick = name.toLower();
502 if (_autoWhoPending.value(chanOrNick, 0) <= 0)
504 if (--_autoWhoPending[chanOrNick] <= 0)
505 _autoWhoPending.remove(chanOrNick);
509 void CoreNetwork::setMyNick(const QString& mynick)
511 Network::setMyNick(mynick);
512 if (connectionState() == Network::Initializing)
513 networkInitialized();
516 void CoreNetwork::onSocketHasData()
518 while (socket.canReadLine()) {
519 QByteArray s = socket.readLine();
520 if (_metricsServer) {
521 _metricsServer->receiveDataNetwork(userId(), s.size());
523 if (s.endsWith("\r\n"))
525 else if (s.endsWith("\n"))
527 NetworkDataEvent* event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
528 event->setTimestamp(QDateTime::currentDateTimeUtc());
529 emit newEvent(event);
533 void CoreNetwork::onSocketError(QAbstractSocket::SocketError error)
535 // Ignore socket closed errors if expected
536 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
540 _previousConnectionAttemptFailed = true;
541 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
542 emit connectionError(socket.errorString());
543 showMessage(NetworkInternalMessage(
545 BufferInfo::StatusBuffer,
547 tr("Connection failure: %1").arg(socket.errorString())
549 emitConnectionError(socket.errorString());
550 if (socket.state() < QAbstractSocket::ConnectedState) {
551 onSocketDisconnected();
555 void CoreNetwork::onSocketInitialized()
557 CoreIdentity* identity = identityPtr();
559 qCritical() << "Identity invalid!";
564 Server server = usedServer();
567 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
568 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
569 if (!server.useSsl || !socket.isEncrypted()) {
570 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
573 if (server.useSsl && !socket.isEncrypted()) {
574 // We'll finish setup once we're encrypted, and called again
578 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
581 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
583 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
584 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
585 // force flag to apply user preferences. When making changes, ensure that this still happens!
586 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
587 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
589 updateRateLimiting(true);
590 // Fill up the token bucket as we're connecting from scratch
593 // Request capabilities as per IRCv3.2 specifications
594 // Older servers should ignore this; newer servers won't downgrade to RFC1459
595 showMessage(NetworkInternalMessage(
597 BufferInfo::StatusBuffer,
599 tr("Requesting capability list...")
601 putRawLine(serverEncode(QString("CAP LS 302")));
603 if (!server.password.isEmpty()) {
604 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
607 if (identity->nicks().isEmpty()) {
609 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
612 nick = identity->nicks()[0];
614 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
615 // Only allow strict-compliant idents when strict mode is enabled
616 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(coreSession()->strictCompliantIdent(identity), identity->realName())));
619 void CoreNetwork::onSocketDisconnected()
621 disablePingTimeout();
623 if (_metricsServer) {
624 _metricsServer->messageQueue(userId(), 0);
627 _autoWhoCycleTimer.stop();
628 _autoWhoTimer.stop();
629 _autoWhoQueue.clear();
630 _autoWhoPending.clear();
632 _socketCloseTimer.stop();
634 _tokenBucketTimer.stop();
638 for (const QString& channel : me_->channels()) {
639 showMessage(NetworkInternalMessage(
641 BufferInfo::ChannelBuffer,
643 _quitReason, me_->hostmask()
649 emit disconnected(networkId());
650 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
651 // Reset disconnect expectations
652 _disconnectExpected = false;
653 if (_quitRequested) {
654 _quitRequested = false;
655 setConnectionState(Network::Disconnected);
656 Core::setNetworkConnected(userId(), networkId(), false);
658 else if (_autoReconnectCount != 0) {
659 setConnectionState(Network::Reconnecting);
660 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
661 doAutoReconnect(); // first try is immediate
663 _autoReconnectTimer.start();
666 if (_metricsServer) {
667 _metricsServer->removeNetwork(userId());
671 void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState)
673 Network::ConnectionState state;
674 switch (socketState) {
675 case QAbstractSocket::UnconnectedState:
676 state = Network::Disconnected;
677 onSocketDisconnected();
679 case QAbstractSocket::HostLookupState:
680 case QAbstractSocket::ConnectingState:
681 state = Network::Connecting;
683 case QAbstractSocket::ConnectedState:
684 state = Network::Initializing;
686 case QAbstractSocket::ClosingState:
687 state = Network::Disconnecting;
690 state = Network::Disconnected;
692 setConnectionState(state);
695 void CoreNetwork::networkInitialized()
697 setConnectionState(Network::Initialized);
699 _disconnectExpected = false;
700 _quitRequested = false;
702 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
703 // flag used for initial registration and capability negotiation.
704 updateRateLimiting();
706 if (useAutoReconnect()) {
708 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
711 // restore away state
712 QString awayMsg = Core::awayMessage(userId(), networkId());
713 if (!awayMsg.isEmpty()) {
714 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
715 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
716 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
723 if (networkConfig()->autoWhoEnabled()) {
724 _autoWhoCycleTimer.start();
725 _autoWhoTimer.start();
726 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
729 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
730 Core::setNetworkConnected(userId(), networkId(), true);
733 void CoreNetwork::sendPerform()
735 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
738 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
739 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
742 // restore old user modes if server default mode is set.
745 if (!me_->userModes().isEmpty()) {
749 connect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
750 connect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
755 for (const QString& line : perform()) {
757 userInput(statusBuf, line);
760 // rejoin channels we've been in
761 if (rejoinChannels()) {
762 QStringList channels, keys;
763 for (const QString& chan : coreSession()->persistentChannels(networkId()).keys()) {
764 QString key = channelKey(chan);
765 if (!key.isEmpty()) {
766 channels.prepend(chan);
770 channels.append(chan);
773 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
774 if (!joinString.isEmpty())
775 userInputHandler()->handleJoin(statusBuf, joinString);
779 void CoreNetwork::restoreUserModes()
784 disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
785 disconnect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
787 QString modesDelta = Core::userModes(userId(), networkId());
788 QString currentModes = me_->userModes();
790 QString addModes, removeModes;
791 if (modesDelta.contains('-')) {
792 addModes = modesDelta.section('-', 0, 0);
793 removeModes = modesDelta.section('-', 1);
796 addModes = modesDelta;
799 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
800 if (currentModes.isEmpty())
801 removeModes = QString();
803 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
805 if (addModes.isEmpty() && removeModes.isEmpty())
808 if (!addModes.isEmpty())
809 addModes = '+' + addModes;
810 if (!removeModes.isEmpty())
811 removeModes = '-' + removeModes;
813 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
814 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
817 void CoreNetwork::updateIssuedModes(const QString& requestedModes)
823 for (auto requestedMode : requestedModes) {
824 if (requestedMode == '+') {
828 if (requestedMode == '-') {
833 addModes += requestedMode;
836 removeModes += requestedMode;
840 QString addModesOld = _requestedUserModes.section('-', 0, 0);
841 QString removeModesOld = _requestedUserModes.section('-', 1);
843 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
844 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
845 addModes += addModesOld;
847 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
848 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
849 removeModes += removeModesOld;
851 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
854 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
856 QString persistentUserModes = Core::userModes(userId(), networkId());
858 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
859 QString requestedRemove = _requestedUserModes.section('-', 1);
861 QString persistentAdd, persistentRemove;
862 if (persistentUserModes.contains('-')) {
863 persistentAdd = persistentUserModes.section('-', 0, 0);
864 persistentRemove = persistentUserModes.section('-', 1);
867 persistentAdd = persistentUserModes;
870 // remove modes we didn't issue
871 if (requestedAdd.isEmpty())
872 addModes = QString();
874 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
876 if (requestedRemove.isEmpty())
877 removeModes = QString();
879 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
882 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
883 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
886 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
887 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
889 // update issued mode list
890 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
891 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
892 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
894 persistentAdd += addModes;
895 persistentRemove += removeModes;
896 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
899 void CoreNetwork::resetPersistentModes()
901 _requestedUserModes = QString('-');
902 Core::setUserModes(userId(), networkId(), QString());
905 void CoreNetwork::setUseAutoReconnect(bool use)
907 Network::setUseAutoReconnect(use);
909 _autoReconnectTimer.stop();
912 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
914 Network::setAutoReconnectInterval(interval);
915 _autoReconnectTimer.setInterval(interval * 1000);
918 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
920 Network::setAutoReconnectRetries(retries);
921 if (_autoReconnectCount != 0) {
922 if (unlimitedReconnectRetries())
923 _autoReconnectCount = -1;
925 _autoReconnectCount = autoReconnectRetries();
929 void CoreNetwork::doAutoReconnect()
931 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
932 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
935 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
936 _autoReconnectCount--; // -2 means we delay the next reconnect
940 void CoreNetwork::sendPing()
942 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
943 if (_pingCount != 0) {
944 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
945 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
947 if ((int) _pingCount >= networkConfig()->maxPingCount() && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
948 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
949 // However, to reduce the risk of breaking things by changing past behavior, we still allow
950 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
952 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
953 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
954 // and unable to even handle a ping answer. So we ignore those misses.
955 disconnectFromIrc(false,
956 QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000),
957 true /* withReconnect */);
962 // Don't send pings until the network is initialized
964 // Mark as waiting for a reply
965 _pongReplyPending = true;
966 // Send default timestamp ping
967 userInputHandler()->handlePing(BufferInfo(), QString());
972 void CoreNetwork::enablePingTimeout(bool enable)
975 disablePingTimeout();
978 resetPongReplyPending();
979 if (networkConfig()->pingTimeoutEnabled())
984 void CoreNetwork::disablePingTimeout()
989 resetPongReplyPending();
992 void CoreNetwork::setPingInterval(int interval)
994 _pingTimer.setInterval(interval * 1000);
997 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
999 _pongTimestampValid = validTimestamp;
1002 /******** Custom Rate Limiting ********/
1004 void CoreNetwork::updateRateLimiting(bool forceUnlimited)
1006 // Verify and apply custom rate limiting options, always resetting the delay and burst size
1007 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
1008 // this may be called while connected to a server.
1010 if (useCustomMessageRate() || forceUnlimited) {
1011 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
1013 _messageDelay = messageRateDelay();
1015 _burstSize = messageRateBurstSize();
1016 if (_burstSize < 1) {
1017 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" << _burstSize;
1018 // Can't go slower than one message at a time
1022 if (_tokenBucket > _burstSize) {
1023 // Don't let the token bucket exceed the maximum
1024 _tokenBucket = _burstSize;
1025 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1026 // changing the rate-limit settings while connected to a server will incorrectly reset
1027 // the token bucket.
1030 // Toggle the timer according to whether or not rate limiting is enabled
1031 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1032 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1033 // Override user preferences if called with force unlimited, only used during connect.
1034 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1035 if (_skipMessageRates) {
1036 // If the message queue already contains messages, they need sent before disabling the
1037 // timer. Set the timer to a rapid pace and let it disable itself.
1038 if (!_msgQueue.isEmpty()) {
1039 qDebug() << "Outgoing message queue contains messages while disabling rate "
1040 "limiting. Sending remaining queued messages...";
1041 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1042 // so nothing should cause this to block.. in theory. However, don't directly call
1043 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1045 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1046 // Hesitant to change it without a wide variety of situations to verify behavior.
1047 _tokenBucketTimer.start(100);
1050 // No rate limiting, disable the timer
1051 _tokenBucketTimer.stop();
1055 // Rate limiting enabled, enable the timer
1056 _tokenBucketTimer.start(_messageDelay);
1060 // Custom message rates disabled. Go for the default.
1062 _skipMessageRates = false; // Enable rate-limiting by default
1063 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1064 _burstSize = 5; // 5 messages at once
1065 if (_tokenBucket > _burstSize) {
1066 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1068 _tokenBucket = _burstSize;
1069 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1070 // changing the rate-limit settings while connected to a server will incorrectly reset
1071 // the token bucket.
1073 // Rate limiting enabled, enable the timer
1074 _tokenBucketTimer.start(_messageDelay);
1078 void CoreNetwork::resetTokenBucket()
1080 // Fill up the token bucket to the maximum
1081 _tokenBucket = _burstSize;
1084 /******** IRCv3 Capability Negotiation ********/
1086 void CoreNetwork::serverCapAdded(const QString& capability)
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);
1095 else if (IrcCap::knownCaps.contains(capability)) {
1096 // Handling for general known capabilities
1097 queueCap(capability);
1101 void CoreNetwork::serverCapAcknowledged(const QString& capability)
1103 // This may be called multiple times in certain situations.
1105 // Handle core-side configuration
1106 if (capability == IrcCap::AWAY_NOTIFY) {
1107 // away-notify enabled, stop the autoWho timers, handle manually
1108 setAutoWhoEnabled(false);
1111 // Handle capabilities that require further messages sent to the IRC server
1112 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1113 if (capability == IrcCap::SASL) {
1114 // If SASL mechanisms specified, limit to what's accepted for authentication
1115 // if the current identity has a cert set, use SASL EXTERNAL
1118 if (!identityPtr()->sslCert().isNull()) {
1119 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1120 // EXTERNAL authentication supported, send request
1121 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1124 showMessage(NetworkInternalMessage(
1126 BufferInfo::StatusBuffer,
1128 tr("SASL EXTERNAL authentication not supported")
1135 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1136 // PLAIN authentication supported, send request
1137 // Only working with PLAIN atm, blowfish later
1138 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1141 showMessage(NetworkInternalMessage(
1143 BufferInfo::StatusBuffer,
1145 tr("SASL PLAIN authentication not supported")
1155 void CoreNetwork::serverCapRemoved(const QString& capability)
1157 // This may be called multiple times in certain situations.
1159 // Handle special cases here
1160 if (capability == IrcCap::AWAY_NOTIFY) {
1161 // away-notify disabled, enable autoWho according to configuration
1162 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1166 void CoreNetwork::queueCap(const QString& capability)
1168 // IRCv3 specs all use lowercase capability names
1169 QString _capLowercase = capability.toLower();
1171 if (capsRequiringConfiguration.contains(_capLowercase)) {
1172 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1173 // so we should negotiate it separately from all other capabilities. Otherwise new
1174 // capabilities will be requested while still configuring the previous one.
1175 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1176 _capsQueuedIndividual.append(_capLowercase);
1180 // The capability doesn't need any special configuration, so it should be safe to try
1181 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1183 if (!_capsQueuedBundled.contains(_capLowercase)) {
1184 _capsQueuedBundled.append(_capLowercase);
1189 QString CoreNetwork::takeQueuedCaps()
1191 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1193 _capsQueuedLastBundle.clear();
1195 // First, negotiate all the standalone capabilities that require additional configuration.
1196 if (!_capsQueuedIndividual.empty()) {
1197 // We have an individual capability available. Take the first and pass it back.
1198 return _capsQueuedIndividual.takeFirst();
1200 else if (!_capsQueuedBundled.empty()) {
1201 // We have capabilities available that can be grouped. Try to fit in as many as within the
1203 // See CoreNetwork::maxCapRequestLength
1205 // Response must have at least one capability regardless of max length for anything to
1207 QString capBundle = _capsQueuedBundled.takeFirst();
1208 QString nextCap("");
1209 while (!_capsQueuedBundled.empty()) {
1210 // As long as capabilities remain, get the next...
1211 nextCap = _capsQueuedBundled.first();
1212 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1213 // [capability + 1 for a space + this new capability] fit within length limits
1214 // Add it to formatted list
1215 capBundle.append(" " + nextCap);
1216 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1217 _capsQueuedLastBundle.append(nextCap);
1218 // Then remove it from the queue
1219 _capsQueuedBundled.removeFirst();
1222 // We've reached the length limit for a single capability request, stop adding more
1226 // Return this space-separated set of capabilities, removing any extra spaces
1227 return capBundle.trimmed();
1230 // No capabilities left to negotiate, return an empty string.
1235 void CoreNetwork::retryCapsIndividually()
1237 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1238 // denied, try each capability individually.
1239 if (_capsQueuedLastBundle.empty()) {
1240 // No most recently tried capability set, just return.
1242 // Note: there's little point in retrying individually requested caps during negotiation.
1243 // We know the individual capability was the one that failed, and it's not likely it'll
1244 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1245 // handling capability removal and addition.
1248 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1249 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1250 // keeping track of which halves of the group fail, dividing the set each time.
1252 // Add most recently tried capability set to individual list, re-requesting them one at a time
1253 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1254 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1255 showMessage(NetworkInternalMessage(
1257 BufferInfo::StatusBuffer,
1259 tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", "))
1261 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1262 // need to remove them here.
1263 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1265 _capsQueuedLastBundle.clear();
1268 void CoreNetwork::beginCapNegotiation()
1270 if (!capNegotiationInProgress()) {
1271 // No capabilities are queued for request, determine the reason why
1272 QString capStatusMsg;
1273 if (caps().empty()) {
1274 // The server doesn't provide any capabilities, but supports CAP LS
1275 capStatusMsg = tr("No capabilities available");
1277 else if (capsEnabled().empty()) {
1278 // The server supports capabilities (caps() is not empty) but Quassel doesn't support
1279 // anything offered. This should be uncommon.
1281 tr("None of the capabilities provided by the server are supported (found: %1)")
1282 .arg(caps().join(", "));
1285 // Quassel has enabled some capabilities, but there are no further capabilities that can
1287 // (E.g. the user has manually run "/cap ls 302" after initial negotiation.)
1289 tr("No additional capabilities are supported (found: %1; currently enabled: %2)")
1290 .arg(caps().join(", "), capsEnabled().join(", "));
1292 // Inform the user of the situation
1293 showMessage(NetworkInternalMessage(
1295 BufferInfo::StatusBuffer,
1300 // End any ongoing capability negotiation, allowing connection to continue
1301 endCapNegotiation();
1305 _capNegotiationActive = true;
1306 showMessage(NetworkInternalMessage(
1308 BufferInfo::StatusBuffer,
1310 tr("Ready to negotiate (found: %1)").arg(caps().join(", "))
1313 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1314 // comma separator between the two if needed (both individual and bundled caps exist).
1315 QString queuedCapsDisplay = _capsQueuedIndividual.join(", ")
1316 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1317 + _capsQueuedBundled.join(", ");
1318 showMessage(NetworkInternalMessage(
1320 BufferInfo::StatusBuffer,
1322 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay)
1328 void CoreNetwork::sendNextCap()
1330 if (capNegotiationInProgress()) {
1331 // Request the next set of capabilities and remove them from the list
1332 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1335 // No pending desired capabilities, capability negotiation finished
1336 // If SASL requested but not available, print a warning
1337 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1338 showMessage(NetworkInternalMessage(
1340 BufferInfo::StatusBuffer,
1342 tr("SASL authentication currently not supported by server")
1345 if (_capNegotiationActive) {
1346 showMessage(NetworkInternalMessage(
1348 BufferInfo::StatusBuffer,
1350 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", "))
1352 _capNegotiationActive = false;
1355 endCapNegotiation();
1359 void CoreNetwork::endCapNegotiation()
1361 // If nick registration is already complete, CAP END is not required
1362 if (!_capInitialNegotiationEnded) {
1363 putRawLine(serverEncode(QString("CAP END")));
1364 _capInitialNegotiationEnded = true;
1368 /******** AutoWHO ********/
1370 void CoreNetwork::startAutoWhoCycle()
1372 if (!_autoWhoQueue.isEmpty()) {
1373 _autoWhoCycleTimer.stop();
1376 _autoWhoQueue = channels();
1379 void CoreNetwork::queueAutoWhoOneshot(const QString& name)
1381 // Prepend so these new channels/nicks are the first to be checked
1382 // Don't allow duplicates
1383 if (!_autoWhoQueue.contains(name.toLower())) {
1384 _autoWhoQueue.prepend(name.toLower());
1386 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1387 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1388 setAutoWhoEnabled(true);
1392 void CoreNetwork::setAutoWhoDelay(int delay)
1394 _autoWhoTimer.setInterval(delay * 1000);
1397 void CoreNetwork::setAutoWhoInterval(int interval)
1399 _autoWhoCycleTimer.setInterval(interval * 1000);
1402 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1404 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1405 _autoWhoTimer.start();
1406 else if (!enabled) {
1407 _autoWhoTimer.stop();
1408 _autoWhoCycleTimer.stop();
1412 void CoreNetwork::sendAutoWho()
1414 // Don't send autowho if there are still some pending
1415 if (_autoWhoPending.count())
1418 while (!_autoWhoQueue.isEmpty()) {
1419 QString chanOrNick = _autoWhoQueue.takeFirst();
1420 // Check if it's a known channel or nick
1421 IrcChannel* ircchan = ircChannel(chanOrNick);
1422 IrcUser* ircuser = ircUser(chanOrNick);
1424 // Apply channel limiting rules
1425 // If using away-notify, don't impose channel size limits in order to capture away
1426 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1427 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1428 && !capEnabled(IrcCap::AWAY_NOTIFY))
1430 _autoWhoPending[chanOrNick.toLower()]++;
1433 // Checking a nick, add it to the pending list
1434 _autoWhoPending[ircuser->nick().toLower()]++;
1437 // Not a channel or a nick, skip it
1438 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1441 if (supports("WHOX")) {
1442 // Use WHO extended to poll away users and/or user accounts
1443 // Explicitly only match on nickname ("n"), don't rely on server defaults
1445 // WHO <nickname> n%chtsunfra,<unique_number>
1447 // See http://faerion.sourceforge.net/doc/irc/whox.var
1448 // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1449 // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1450 putRawLine(serverEncode(
1451 QString("WHO %1 n%chtsunfra,%2")
1452 .arg(chanOrNick, QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))
1456 // Fall back to normal WHO
1458 // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1459 // hostmask, etc. There's nothing we can do about that :(
1461 // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1462 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1467 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1468 // Timer was stopped, means a new cycle is due immediately
1469 // Don't run a new cycle if using away-notify; server will notify as appropriate
1470 _autoWhoCycleTimer.start();
1471 startAutoWhoCycle();
1473 else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1474 // Don't run another who cycle if away-notify is enabled
1475 _autoWhoCycleTimer.stop();
1480 void CoreNetwork::onSslErrors(const QList<QSslError>& sslErrors)
1482 Server server = usedServer();
1483 if (server.sslVerify) {
1484 // Treat the SSL error as a hard error
1485 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1486 "since verification is required");
1487 if (!sslErrors.empty()) {
1488 // Add the error reason if known
1489 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1491 showMessage(NetworkInternalMessage(
1493 BufferInfo::StatusBuffer,
1498 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1499 // validity, network trouble, etc.
1500 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1503 // Treat the SSL error as a warning, continue to connect anyways
1504 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1505 "since verification is not required");
1506 if (!sslErrors.empty()) {
1507 // Add the error reason if known
1508 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1510 showMessage(NetworkInternalMessage(
1512 BufferInfo::StatusBuffer,
1517 // Proceed with the connection
1518 socket.ignoreSslErrors();
1524 void CoreNetwork::checkTokenBucket()
1526 if (_skipMessageRates) {
1527 if (_msgQueue.empty()) {
1528 // Message queue emptied; stop the timer and bail out
1529 _tokenBucketTimer.stop();
1532 // Otherwise, we're emptying the queue, continue on as normal
1535 // Process whatever messages are pending
1536 fillBucketAndProcessQueue();
1539 void CoreNetwork::fillBucketAndProcessQueue()
1541 // If there's less tokens than burst size, refill the token bucket by 1
1542 if (_tokenBucket < _burstSize) {
1546 // As long as there's tokens available and messages remaining, sending messages from the queue
1547 while (!_msgQueue.empty() && _tokenBucket > 0) {
1548 writeToSocket(_msgQueue.takeFirst());
1549 if (_metricsServer) {
1550 _metricsServer->messageQueue(userId(), _msgQueue.size());
1555 void CoreNetwork::writeToSocket(const QByteArray& data)
1557 // Log the message if enabled and network ID matches or allows all
1558 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1559 // Include network ID
1560 qDebug() << "IRC net" << networkId() << ">>" << data;
1563 socket.write("\r\n");
1564 if (_metricsServer) {
1565 _metricsServer->transmitDataNetwork(userId(), data.size() + 2);
1567 if (!_skipMessageRates) {
1568 // Only subtract from the token bucket if message rate limiting is enabled
1573 Network::Server CoreNetwork::usedServer() const
1575 if (_lastUsedServerIndex < serverList().count())
1576 return serverList()[_lastUsedServerIndex];
1578 if (!serverList().isEmpty())
1579 return serverList()[0];
1581 return Network::Server();
1584 void CoreNetwork::requestConnect() const
1586 if (_shuttingDown) {
1589 if (connectionState() != Disconnected) {
1590 qWarning() << "Requesting connect while already being connected!";
1593 QMetaObject::invokeMethod(const_cast<CoreNetwork*>(this), "connectToIrc", Qt::QueuedConnection);
1596 void CoreNetwork::requestDisconnect() const
1598 if (_shuttingDown) {
1601 if (connectionState() == Disconnected) {
1602 qWarning() << "Requesting disconnect while not being connected!";
1605 userInputHandler()->handleQuit(BufferInfo(), QString());
1608 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info)
1610 Network::Server currentServer = usedServer();
1611 setNetworkInfo(info);
1612 Core::updateNetwork(coreSession()->user(), info);
1614 // the order of the servers might have changed,
1615 // so we try to find the previously used server
1616 _lastUsedServerIndex = 0;
1617 for (int i = 0; i < serverList().count(); i++) {
1618 Network::Server server = serverList()[i];
1619 if (server.host == currentServer.host && server.port == currentServer.port) {
1620 _lastUsedServerIndex = i;
1626 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString& cmd,
1627 const QString& message,
1628 const std::function<QList<QByteArray>(QString&)>& cmdGenerator)
1630 QString wrkMsg(message);
1631 QList<QList<QByteArray>> msgsToSend;
1633 // do while (wrkMsg.size() > 0)
1635 // First, check to see if the whole message can be sent at once. The
1636 // cmdGenerator function is passed in by the caller and is used to encode
1637 // and encrypt (if applicable) the message, since different callers might
1638 // want to use different encoding or encode different values.
1639 int splitPos = wrkMsg.size();
1640 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1641 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1643 if (initialOverrun) {
1644 // If the message was too long to be sent, first try splitting it along
1645 // word boundaries with QTextBoundaryFinder.
1646 QString splitMsg(wrkMsg);
1647 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1648 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1649 QList<QByteArray> splitMsgEnc;
1650 int overrun = initialOverrun;
1653 splitPos = qtbf.toPreviousBoundary();
1655 // splitPos==-1 means the QTBF couldn't find a split point at all and
1656 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1657 // the string. Neither one of these works for us.
1659 // If a split point could be found, split the message there, calculate the
1660 // overrun, and continue with the loop.
1661 splitMsg = splitMsg.left(splitPos);
1662 splitMsgEnc = cmdGenerator(splitMsg);
1663 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1666 // If a split point could not be found (the beginning of the message
1667 // is reached without finding a split point short enough to send) and we
1668 // are still in Word mode, switch to Grapheme mode. We also need to restore
1669 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1670 // the previous attempt to find a split point.
1671 if (qtbf.type() == QTextBoundaryFinder::Word) {
1673 splitPos = splitMsg.size();
1674 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1675 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1676 qtbf = graphemeQtbf;
1679 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1680 // This should never happen, but it should be handled anyway.
1681 qWarning() << "Unexpected failure to split message!";
1687 // Once a message of sendable length has been found, remove it from the wrkMsg and
1688 // add it to the list of messages to be sent.
1689 wrkMsg.remove(0, splitPos);
1690 msgsToSend.append(splitMsgEnc);
1693 // If the entire remaining message is short enough to be sent all at once, remove
1694 // it from the wrkMsg and add it to the list of messages to be sent.
1695 wrkMsg.remove(0, splitPos);
1696 msgsToSend.append(initialSplitMsgEnc);
1698 } while (wrkMsg.size() > 0);