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);
87 connect(&socket, &QSslSocket::encrypted, this, &CoreNetwork::onSocketInitialized);
88 connect(&socket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &CoreNetwork::onSslErrors);
89 connect(this, &CoreNetwork::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
91 // Custom rate limiting
92 // These react to the user changing settings in the client
93 connect(this, &Network::useCustomMessageRateSet, this, &CoreNetwork::updateRateLimiting);
94 connect(this, &Network::messageRateBurstSizeSet, this, &CoreNetwork::updateRateLimiting);
95 connect(this, &Network::messageRateDelaySet, this, &CoreNetwork::updateRateLimiting);
96 connect(this, &Network::unlimitedMessageRateSet, this, &CoreNetwork::updateRateLimiting);
98 // IRCv3 capability handling
99 // These react to CAP messages from the server
100 connect(this, &Network::capAdded, this, &CoreNetwork::serverCapAdded);
101 connect(this, &Network::capAcknowledged, this, &CoreNetwork::serverCapAcknowledged);
102 connect(this, &Network::capRemoved, this, &CoreNetwork::serverCapRemoved);
104 if (Quassel::isOptionSet("oidentd")) {
105 connect(this, &CoreNetwork::socketInitialized, Core::instance()->oidentdConfigGenerator(), &OidentdConfigGenerator::addSocket);
106 connect(this, &CoreNetwork::socketDisconnected, Core::instance()->oidentdConfigGenerator(), &OidentdConfigGenerator::removeSocket);
109 if (Quassel::isOptionSet("ident-daemon")) {
110 connect(this, &CoreNetwork::socketInitialized, Core::instance()->identServer(), &IdentServer::addSocket);
111 connect(this, &CoreNetwork::socketDisconnected, Core::instance()->identServer(), &IdentServer::removeSocket);
115 CoreNetwork::~CoreNetwork()
117 // Ensure we don't get any more signals from the socket while shutting down
118 disconnect(&socket, nullptr, this, nullptr);
119 if (!forceDisconnect()) {
120 qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
122 .arg(networkId().toInt())
123 .arg(userId().toInt());
127 bool CoreNetwork::forceDisconnect(int msecs)
129 if (socket.state() == QAbstractSocket::UnconnectedState) {
130 // Socket already disconnected.
133 // Request a socket-level disconnect if not already happened
134 socket.disconnectFromHost();
135 if (socket.state() != QAbstractSocket::UnconnectedState) {
136 return socket.waitForDisconnected(msecs);
141 QString CoreNetwork::channelDecode(const QString& bufferName, const QByteArray& string) const
143 if (!bufferName.isEmpty()) {
144 IrcChannel* channel = ircChannel(bufferName);
146 return channel->decodeString(string);
148 return decodeString(string);
151 QString CoreNetwork::userDecode(const QString& userNick, const QByteArray& string) const
153 IrcUser* user = ircUser(userNick);
155 return user->decodeString(string);
156 return decodeString(string);
159 QByteArray CoreNetwork::channelEncode(const QString& bufferName, const QString& string) const
161 if (!bufferName.isEmpty()) {
162 IrcChannel* channel = ircChannel(bufferName);
164 return channel->encodeString(string);
166 return encodeString(string);
169 QByteArray CoreNetwork::userEncode(const QString& userNick, const QString& string) const
171 IrcUser* user = ircUser(userNick);
173 return user->encodeString(string);
174 return encodeString(string);
177 void CoreNetwork::connectToIrc(bool reconnecting)
183 if (Core::instance()->identServer()) {
184 _socketId = Core::instance()->identServer()->addWaitingSocket();
187 if (_metricsServer) {
188 _metricsServer->addNetwork(userId());
191 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
192 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
193 if (unlimitedReconnectRetries())
194 _autoReconnectCount = -1;
196 _autoReconnectCount = autoReconnectRetries();
198 if (serverList().isEmpty()) {
199 qWarning() << "Server list empty, ignoring connect request!";
202 CoreIdentity* identity = identityPtr();
204 qWarning() << "Invalid identity configures, ignoring connect request!";
208 // cleaning up old quit reason
211 // Reset capability negotiation tracking, also handling server changes during reconnect
212 _capsQueuedIndividual.clear();
213 _capsQueuedBundled.clear();
215 _capNegotiationActive = false;
216 _capInitialNegotiationEnded = false;
218 // use a random server?
219 if (useRandomServer()) {
220 _lastUsedServerIndex = qrand() % serverList().size();
222 else if (_previousConnectionAttemptFailed) {
223 // cycle to next server if previous connection attempt failed
224 _previousConnectionAttemptFailed = false;
225 showMessage(NetworkInternalMessage(
227 BufferInfo::StatusBuffer,
229 tr("Connection failed. Cycling to next server...")
231 if (++_lastUsedServerIndex >= serverList().size()) {
232 _lastUsedServerIndex = 0;
236 // Start out with the top server in the list
237 _lastUsedServerIndex = 0;
240 Server server = usedServer();
241 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
242 showMessage(NetworkInternalMessage(
244 BufferInfo::StatusBuffer,
246 tr("Connecting to %1:%2...").arg(server.host).arg(server.port)
249 if (server.useProxy) {
250 QNetworkProxy proxy((QNetworkProxy::ProxyType) server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
251 socket.setProxy(proxy);
254 socket.setProxy(QNetworkProxy::NoProxy);
259 // Reset tracking for valid timestamps in PONG replies
260 setPongTimestampValid(false);
262 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
263 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
264 if (!server.useProxy) {
265 // Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
266 // hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
267 QHostInfo::fromName(server.host);
270 CoreIdentity* identity = identityPtr();
272 socket.setLocalCertificate(identity->sslCert());
273 socket.setPrivateKey(identity->sslKey());
275 socket.connectToHostEncrypted(server.host, server.port);
278 socket.connectToHost(server.host, server.port);
282 void CoreNetwork::disconnectFromIrc(bool requested, const QString& reason, bool withReconnect)
284 // Disconnecting from the network, should expect a socket close or error
285 _disconnectExpected = true;
286 _quitRequested = requested; // see socketDisconnected();
287 if (!withReconnect) {
288 _autoReconnectTimer.stop();
289 _autoReconnectCount = 0; // prohibiting auto reconnect
291 disablePingTimeout();
293 if (_metricsServer) {
294 _metricsServer->messageQueue(userId(), 0);
301 awayMsg = me_->awayMessage();
302 Core::setAwayMessage(userId(), networkId(), awayMsg);
305 if (reason.isEmpty() && identityPtr())
306 _quitReason = identityPtr()->quitReason();
308 _quitReason = reason;
310 showMessage(NetworkInternalMessage(
312 BufferInfo::StatusBuffer,
314 tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason)
316 if (socket.state() == QAbstractSocket::UnconnectedState) {
317 onSocketDisconnected();
320 if (socket.state() == QAbstractSocket::ConnectedState) {
321 // If shutting down, prioritize the QUIT command
322 userInputHandler()->issueQuit(_quitReason, _shuttingDown);
327 if (socket.state() != QAbstractSocket::UnconnectedState) {
328 // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
329 _socketCloseTimer.start(10000);
334 void CoreNetwork::onSocketCloseTimeout()
336 qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
338 .arg(networkId().toInt())
339 .arg(userId().toInt());
343 void CoreNetwork::shutdown()
345 _shuttingDown = true;
346 disconnectFromIrc(false, {}, false);
349 void CoreNetwork::userInput(const BufferInfo& buf, QString msg)
351 userInputHandler()->handleUserInput(buf, msg);
354 void CoreNetwork::putRawLine(const QByteArray& s, bool prepend)
356 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.isEmpty())) {
357 // If there's tokens remaining, ...
358 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
359 // Send the message now.
363 // Otherwise, queue the message for later
365 // Jump to the start, skipping other messages
366 _msgQueue.prepend(s);
369 // Add to back, waiting in order
372 if (_metricsServer) {
373 _metricsServer->messageQueue(userId(), _msgQueue.size());
378 void CoreNetwork::putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString>& tags, bool prepend)
380 putRawLine(IrcEncoder::writeMessage(tags, prefix, cmd, params), prepend);
383 void CoreNetwork::putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString>& tags, bool prependAll)
385 QListIterator<QList<QByteArray>> i(params);
386 while (i.hasNext()) {
387 QList<QByteArray> msg = i.next();
388 putCmd(cmd, msg, prefix, tags, prependAll);
392 void CoreNetwork::setChannelJoined(const QString& channel)
394 queueAutoWhoOneshot(channel); // check this new channel first
396 Core::setChannelPersistent(userId(), networkId(), channel, true);
397 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
400 void CoreNetwork::setChannelParted(const QString& channel)
402 removeChannelKey(channel);
403 _autoWhoQueue.removeAll(channel.toLower());
404 _autoWhoPending.remove(channel.toLower());
406 Core::setChannelPersistent(userId(), networkId(), channel, false);
409 void CoreNetwork::addChannelKey(const QString& channel, const QString& key)
412 removeChannelKey(channel);
415 _channelKeys[channel.toLower()] = key;
419 void CoreNetwork::removeChannelKey(const QString& channel)
421 _channelKeys.remove(channel.toLower());
425 Cipher* CoreNetwork::cipher(const QString& target)
427 if (target.isEmpty())
430 if (!Cipher::neededFeaturesAvailable())
433 auto* channel = qobject_cast<CoreIrcChannel*>(ircChannel(target));
435 return channel->cipher();
437 auto* user = qobject_cast<CoreIrcUser*>(ircUser(target));
439 return user->cipher();
441 else if (!isChannelName(target)) {
442 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
447 QByteArray CoreNetwork::cipherKey(const QString& target) const
449 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
451 return c->cipher()->key();
453 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
455 return u->cipher()->key();
460 void CoreNetwork::setCipherKey(const QString& target, const QByteArray& key)
462 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
464 c->setEncrypted(c->cipher()->setKey(key));
465 coreSession()->setBufferCipher(networkId(), target, key);
469 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
470 if (!u && !isChannelName(target))
471 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
474 u->setEncrypted(u->cipher()->setKey(key));
475 coreSession()->setBufferCipher(networkId(), target, key);
480 bool CoreNetwork::cipherUsesCBC(const QString& target)
482 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
484 return c->cipher()->usesCBC();
485 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
487 return u->cipher()->usesCBC();
491 #endif /* HAVE_QCA2 */
493 bool CoreNetwork::setAutoWhoDone(const QString& name)
495 QString chanOrNick = name.toLower();
496 if (_autoWhoPending.value(chanOrNick, 0) <= 0)
498 if (--_autoWhoPending[chanOrNick] <= 0)
499 _autoWhoPending.remove(chanOrNick);
503 void CoreNetwork::setMyNick(const QString& mynick)
505 Network::setMyNick(mynick);
506 if (connectionState() == Network::Initializing)
507 networkInitialized();
510 void CoreNetwork::onSocketHasData()
512 while (socket.canReadLine()) {
513 QByteArray s = socket.readLine();
514 if (_metricsServer) {
515 _metricsServer->receiveDataNetwork(userId(), s.size());
517 if (s.endsWith("\r\n"))
519 else if (s.endsWith("\n"))
521 NetworkDataEvent* event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
522 event->setTimestamp(QDateTime::currentDateTimeUtc());
523 emit newEvent(event);
527 void CoreNetwork::onSocketError(QAbstractSocket::SocketError error)
529 // Ignore socket closed errors if expected
530 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
534 _previousConnectionAttemptFailed = true;
535 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
536 emit connectionError(socket.errorString());
537 showMessage(NetworkInternalMessage(
539 BufferInfo::StatusBuffer,
541 tr("Connection failure: %1").arg(socket.errorString())
543 emitConnectionError(socket.errorString());
544 if (socket.state() < QAbstractSocket::ConnectedState) {
545 onSocketDisconnected();
549 void CoreNetwork::onSocketInitialized()
551 CoreIdentity* identity = identityPtr();
553 qCritical() << "Identity invalid!";
558 Server server = usedServer();
560 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
561 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
562 if (!server.useSsl || !socket.isEncrypted()) {
563 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
566 if (server.useSsl && !socket.isEncrypted()) {
567 // We'll finish setup once we're encrypted, and called again
571 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
573 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
574 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
575 // force flag to apply user preferences. When making changes, ensure that this still happens!
576 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
577 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
579 updateRateLimiting(true);
580 // Fill up the token bucket as we're connecting from scratch
583 // Request capabilities as per IRCv3.2 specifications
584 // Older servers should ignore this; newer servers won't downgrade to RFC1459
585 showMessage(NetworkInternalMessage(
587 BufferInfo::StatusBuffer,
589 tr("Requesting capability list...")
591 putRawLine(serverEncode(QString("CAP LS 302")));
593 if (!server.password.isEmpty()) {
594 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
597 if (identity->nicks().isEmpty()) {
599 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
602 nick = identity->nicks()[0];
604 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
605 // Only allow strict-compliant idents when strict mode is enabled
606 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(coreSession()->strictCompliantIdent(identity), identity->realName())));
609 void CoreNetwork::onSocketDisconnected()
611 disablePingTimeout();
613 if (_metricsServer) {
614 _metricsServer->messageQueue(userId(), 0);
617 _autoWhoCycleTimer.stop();
618 _autoWhoTimer.stop();
619 _autoWhoQueue.clear();
620 _autoWhoPending.clear();
622 _socketCloseTimer.stop();
624 _tokenBucketTimer.stop();
628 for (const QString& channel : me_->channels()) {
629 showMessage(NetworkInternalMessage(
631 BufferInfo::ChannelBuffer,
633 _quitReason, me_->hostmask()
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);
648 else if (_autoReconnectCount != 0) {
649 setConnectionState(Network::Reconnecting);
650 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
651 doAutoReconnect(); // first try is immediate
653 _autoReconnectTimer.start();
656 if (_metricsServer) {
657 _metricsServer->removeNetwork(userId());
661 void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState)
663 Network::ConnectionState state;
664 switch (socketState) {
665 case QAbstractSocket::UnconnectedState:
666 state = Network::Disconnected;
667 onSocketDisconnected();
669 case QAbstractSocket::HostLookupState:
670 case QAbstractSocket::ConnectingState:
671 state = Network::Connecting;
673 case QAbstractSocket::ConnectedState:
674 state = Network::Initializing;
676 case QAbstractSocket::ClosingState:
677 state = Network::Disconnecting;
680 state = Network::Disconnected;
682 setConnectionState(state);
685 void CoreNetwork::networkInitialized()
687 setConnectionState(Network::Initialized);
689 _disconnectExpected = false;
690 _quitRequested = false;
692 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
693 // flag used for initial registration and capability negotiation.
694 updateRateLimiting();
696 if (useAutoReconnect()) {
698 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
701 // restore away state
702 QString awayMsg = Core::awayMessage(userId(), networkId());
703 if (!awayMsg.isEmpty()) {
704 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
705 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
706 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
713 if (networkConfig()->autoWhoEnabled()) {
714 _autoWhoCycleTimer.start();
715 _autoWhoTimer.start();
716 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
719 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
720 Core::setNetworkConnected(userId(), networkId(), true);
723 void CoreNetwork::sendPerform()
725 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
728 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
729 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
732 // restore old user modes if server default mode is set.
735 if (!me_->userModes().isEmpty()) {
739 connect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
740 connect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
745 for (const QString& line : perform()) {
747 userInput(statusBuf, line);
750 // rejoin channels we've been in
751 if (rejoinChannels()) {
752 QStringList channels, keys;
753 for (const QString& chan : coreSession()->persistentChannels(networkId()).keys()) {
754 QString key = channelKey(chan);
755 if (!key.isEmpty()) {
756 channels.prepend(chan);
760 channels.append(chan);
763 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
764 if (!joinString.isEmpty())
765 userInputHandler()->handleJoin(statusBuf, joinString);
769 void CoreNetwork::restoreUserModes()
774 disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
775 disconnect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
777 QString modesDelta = Core::userModes(userId(), networkId());
778 QString currentModes = me_->userModes();
780 QString addModes, removeModes;
781 if (modesDelta.contains('-')) {
782 addModes = modesDelta.section('-', 0, 0);
783 removeModes = modesDelta.section('-', 1);
786 addModes = modesDelta;
789 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
790 if (currentModes.isEmpty())
791 removeModes = QString();
793 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
795 if (addModes.isEmpty() && removeModes.isEmpty())
798 if (!addModes.isEmpty())
799 addModes = '+' + addModes;
800 if (!removeModes.isEmpty())
801 removeModes = '-' + removeModes;
803 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
804 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
807 void CoreNetwork::updateIssuedModes(const QString& requestedModes)
813 for (auto requestedMode : requestedModes) {
814 if (requestedMode == '+') {
818 if (requestedMode == '-') {
823 addModes += requestedMode;
826 removeModes += requestedMode;
830 QString addModesOld = _requestedUserModes.section('-', 0, 0);
831 QString removeModesOld = _requestedUserModes.section('-', 1);
833 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
834 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
835 addModes += addModesOld;
837 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
838 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
839 removeModes += removeModesOld;
841 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
844 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
846 QString persistentUserModes = Core::userModes(userId(), networkId());
848 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
849 QString requestedRemove = _requestedUserModes.section('-', 1);
851 QString persistentAdd, persistentRemove;
852 if (persistentUserModes.contains('-')) {
853 persistentAdd = persistentUserModes.section('-', 0, 0);
854 persistentRemove = persistentUserModes.section('-', 1);
857 persistentAdd = persistentUserModes;
860 // remove modes we didn't issue
861 if (requestedAdd.isEmpty())
862 addModes = QString();
864 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
866 if (requestedRemove.isEmpty())
867 removeModes = QString();
869 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
872 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
873 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
876 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
877 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
879 // update issued mode list
880 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
881 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
882 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
884 persistentAdd += addModes;
885 persistentRemove += removeModes;
886 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
889 void CoreNetwork::resetPersistentModes()
891 _requestedUserModes = QString('-');
892 Core::setUserModes(userId(), networkId(), QString());
895 void CoreNetwork::setUseAutoReconnect(bool use)
897 Network::setUseAutoReconnect(use);
899 _autoReconnectTimer.stop();
902 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
904 Network::setAutoReconnectInterval(interval);
905 _autoReconnectTimer.setInterval(interval * 1000);
908 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
910 Network::setAutoReconnectRetries(retries);
911 if (_autoReconnectCount != 0) {
912 if (unlimitedReconnectRetries())
913 _autoReconnectCount = -1;
915 _autoReconnectCount = autoReconnectRetries();
919 void CoreNetwork::doAutoReconnect()
921 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
922 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
925 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
926 _autoReconnectCount--; // -2 means we delay the next reconnect
930 void CoreNetwork::sendPing()
932 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
933 if (_pingCount != 0) {
934 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
935 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
937 if ((int) _pingCount >= networkConfig()->maxPingCount() && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
938 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
939 // However, to reduce the risk of breaking things by changing past behavior, we still allow
940 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
942 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
943 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
944 // and unable to even handle a ping answer. So we ignore those misses.
945 disconnectFromIrc(false,
946 QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000),
947 true /* withReconnect */);
952 // Don't send pings until the network is initialized
954 // Mark as waiting for a reply
955 _pongReplyPending = true;
956 // Send default timestamp ping
957 userInputHandler()->handlePing(BufferInfo(), QString());
962 void CoreNetwork::enablePingTimeout(bool enable)
965 disablePingTimeout();
968 resetPongReplyPending();
969 if (networkConfig()->pingTimeoutEnabled())
974 void CoreNetwork::disablePingTimeout()
979 resetPongReplyPending();
982 void CoreNetwork::setPingInterval(int interval)
984 _pingTimer.setInterval(interval * 1000);
987 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
989 _pongTimestampValid = validTimestamp;
992 /******** Custom Rate Limiting ********/
994 void CoreNetwork::updateRateLimiting(bool forceUnlimited)
996 // Verify and apply custom rate limiting options, always resetting the delay and burst size
997 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
998 // this may be called while connected to a server.
1000 if (useCustomMessageRate() || forceUnlimited) {
1001 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
1003 _messageDelay = messageRateDelay();
1005 _burstSize = messageRateBurstSize();
1006 if (_burstSize < 1) {
1007 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" << _burstSize;
1008 // Can't go slower than one message at a time
1012 if (_tokenBucket > _burstSize) {
1013 // Don't let the token bucket exceed the maximum
1014 _tokenBucket = _burstSize;
1015 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1016 // changing the rate-limit settings while connected to a server will incorrectly reset
1017 // the token bucket.
1020 // Toggle the timer according to whether or not rate limiting is enabled
1021 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1022 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1023 // Override user preferences if called with force unlimited, only used during connect.
1024 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1025 if (_skipMessageRates) {
1026 // If the message queue already contains messages, they need sent before disabling the
1027 // timer. Set the timer to a rapid pace and let it disable itself.
1028 if (!_msgQueue.isEmpty()) {
1029 qDebug() << "Outgoing message queue contains messages while disabling rate "
1030 "limiting. Sending remaining queued messages...";
1031 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1032 // so nothing should cause this to block.. in theory. However, don't directly call
1033 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1035 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1036 // Hesitant to change it without a wide variety of situations to verify behavior.
1037 _tokenBucketTimer.start(100);
1040 // No rate limiting, disable the timer
1041 _tokenBucketTimer.stop();
1045 // Rate limiting enabled, enable the timer
1046 _tokenBucketTimer.start(_messageDelay);
1050 // Custom message rates disabled. Go for the default.
1052 _skipMessageRates = false; // Enable rate-limiting by default
1053 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1054 _burstSize = 5; // 5 messages at once
1055 if (_tokenBucket > _burstSize) {
1056 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1058 _tokenBucket = _burstSize;
1059 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1060 // changing the rate-limit settings while connected to a server will incorrectly reset
1061 // the token bucket.
1063 // Rate limiting enabled, enable the timer
1064 _tokenBucketTimer.start(_messageDelay);
1068 void CoreNetwork::resetTokenBucket()
1070 // Fill up the token bucket to the maximum
1071 _tokenBucket = _burstSize;
1074 /******** IRCv3 Capability Negotiation ********/
1076 void CoreNetwork::serverCapAdded(const QString& capability)
1078 // Check if it's a known capability; if so, add it to the list
1079 // Handle special cases first
1080 if (capability == IrcCap::SASL) {
1081 // Only request SASL if it's enabled
1082 if (networkInfo().useSasl)
1083 queueCap(capability);
1085 else if (IrcCap::knownCaps.contains(capability)) {
1086 // Handling for general known capabilities
1087 queueCap(capability);
1091 void CoreNetwork::serverCapAcknowledged(const QString& capability)
1093 // This may be called multiple times in certain situations.
1095 // Handle core-side configuration
1096 if (capability == IrcCap::AWAY_NOTIFY) {
1097 // away-notify enabled, stop the autoWho timers, handle manually
1098 setAutoWhoEnabled(false);
1101 // Handle capabilities that require further messages sent to the IRC server
1102 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1103 if (capability == IrcCap::SASL) {
1104 // If SASL mechanisms specified, limit to what's accepted for authentication
1105 // if the current identity has a cert set, use SASL EXTERNAL
1107 if (!identityPtr()->sslCert().isNull()) {
1108 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1109 // EXTERNAL authentication supported, send request
1110 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1113 showMessage(NetworkInternalMessage(
1115 BufferInfo::StatusBuffer,
1117 tr("SASL EXTERNAL authentication not supported")
1123 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1124 // PLAIN authentication supported, send request
1125 // Only working with PLAIN atm, blowfish later
1126 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1129 showMessage(NetworkInternalMessage(
1131 BufferInfo::StatusBuffer,
1133 tr("SASL PLAIN authentication not supported")
1141 void CoreNetwork::serverCapRemoved(const QString& capability)
1143 // This may be called multiple times in certain situations.
1145 // Handle special cases here
1146 if (capability == IrcCap::AWAY_NOTIFY) {
1147 // away-notify disabled, enable autoWho according to configuration
1148 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1152 void CoreNetwork::queueCap(const QString& capability)
1154 // IRCv3 specs all use lowercase capability names
1155 QString _capLowercase = capability.toLower();
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);
1166 // The capability doesn't need any special configuration, so it should be safe to try
1167 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1169 if (!_capsQueuedBundled.contains(_capLowercase)) {
1170 _capsQueuedBundled.append(_capLowercase);
1175 QString CoreNetwork::takeQueuedCaps()
1177 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1179 _capsQueuedLastBundle.clear();
1181 // First, negotiate all the standalone capabilities that require additional configuration.
1182 if (!_capsQueuedIndividual.empty()) {
1183 // We have an individual capability available. Take the first and pass it back.
1184 return _capsQueuedIndividual.takeFirst();
1186 else if (!_capsQueuedBundled.empty()) {
1187 // We have capabilities available that can be grouped. Try to fit in as many as within the
1189 // See CoreNetwork::maxCapRequestLength
1191 // Response must have at least one capability regardless of max length for anything to
1193 QString capBundle = _capsQueuedBundled.takeFirst();
1194 QString nextCap("");
1195 while (!_capsQueuedBundled.empty()) {
1196 // As long as capabilities remain, get the next...
1197 nextCap = _capsQueuedBundled.first();
1198 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1199 // [capability + 1 for a space + this new capability] fit within length limits
1200 // Add it to formatted list
1201 capBundle.append(" " + nextCap);
1202 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1203 _capsQueuedLastBundle.append(nextCap);
1204 // Then remove it from the queue
1205 _capsQueuedBundled.removeFirst();
1208 // We've reached the length limit for a single capability request, stop adding more
1212 // Return this space-separated set of capabilities, removing any extra spaces
1213 return capBundle.trimmed();
1216 // No capabilities left to negotiate, return an empty string.
1221 void CoreNetwork::retryCapsIndividually()
1223 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1224 // denied, try each capability individually.
1225 if (_capsQueuedLastBundle.empty()) {
1226 // No most recently tried capability set, just return.
1228 // Note: there's little point in retrying individually requested caps during negotiation.
1229 // We know the individual capability was the one that failed, and it's not likely it'll
1230 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1231 // handling capability removal and addition.
1234 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1235 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1236 // keeping track of which halves of the group fail, dividing the set each time.
1238 // Add most recently tried capability set to individual list, re-requesting them one at a time
1239 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1240 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1241 showMessage(NetworkInternalMessage(
1243 BufferInfo::StatusBuffer,
1245 tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", "))
1247 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1248 // need to remove them here.
1249 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1251 _capsQueuedLastBundle.clear();
1254 void CoreNetwork::beginCapNegotiation()
1256 if (!capsPendingNegotiation()) {
1257 // No capabilities are queued for request, determine the reason why
1258 QString capStatusMsg;
1259 if (caps().empty()) {
1260 // The server doesn't provide any capabilities, but supports CAP LS
1261 capStatusMsg = tr("No capabilities available");
1263 else if (capsEnabled().empty()) {
1264 // The server supports capabilities (caps() is not empty) but Quassel doesn't support
1265 // anything offered. This should be uncommon.
1267 tr("None of the capabilities provided by the server are supported (found: %1)")
1268 .arg(caps().join(", "));
1271 // Quassel has enabled some capabilities, but there are no further capabilities that can
1273 // (E.g. the user has manually run "/cap ls 302" after initial negotiation.)
1275 tr("No additional capabilities are supported (found: %1; currently enabled: %2)")
1276 .arg(caps().join(", "), capsEnabled().join(", "));
1278 // Inform the user of the situation
1279 showMessage(NetworkInternalMessage(
1281 BufferInfo::StatusBuffer,
1286 // End any ongoing capability negotiation, allowing connection to continue
1287 endCapNegotiation();
1291 _capNegotiationActive = true;
1292 showMessage(NetworkInternalMessage(
1294 BufferInfo::StatusBuffer,
1296 tr("Ready to negotiate (found: %1)").arg(caps().join(", "))
1299 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1300 // comma separator between the two if needed (both individual and bundled caps exist).
1301 QString queuedCapsDisplay = _capsQueuedIndividual.join(", ")
1302 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1303 + _capsQueuedBundled.join(", ");
1304 showMessage(NetworkInternalMessage(
1306 BufferInfo::StatusBuffer,
1308 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay)
1314 void CoreNetwork::sendNextCap()
1316 if (capsPendingNegotiation()) {
1317 // Request the next set of capabilities and remove them from the list
1318 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1321 // No pending desired capabilities, capability negotiation finished
1322 // If SASL requested but not available, print a warning
1323 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1324 showMessage(NetworkInternalMessage(
1326 BufferInfo::StatusBuffer,
1328 tr("SASL authentication currently not supported by server")
1331 if (_capNegotiationActive) {
1332 showMessage(NetworkInternalMessage(
1334 BufferInfo::StatusBuffer,
1336 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", "))
1338 _capNegotiationActive = false;
1341 endCapNegotiation();
1345 void CoreNetwork::endCapNegotiation()
1347 // If nick registration is already complete, CAP END is not required
1348 if (!_capInitialNegotiationEnded) {
1349 putRawLine(serverEncode(QString("CAP END")));
1350 _capInitialNegotiationEnded = true;
1354 /******** AutoWHO ********/
1356 void CoreNetwork::startAutoWhoCycle()
1358 if (!_autoWhoQueue.isEmpty()) {
1359 _autoWhoCycleTimer.stop();
1362 _autoWhoQueue = channels();
1365 void CoreNetwork::queueAutoWhoOneshot(const QString& name)
1367 // Prepend so these new channels/nicks are the first to be checked
1368 // Don't allow duplicates
1369 if (!_autoWhoQueue.contains(name.toLower())) {
1370 _autoWhoQueue.prepend(name.toLower());
1372 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1373 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1374 setAutoWhoEnabled(true);
1378 void CoreNetwork::setAutoWhoDelay(int delay)
1380 _autoWhoTimer.setInterval(delay * 1000);
1383 void CoreNetwork::setAutoWhoInterval(int interval)
1385 _autoWhoCycleTimer.setInterval(interval * 1000);
1388 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1390 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1391 _autoWhoTimer.start();
1392 else if (!enabled) {
1393 _autoWhoTimer.stop();
1394 _autoWhoCycleTimer.stop();
1398 void CoreNetwork::sendAutoWho()
1400 // Don't send autowho if there are still some pending
1401 if (_autoWhoPending.count())
1404 while (!_autoWhoQueue.isEmpty()) {
1405 QString chanOrNick = _autoWhoQueue.takeFirst();
1406 // Check if it's a known channel or nick
1407 IrcChannel* ircchan = ircChannel(chanOrNick);
1408 IrcUser* ircuser = ircUser(chanOrNick);
1410 // Apply channel limiting rules
1411 // If using away-notify, don't impose channel size limits in order to capture away
1412 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1413 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1414 && !capEnabled(IrcCap::AWAY_NOTIFY))
1416 _autoWhoPending[chanOrNick.toLower()]++;
1419 // Checking a nick, add it to the pending list
1420 _autoWhoPending[ircuser->nick().toLower()]++;
1423 // Not a channel or a nick, skip it
1424 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1427 if (supports("WHOX")) {
1428 // Use WHO extended to poll away users and/or user accounts
1429 // Explicitly only match on nickname ("n"), don't rely on server defaults
1431 // WHO <nickname> n%chtsunfra,<unique_number>
1433 // See http://faerion.sourceforge.net/doc/irc/whox.var
1434 // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1435 // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1436 putRawLine(serverEncode(
1437 QString("WHO %1 n%chtsunfra,%2")
1438 .arg(chanOrNick, QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))
1442 // Fall back to normal WHO
1444 // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1445 // hostmask, etc. There's nothing we can do about that :(
1447 // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1448 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1453 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1454 // Timer was stopped, means a new cycle is due immediately
1455 // Don't run a new cycle if using away-notify; server will notify as appropriate
1456 _autoWhoCycleTimer.start();
1457 startAutoWhoCycle();
1459 else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1460 // Don't run another who cycle if away-notify is enabled
1461 _autoWhoCycleTimer.stop();
1465 void CoreNetwork::onSslErrors(const QList<QSslError>& sslErrors)
1467 Server server = usedServer();
1468 if (server.sslVerify) {
1469 // Treat the SSL error as a hard error
1470 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1471 "since verification is required");
1472 if (!sslErrors.empty()) {
1473 // Add the error reason if known
1474 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1476 showMessage(NetworkInternalMessage(
1478 BufferInfo::StatusBuffer,
1483 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1484 // validity, network trouble, etc.
1485 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1488 // Treat the SSL error as a warning, continue to connect anyways
1489 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1490 "since verification is not required");
1491 if (!sslErrors.empty()) {
1492 // Add the error reason if known
1493 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1495 showMessage(NetworkInternalMessage(
1497 BufferInfo::StatusBuffer,
1502 // Proceed with the connection
1503 socket.ignoreSslErrors();
1507 void CoreNetwork::checkTokenBucket()
1509 if (_skipMessageRates) {
1510 if (_msgQueue.empty()) {
1511 // Message queue emptied; stop the timer and bail out
1512 _tokenBucketTimer.stop();
1515 // Otherwise, we're emptying the queue, continue on as normal
1518 // Process whatever messages are pending
1519 fillBucketAndProcessQueue();
1522 void CoreNetwork::fillBucketAndProcessQueue()
1524 // If there's less tokens than burst size, refill the token bucket by 1
1525 if (_tokenBucket < _burstSize) {
1529 // As long as there's tokens available and messages remaining, sending messages from the queue
1530 while (!_msgQueue.empty() && _tokenBucket > 0) {
1531 writeToSocket(_msgQueue.takeFirst());
1532 if (_metricsServer) {
1533 _metricsServer->messageQueue(userId(), _msgQueue.size());
1538 void CoreNetwork::writeToSocket(const QByteArray& data)
1540 // Log the message if enabled and network ID matches or allows all
1541 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1542 // Include network ID
1543 qDebug() << "IRC net" << networkId() << ">>" << data;
1546 socket.write("\r\n");
1547 if (_metricsServer) {
1548 _metricsServer->transmitDataNetwork(userId(), data.size() + 2);
1550 if (!_skipMessageRates) {
1551 // Only subtract from the token bucket if message rate limiting is enabled
1556 Network::Server CoreNetwork::usedServer() const
1558 if (_lastUsedServerIndex < serverList().count())
1559 return serverList()[_lastUsedServerIndex];
1561 if (!serverList().isEmpty())
1562 return serverList()[0];
1564 return Network::Server();
1567 void CoreNetwork::requestConnect() const
1569 if (_shuttingDown) {
1572 if (connectionState() != Disconnected) {
1573 qWarning() << "Requesting connect while already being connected!";
1576 QMetaObject::invokeMethod(const_cast<CoreNetwork*>(this), "connectToIrc", Qt::QueuedConnection);
1579 void CoreNetwork::requestDisconnect() const
1581 if (_shuttingDown) {
1584 if (connectionState() == Disconnected) {
1585 qWarning() << "Requesting disconnect while not being connected!";
1588 userInputHandler()->handleQuit(BufferInfo(), QString());
1591 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info)
1593 Network::Server currentServer = usedServer();
1594 setNetworkInfo(info);
1595 Core::updateNetwork(coreSession()->user(), info);
1597 // the order of the servers might have changed,
1598 // so we try to find the previously used server
1599 _lastUsedServerIndex = 0;
1600 for (int i = 0; i < serverList().count(); i++) {
1601 Network::Server server = serverList()[i];
1602 if (server.host == currentServer.host && server.port == currentServer.port) {
1603 _lastUsedServerIndex = i;
1609 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString& cmd,
1610 const QString& message,
1611 const std::function<QList<QByteArray>(QString&)>& cmdGenerator)
1613 QString wrkMsg(message);
1614 QList<QList<QByteArray>> msgsToSend;
1616 // do while (wrkMsg.size() > 0)
1618 // First, check to see if the whole message can be sent at once. The
1619 // cmdGenerator function is passed in by the caller and is used to encode
1620 // and encrypt (if applicable) the message, since different callers might
1621 // want to use different encoding or encode different values.
1622 int splitPos = wrkMsg.size();
1623 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1624 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1626 if (initialOverrun) {
1627 // If the message was too long to be sent, first try splitting it along
1628 // word boundaries with QTextBoundaryFinder.
1629 QString splitMsg(wrkMsg);
1630 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1631 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1632 QList<QByteArray> splitMsgEnc;
1633 int overrun = initialOverrun;
1636 splitPos = qtbf.toPreviousBoundary();
1638 // splitPos==-1 means the QTBF couldn't find a split point at all and
1639 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1640 // the string. Neither one of these works for us.
1642 // If a split point could be found, split the message there, calculate the
1643 // overrun, and continue with the loop.
1644 splitMsg = splitMsg.left(splitPos);
1645 splitMsgEnc = cmdGenerator(splitMsg);
1646 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1649 // If a split point could not be found (the beginning of the message
1650 // is reached without finding a split point short enough to send) and we
1651 // are still in Word mode, switch to Grapheme mode. We also need to restore
1652 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1653 // the previous attempt to find a split point.
1654 if (qtbf.type() == QTextBoundaryFinder::Word) {
1656 splitPos = splitMsg.size();
1657 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1658 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1659 qtbf = graphemeQtbf;
1662 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1663 // This should never happen, but it should be handled anyway.
1664 qWarning() << "Unexpected failure to split message!";
1670 // Once a message of sendable length has been found, remove it from the wrkMsg and
1671 // add it to the list of messages to be sent.
1672 wrkMsg.remove(0, splitPos);
1673 msgsToSend.append(splitMsgEnc);
1676 // If the entire remaining message is short enough to be sent all at once, remove
1677 // it from the wrkMsg and add it to the list of messages to be sent.
1678 wrkMsg.remove(0, splitPos);
1679 msgsToSend.append(initialSplitMsgEnc);
1681 } while (wrkMsg.size() > 0);