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"
27 #include <QTextBoundaryFinder>
30 #include "coreidentity.h"
31 #include "corenetworkconfig.h"
32 #include "coresession.h"
33 #include "coreuserinputhandler.h"
34 #include "ircencoder.h"
37 #include "networkevent.h"
39 CoreNetwork::CoreNetwork(const NetworkId& networkid, CoreSession* session)
40 : Network(networkid, session)
41 , _coreSession(session)
42 , _userInputHandler(new CoreUserInputHandler(this))
43 , _metricsServer(Core::instance()->metricsServer())
44 , _autoReconnectCount(0)
45 , _quitRequested(false)
46 , _disconnectExpected(false)
47 , _previousConnectionAttemptFailed(false)
48 , _lastUsedServerIndex(0)
49 , _requestedUserModes('-')
51 // Check if raw IRC logging is enabled
52 _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
53 _debugLogRawNetId = Quassel::optionValue("debug-irc-id").toInt();
55 _autoReconnectTimer.setSingleShot(true);
56 connect(&_socketCloseTimer, &QTimer::timeout, this, &CoreNetwork::onSocketCloseTimeout);
58 setPingInterval(networkConfig()->pingInterval());
59 connect(&_pingTimer, &QTimer::timeout, this, &CoreNetwork::sendPing);
61 setAutoWhoDelay(networkConfig()->autoWhoDelay());
62 setAutoWhoInterval(networkConfig()->autoWhoInterval());
64 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
65 for (const QString& chan : channels.keys()) {
66 _channelKeys[chan.toLower()] = channels[chan];
69 QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
70 for (const QString& buffer : bufferCiphers.keys()) {
71 storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
74 connect(networkConfig(), &NetworkConfig::pingTimeoutEnabledSet, this, &CoreNetwork::enablePingTimeout);
75 connect(networkConfig(), &NetworkConfig::pingIntervalSet, this, &CoreNetwork::setPingInterval);
76 connect(networkConfig(), &NetworkConfig::autoWhoEnabledSet, this, &CoreNetwork::setAutoWhoEnabled);
77 connect(networkConfig(), &NetworkConfig::autoWhoIntervalSet, this, &CoreNetwork::setAutoWhoInterval);
78 connect(networkConfig(), &NetworkConfig::autoWhoDelaySet, this, &CoreNetwork::setAutoWhoDelay);
80 connect(&_autoReconnectTimer, &QTimer::timeout, this, &CoreNetwork::doAutoReconnect);
81 connect(&_autoWhoTimer, &QTimer::timeout, this, &CoreNetwork::sendAutoWho);
82 connect(&_autoWhoCycleTimer, &QTimer::timeout, this, &CoreNetwork::startAutoWhoCycle);
83 connect(&_tokenBucketTimer, &QTimer::timeout, this, &CoreNetwork::checkTokenBucket);
85 connect(&socket, &QAbstractSocket::connected, this, &CoreNetwork::onSocketInitialized);
86 connect(&socket, selectOverload<QAbstractSocket::SocketError>(&QAbstractSocket::error), this, &CoreNetwork::onSocketError);
87 connect(&socket, &QAbstractSocket::stateChanged, this, &CoreNetwork::onSocketStateChanged);
88 connect(&socket, &QIODevice::readyRead, this, &CoreNetwork::onSocketHasData);
89 connect(&socket, &QSslSocket::encrypted, this, &CoreNetwork::onSocketInitialized);
90 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);
272 CoreIdentity* identity = identityPtr();
274 socket.setLocalCertificate(identity->sslCert());
275 socket.setPrivateKey(identity->sslKey());
277 socket.connectToHostEncrypted(server.host, server.port);
280 socket.connectToHost(server.host, server.port);
284 void CoreNetwork::disconnectFromIrc(bool requested, const QString& reason, bool withReconnect)
286 // Disconnecting from the network, should expect a socket close or error
287 _disconnectExpected = true;
288 _quitRequested = requested; // see socketDisconnected();
289 if (!withReconnect) {
290 _autoReconnectTimer.stop();
291 _autoReconnectCount = 0; // prohibiting auto reconnect
293 disablePingTimeout();
295 if (_metricsServer) {
296 _metricsServer->messageQueue(userId(), 0);
303 awayMsg = me_->awayMessage();
304 Core::setAwayMessage(userId(), networkId(), awayMsg);
307 if (reason.isEmpty() && identityPtr())
308 _quitReason = identityPtr()->quitReason();
310 _quitReason = reason;
312 showMessage(NetworkInternalMessage(
314 BufferInfo::StatusBuffer,
316 tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason)
318 if (socket.state() == QAbstractSocket::UnconnectedState) {
319 onSocketDisconnected();
322 if (socket.state() == QAbstractSocket::ConnectedState) {
323 // If shutting down, prioritize the QUIT command
324 userInputHandler()->issueQuit(_quitReason, _shuttingDown);
329 if (socket.state() != QAbstractSocket::UnconnectedState) {
330 // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
331 _socketCloseTimer.start(10000);
336 void CoreNetwork::onSocketCloseTimeout()
338 qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
340 .arg(networkId().toInt())
341 .arg(userId().toInt());
345 void CoreNetwork::shutdown()
347 _shuttingDown = true;
348 disconnectFromIrc(false, {}, false);
351 void CoreNetwork::userInput(const BufferInfo& buf, QString msg)
353 userInputHandler()->handleUserInput(buf, msg);
356 void CoreNetwork::putRawLine(const QByteArray& s, bool prepend)
358 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.isEmpty())) {
359 // If there's tokens remaining, ...
360 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
361 // Send the message now.
365 // Otherwise, queue the message for later
367 // Jump to the start, skipping other messages
368 _msgQueue.prepend(s);
371 // Add to back, waiting in order
374 if (_metricsServer) {
375 _metricsServer->messageQueue(userId(), _msgQueue.size());
380 void CoreNetwork::putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString>& tags, bool prepend)
382 putRawLine(IrcEncoder::writeMessage(tags, prefix, cmd, params), prepend);
385 void CoreNetwork::putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString>& tags, bool prependAll)
387 QListIterator<QList<QByteArray>> i(params);
388 while (i.hasNext()) {
389 QList<QByteArray> msg = i.next();
390 putCmd(cmd, msg, prefix, tags, prependAll);
394 void CoreNetwork::setChannelJoined(const QString& channel)
396 queueAutoWhoOneshot(channel); // check this new channel first
398 Core::setChannelPersistent(userId(), networkId(), channel, true);
399 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
402 void CoreNetwork::setChannelParted(const QString& channel)
404 removeChannelKey(channel);
405 _autoWhoQueue.removeAll(channel.toLower());
406 _autoWhoPending.remove(channel.toLower());
408 Core::setChannelPersistent(userId(), networkId(), channel, false);
411 void CoreNetwork::addChannelKey(const QString& channel, const QString& key)
414 removeChannelKey(channel);
417 _channelKeys[channel.toLower()] = key;
421 void CoreNetwork::removeChannelKey(const QString& channel)
423 _channelKeys.remove(channel.toLower());
427 Cipher* CoreNetwork::cipher(const QString& target)
429 if (target.isEmpty())
432 if (!Cipher::neededFeaturesAvailable())
435 auto* channel = qobject_cast<CoreIrcChannel*>(ircChannel(target));
437 return channel->cipher();
439 auto* user = qobject_cast<CoreIrcUser*>(ircUser(target));
441 return user->cipher();
443 else if (!isChannelName(target)) {
444 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
449 QByteArray CoreNetwork::cipherKey(const QString& target) const
451 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
453 return c->cipher()->key();
455 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
457 return u->cipher()->key();
462 void CoreNetwork::setCipherKey(const QString& target, const QByteArray& key)
464 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
466 c->setEncrypted(c->cipher()->setKey(key));
467 coreSession()->setBufferCipher(networkId(), target, key);
471 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
472 if (!u && !isChannelName(target))
473 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
476 u->setEncrypted(u->cipher()->setKey(key));
477 coreSession()->setBufferCipher(networkId(), target, key);
482 bool CoreNetwork::cipherUsesCBC(const QString& target)
484 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
486 return c->cipher()->usesCBC();
487 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
489 return u->cipher()->usesCBC();
493 #endif /* HAVE_QCA2 */
495 bool CoreNetwork::setAutoWhoDone(const QString& name)
497 QString chanOrNick = name.toLower();
498 if (_autoWhoPending.value(chanOrNick, 0) <= 0)
500 if (--_autoWhoPending[chanOrNick] <= 0)
501 _autoWhoPending.remove(chanOrNick);
505 void CoreNetwork::setMyNick(const QString& mynick)
507 Network::setMyNick(mynick);
508 if (connectionState() == Network::Initializing)
509 networkInitialized();
512 void CoreNetwork::onSocketHasData()
514 while (socket.canReadLine()) {
515 QByteArray s = socket.readLine();
516 if (_metricsServer) {
517 _metricsServer->receiveDataNetwork(userId(), s.size());
519 if (s.endsWith("\r\n"))
521 else if (s.endsWith("\n"))
523 NetworkDataEvent* event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
524 event->setTimestamp(QDateTime::currentDateTimeUtc());
525 emit newEvent(event);
529 void CoreNetwork::onSocketError(QAbstractSocket::SocketError error)
531 // Ignore socket closed errors if expected
532 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
536 _previousConnectionAttemptFailed = true;
537 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
538 emit connectionError(socket.errorString());
539 showMessage(NetworkInternalMessage(
541 BufferInfo::StatusBuffer,
543 tr("Connection failure: %1").arg(socket.errorString())
545 emitConnectionError(socket.errorString());
546 if (socket.state() < QAbstractSocket::ConnectedState) {
547 onSocketDisconnected();
551 void CoreNetwork::onSocketInitialized()
553 CoreIdentity* identity = identityPtr();
555 qCritical() << "Identity invalid!";
560 Server server = usedServer();
562 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
563 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
564 if (!server.useSsl || !socket.isEncrypted()) {
565 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
568 if (server.useSsl && !socket.isEncrypted()) {
569 // We'll finish setup once we're encrypted, and called again
573 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
575 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
576 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
577 // force flag to apply user preferences. When making changes, ensure that this still happens!
578 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
579 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
581 updateRateLimiting(true);
582 // Fill up the token bucket as we're connecting from scratch
585 // Request capabilities as per IRCv3.2 specifications
586 // Older servers should ignore this; newer servers won't downgrade to RFC1459
587 showMessage(NetworkInternalMessage(
589 BufferInfo::StatusBuffer,
591 tr("Requesting capability list...")
593 putRawLine(serverEncode(QString("CAP LS 302")));
595 if (!server.password.isEmpty()) {
596 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
599 if (identity->nicks().isEmpty()) {
601 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
604 nick = identity->nicks()[0];
606 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
607 // Only allow strict-compliant idents when strict mode is enabled
608 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(coreSession()->strictCompliantIdent(identity), identity->realName())));
611 void CoreNetwork::onSocketDisconnected()
613 disablePingTimeout();
615 if (_metricsServer) {
616 _metricsServer->messageQueue(userId(), 0);
619 _autoWhoCycleTimer.stop();
620 _autoWhoTimer.stop();
621 _autoWhoQueue.clear();
622 _autoWhoPending.clear();
624 _socketCloseTimer.stop();
626 _tokenBucketTimer.stop();
630 for (const QString& channel : me_->channels()) {
631 showMessage(NetworkInternalMessage(
633 BufferInfo::ChannelBuffer,
635 _quitReason, me_->hostmask()
641 emit disconnected(networkId());
642 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
643 // Reset disconnect expectations
644 _disconnectExpected = false;
645 if (_quitRequested) {
646 _quitRequested = false;
647 setConnectionState(Network::Disconnected);
648 Core::setNetworkConnected(userId(), networkId(), false);
650 else if (_autoReconnectCount != 0) {
651 setConnectionState(Network::Reconnecting);
652 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
653 doAutoReconnect(); // first try is immediate
655 _autoReconnectTimer.start();
658 if (_metricsServer) {
659 _metricsServer->removeNetwork(userId());
663 void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState)
665 Network::ConnectionState state;
666 switch (socketState) {
667 case QAbstractSocket::UnconnectedState:
668 state = Network::Disconnected;
669 onSocketDisconnected();
671 case QAbstractSocket::HostLookupState:
672 case QAbstractSocket::ConnectingState:
673 state = Network::Connecting;
675 case QAbstractSocket::ConnectedState:
676 state = Network::Initializing;
678 case QAbstractSocket::ClosingState:
679 state = Network::Disconnecting;
682 state = Network::Disconnected;
684 setConnectionState(state);
687 void CoreNetwork::networkInitialized()
689 setConnectionState(Network::Initialized);
691 _disconnectExpected = false;
692 _quitRequested = false;
694 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
695 // flag used for initial registration and capability negotiation.
696 updateRateLimiting();
698 if (useAutoReconnect()) {
700 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
703 // restore away state
704 QString awayMsg = Core::awayMessage(userId(), networkId());
705 if (!awayMsg.isEmpty()) {
706 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
707 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
708 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
715 if (networkConfig()->autoWhoEnabled()) {
716 _autoWhoCycleTimer.start();
717 _autoWhoTimer.start();
718 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
721 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
722 Core::setNetworkConnected(userId(), networkId(), true);
725 void CoreNetwork::sendPerform()
727 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
730 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
731 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
734 // restore old user modes if server default mode is set.
737 if (!me_->userModes().isEmpty()) {
741 connect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
742 connect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
747 for (const QString& line : perform()) {
749 userInput(statusBuf, line);
752 // rejoin channels we've been in
753 if (rejoinChannels()) {
754 QStringList channels, keys;
755 for (const QString& chan : coreSession()->persistentChannels(networkId()).keys()) {
756 QString key = channelKey(chan);
757 if (!key.isEmpty()) {
758 channels.prepend(chan);
762 channels.append(chan);
765 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
766 if (!joinString.isEmpty())
767 userInputHandler()->handleJoin(statusBuf, joinString);
771 void CoreNetwork::restoreUserModes()
776 disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
777 disconnect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
779 QString modesDelta = Core::userModes(userId(), networkId());
780 QString currentModes = me_->userModes();
782 QString addModes, removeModes;
783 if (modesDelta.contains('-')) {
784 addModes = modesDelta.section('-', 0, 0);
785 removeModes = modesDelta.section('-', 1);
788 addModes = modesDelta;
791 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
792 if (currentModes.isEmpty())
793 removeModes = QString();
795 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
797 if (addModes.isEmpty() && removeModes.isEmpty())
800 if (!addModes.isEmpty())
801 addModes = '+' + addModes;
802 if (!removeModes.isEmpty())
803 removeModes = '-' + removeModes;
805 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
806 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
809 void CoreNetwork::updateIssuedModes(const QString& requestedModes)
815 for (auto requestedMode : requestedModes) {
816 if (requestedMode == '+') {
820 if (requestedMode == '-') {
825 addModes += requestedMode;
828 removeModes += requestedMode;
832 QString addModesOld = _requestedUserModes.section('-', 0, 0);
833 QString removeModesOld = _requestedUserModes.section('-', 1);
835 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
836 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
837 addModes += addModesOld;
839 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
840 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
841 removeModes += removeModesOld;
843 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
846 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
848 QString persistentUserModes = Core::userModes(userId(), networkId());
850 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
851 QString requestedRemove = _requestedUserModes.section('-', 1);
853 QString persistentAdd, persistentRemove;
854 if (persistentUserModes.contains('-')) {
855 persistentAdd = persistentUserModes.section('-', 0, 0);
856 persistentRemove = persistentUserModes.section('-', 1);
859 persistentAdd = persistentUserModes;
862 // remove modes we didn't issue
863 if (requestedAdd.isEmpty())
864 addModes = QString();
866 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
868 if (requestedRemove.isEmpty())
869 removeModes = QString();
871 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
874 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
875 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
878 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
879 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
881 // update issued mode list
882 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
883 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
884 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
886 persistentAdd += addModes;
887 persistentRemove += removeModes;
888 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
891 void CoreNetwork::resetPersistentModes()
893 _requestedUserModes = QString('-');
894 Core::setUserModes(userId(), networkId(), QString());
897 void CoreNetwork::setUseAutoReconnect(bool use)
899 Network::setUseAutoReconnect(use);
901 _autoReconnectTimer.stop();
904 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
906 Network::setAutoReconnectInterval(interval);
907 _autoReconnectTimer.setInterval(interval * 1000);
910 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
912 Network::setAutoReconnectRetries(retries);
913 if (_autoReconnectCount != 0) {
914 if (unlimitedReconnectRetries())
915 _autoReconnectCount = -1;
917 _autoReconnectCount = autoReconnectRetries();
921 void CoreNetwork::doAutoReconnect()
923 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
924 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
927 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
928 _autoReconnectCount--; // -2 means we delay the next reconnect
932 void CoreNetwork::sendPing()
934 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
935 if (_pingCount != 0) {
936 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
937 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
939 if ((int) _pingCount >= networkConfig()->maxPingCount() && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
940 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
941 // However, to reduce the risk of breaking things by changing past behavior, we still allow
942 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
944 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
945 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
946 // and unable to even handle a ping answer. So we ignore those misses.
947 disconnectFromIrc(false,
948 QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000),
949 true /* withReconnect */);
954 // Don't send pings until the network is initialized
956 // Mark as waiting for a reply
957 _pongReplyPending = true;
958 // Send default timestamp ping
959 userInputHandler()->handlePing(BufferInfo(), QString());
964 void CoreNetwork::enablePingTimeout(bool enable)
967 disablePingTimeout();
970 resetPongReplyPending();
971 if (networkConfig()->pingTimeoutEnabled())
976 void CoreNetwork::disablePingTimeout()
981 resetPongReplyPending();
984 void CoreNetwork::setPingInterval(int interval)
986 _pingTimer.setInterval(interval * 1000);
989 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
991 _pongTimestampValid = validTimestamp;
994 /******** Custom Rate Limiting ********/
996 void CoreNetwork::updateRateLimiting(bool forceUnlimited)
998 // Verify and apply custom rate limiting options, always resetting the delay and burst size
999 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
1000 // this may be called while connected to a server.
1002 if (useCustomMessageRate() || forceUnlimited) {
1003 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
1005 _messageDelay = messageRateDelay();
1007 _burstSize = messageRateBurstSize();
1008 if (_burstSize < 1) {
1009 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" << _burstSize;
1010 // Can't go slower than one message at a time
1014 if (_tokenBucket > _burstSize) {
1015 // Don't let the token bucket exceed the maximum
1016 _tokenBucket = _burstSize;
1017 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1018 // changing the rate-limit settings while connected to a server will incorrectly reset
1019 // the token bucket.
1022 // Toggle the timer according to whether or not rate limiting is enabled
1023 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1024 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1025 // Override user preferences if called with force unlimited, only used during connect.
1026 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1027 if (_skipMessageRates) {
1028 // If the message queue already contains messages, they need sent before disabling the
1029 // timer. Set the timer to a rapid pace and let it disable itself.
1030 if (!_msgQueue.isEmpty()) {
1031 qDebug() << "Outgoing message queue contains messages while disabling rate "
1032 "limiting. Sending remaining queued messages...";
1033 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1034 // so nothing should cause this to block.. in theory. However, don't directly call
1035 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1037 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1038 // Hesitant to change it without a wide variety of situations to verify behavior.
1039 _tokenBucketTimer.start(100);
1042 // No rate limiting, disable the timer
1043 _tokenBucketTimer.stop();
1047 // Rate limiting enabled, enable the timer
1048 _tokenBucketTimer.start(_messageDelay);
1052 // Custom message rates disabled. Go for the default.
1054 _skipMessageRates = false; // Enable rate-limiting by default
1055 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1056 _burstSize = 5; // 5 messages at once
1057 if (_tokenBucket > _burstSize) {
1058 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1060 _tokenBucket = _burstSize;
1061 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1062 // changing the rate-limit settings while connected to a server will incorrectly reset
1063 // the token bucket.
1065 // Rate limiting enabled, enable the timer
1066 _tokenBucketTimer.start(_messageDelay);
1070 void CoreNetwork::resetTokenBucket()
1072 // Fill up the token bucket to the maximum
1073 _tokenBucket = _burstSize;
1076 /******** IRCv3 Capability Negotiation ********/
1078 void CoreNetwork::serverCapAdded(const QString& capability)
1080 // Exclude skipped capabilities
1081 if (skipCaps().contains(capability)) {
1085 // Check if it's a known capability; if so, add it to the list
1086 // Handle special cases first
1087 if (capability == IrcCap::SASL) {
1088 // Only request SASL if it's enabled
1090 queueCap(capability);
1093 else if (IrcCap::knownCaps.contains(capability)) {
1094 // Handling for general known capabilities
1095 queueCap(capability);
1099 void CoreNetwork::serverCapAcknowledged(const QString& capability)
1101 // This may be called multiple times in certain situations.
1103 // Handle core-side configuration
1104 if (capability == IrcCap::AWAY_NOTIFY) {
1105 // away-notify enabled, stop the autoWho timers, handle manually
1106 setAutoWhoEnabled(false);
1109 // Handle capabilities that require further messages sent to the IRC server
1110 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringConfiguration
1111 if (capability == IrcCap::SASL) {
1112 // If SASL mechanisms specified, limit to what's accepted for authentication
1113 // if the current identity has a cert set, use SASL EXTERNAL
1115 if (!identityPtr()->sslCert().isNull()) {
1116 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1117 // EXTERNAL authentication supported, send request
1118 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1121 showMessage(NetworkInternalMessage(
1123 BufferInfo::StatusBuffer,
1125 tr("SASL EXTERNAL authentication not supported")
1131 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1132 // PLAIN authentication supported, send request
1133 // Only working with PLAIN atm, blowfish later
1134 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1137 showMessage(NetworkInternalMessage(
1139 BufferInfo::StatusBuffer,
1141 tr("SASL PLAIN authentication not supported")
1149 void CoreNetwork::serverCapRemoved(const QString& capability)
1151 // This may be called multiple times in certain situations.
1153 // Handle special cases here
1154 if (capability == IrcCap::AWAY_NOTIFY) {
1155 // away-notify disabled, enable autoWho according to configuration
1156 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1160 void CoreNetwork::queueCap(const QString& capability)
1162 // IRCv3 specs all use lowercase capability names
1163 QString _capLowercase = capability.toLower();
1165 if (capsRequiringConfiguration.contains(_capLowercase)) {
1166 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1167 // so we should negotiate it separately from all other capabilities. Otherwise new
1168 // capabilities will be requested while still configuring the previous one.
1169 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1170 _capsQueuedIndividual.append(_capLowercase);
1174 // The capability doesn't need any special configuration, so it should be safe to try
1175 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1177 if (!_capsQueuedBundled.contains(_capLowercase)) {
1178 _capsQueuedBundled.append(_capLowercase);
1183 QString CoreNetwork::takeQueuedCaps()
1185 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1187 _capsQueuedLastBundle.clear();
1189 // First, negotiate all the standalone capabilities that require additional configuration.
1190 if (!_capsQueuedIndividual.empty()) {
1191 // We have an individual capability available. Take the first and pass it back.
1192 return _capsQueuedIndividual.takeFirst();
1194 else if (!_capsQueuedBundled.empty()) {
1195 // We have capabilities available that can be grouped. Try to fit in as many as within the
1197 // See CoreNetwork::maxCapRequestLength
1199 // Response must have at least one capability regardless of max length for anything to
1201 QString capBundle = _capsQueuedBundled.takeFirst();
1202 QString nextCap("");
1203 while (!_capsQueuedBundled.empty()) {
1204 // As long as capabilities remain, get the next...
1205 nextCap = _capsQueuedBundled.first();
1206 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1207 // [capability + 1 for a space + this new capability] fit within length limits
1208 // Add it to formatted list
1209 capBundle.append(" " + nextCap);
1210 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1211 _capsQueuedLastBundle.append(nextCap);
1212 // Then remove it from the queue
1213 _capsQueuedBundled.removeFirst();
1216 // We've reached the length limit for a single capability request, stop adding more
1220 // Return this space-separated set of capabilities, removing any extra spaces
1221 return capBundle.trimmed();
1224 // No capabilities left to negotiate, return an empty string.
1229 void CoreNetwork::retryCapsIndividually()
1231 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1232 // denied, try each capability individually.
1233 if (_capsQueuedLastBundle.empty()) {
1234 // No most recently tried capability set, just return.
1236 // Note: there's little point in retrying individually requested caps during negotiation.
1237 // We know the individual capability was the one that failed, and it's not likely it'll
1238 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1239 // handling capability removal and addition.
1242 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1243 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1244 // keeping track of which halves of the group fail, dividing the set each time.
1246 // Add most recently tried capability set to individual list, re-requesting them one at a time
1247 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1248 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1249 showMessage(NetworkInternalMessage(
1251 BufferInfo::StatusBuffer,
1253 tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", "))
1255 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1256 // need to remove them here.
1257 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1259 _capsQueuedLastBundle.clear();
1262 void CoreNetwork::beginCapNegotiation()
1264 // Check if any available capabilities have been disabled
1265 QStringList capsSkipped;
1266 if (!skipCaps().isEmpty() && !caps().isEmpty()) {
1267 // Find the entries that are common to skipCaps() and caps(). This represents any
1268 // capabilities supported by the server that were skipped.
1270 // Both skipCaps() and caps() are already lowercase
1271 // std::set_intersection requires sorted lists, and we can't modify the original lists.
1273 // skipCaps() should already be sorted. caps() is intentionally not sorted elsewhere so
1274 // Quassel can show the capabilities in the order transmitted by the network.
1275 auto sortedCaps = caps();
1278 // Find the intersection between skipped caps and server-supplied caps
1279 std::set_intersection(skipCaps().cbegin(), skipCaps().cend(),
1280 sortedCaps.cbegin(), sortedCaps.cend(),
1281 std::back_inserter(capsSkipped));
1284 if (!capsPendingNegotiation()) {
1285 // No capabilities are queued for request, determine the reason why
1286 QString capStatusMsg;
1287 if (caps().empty()) {
1288 // The server doesn't provide any capabilities, but supports CAP LS
1289 capStatusMsg = tr("No capabilities available");
1291 else if (capsEnabled().empty()) {
1292 // The server supports capabilities (caps() is not empty) but Quassel doesn't support
1293 // anything offered. This should be uncommon.
1295 tr("None of the capabilities provided by the server are supported (found: %1)")
1296 .arg(caps().join(", "));
1299 // Quassel has enabled some capabilities, but there are no further capabilities that can
1301 // (E.g. the user has manually run "/cap ls 302" after initial negotiation.)
1303 tr("No additional capabilities are supported (found: %1; currently enabled: %2)")
1304 .arg(caps().join(", "), capsEnabled().join(", "));
1306 // Inform the user of the situation
1307 showMessage(NetworkInternalMessage(
1309 BufferInfo::StatusBuffer,
1314 if (!capsSkipped.isEmpty()) {
1315 // Mention that some capabilities are skipped
1316 showMessage(NetworkInternalMessage(
1318 BufferInfo::StatusBuffer,
1320 tr("Quassel is configured to ignore some capabilities (skipped: %1)").arg(capsSkipped.join(", "))
1324 // End any ongoing capability negotiation, allowing connection to continue
1325 endCapNegotiation();
1329 _capNegotiationActive = true;
1330 showMessage(NetworkInternalMessage(
1332 BufferInfo::StatusBuffer,
1334 tr("Ready to negotiate (found: %1)").arg(caps().join(", "))
1337 if (!capsSkipped.isEmpty()) {
1338 // Mention that some capabilities are skipped
1339 showMessage(NetworkInternalMessage(
1341 BufferInfo::StatusBuffer,
1343 tr("Quassel is configured to ignore some capabilities (skipped: %1)").arg(capsSkipped.join(", "))
1347 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1348 // comma separator between the two if needed (both individual and bundled caps exist).
1349 QString queuedCapsDisplay = _capsQueuedIndividual.join(", ")
1350 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1351 + _capsQueuedBundled.join(", ");
1352 showMessage(NetworkInternalMessage(
1354 BufferInfo::StatusBuffer,
1356 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay)
1362 void CoreNetwork::sendNextCap()
1364 if (capsPendingNegotiation()) {
1365 // Request the next set of capabilities and remove them from the list
1366 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1369 // No pending desired capabilities, capability negotiation finished
1370 // If SASL requested but not available, print a warning
1371 if (useSasl() && !capEnabled(IrcCap::SASL))
1372 showMessage(NetworkInternalMessage(
1374 BufferInfo::StatusBuffer,
1376 tr("SASL authentication currently not supported by server")
1379 if (_capNegotiationActive) {
1380 showMessage(NetworkInternalMessage(
1382 BufferInfo::StatusBuffer,
1384 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", "))
1386 _capNegotiationActive = false;
1389 endCapNegotiation();
1393 void CoreNetwork::endCapNegotiation()
1395 // If nick registration is already complete, CAP END is not required
1396 if (!_capInitialNegotiationEnded) {
1397 putRawLine(serverEncode(QString("CAP END")));
1398 _capInitialNegotiationEnded = true;
1402 /******** AutoWHO ********/
1404 void CoreNetwork::startAutoWhoCycle()
1406 if (!_autoWhoQueue.isEmpty()) {
1407 _autoWhoCycleTimer.stop();
1410 _autoWhoQueue = channels();
1413 void CoreNetwork::queueAutoWhoOneshot(const QString& name)
1415 // Prepend so these new channels/nicks are the first to be checked
1416 // Don't allow duplicates
1417 if (!_autoWhoQueue.contains(name.toLower())) {
1418 _autoWhoQueue.prepend(name.toLower());
1420 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1421 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1422 setAutoWhoEnabled(true);
1426 void CoreNetwork::setAutoWhoDelay(int delay)
1428 _autoWhoTimer.setInterval(delay * 1000);
1431 void CoreNetwork::setAutoWhoInterval(int interval)
1433 _autoWhoCycleTimer.setInterval(interval * 1000);
1436 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1438 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1439 _autoWhoTimer.start();
1440 else if (!enabled) {
1441 _autoWhoTimer.stop();
1442 _autoWhoCycleTimer.stop();
1446 void CoreNetwork::sendAutoWho()
1448 // Don't send autowho if there are still some pending
1449 if (_autoWhoPending.count())
1452 while (!_autoWhoQueue.isEmpty()) {
1453 QString chanOrNick = _autoWhoQueue.takeFirst();
1454 // Check if it's a known channel or nick
1455 IrcChannel* ircchan = ircChannel(chanOrNick);
1456 IrcUser* ircuser = ircUser(chanOrNick);
1458 // Apply channel limiting rules
1459 // If using away-notify, don't impose channel size limits in order to capture away
1460 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1461 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1462 && !capEnabled(IrcCap::AWAY_NOTIFY))
1464 _autoWhoPending[chanOrNick.toLower()]++;
1467 // Checking a nick, add it to the pending list
1468 _autoWhoPending[ircuser->nick().toLower()]++;
1471 // Not a channel or a nick, skip it
1472 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1475 if (supports("WHOX")) {
1476 // Use WHO extended to poll away users and/or user accounts
1477 // Explicitly only match on nickname ("n"), don't rely on server defaults
1479 // WHO <nickname> n%chtsunfra,<unique_number>
1481 // See http://faerion.sourceforge.net/doc/irc/whox.var
1482 // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1483 // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1484 putRawLine(serverEncode(
1485 QString("WHO %1 n%chtsunfra,%2")
1486 .arg(chanOrNick, QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))
1490 // Fall back to normal WHO
1492 // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1493 // hostmask, etc. There's nothing we can do about that :(
1495 // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1496 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1501 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1502 // Timer was stopped, means a new cycle is due immediately
1503 // Don't run a new cycle if using away-notify; server will notify as appropriate
1504 _autoWhoCycleTimer.start();
1505 startAutoWhoCycle();
1507 else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1508 // Don't run another who cycle if away-notify is enabled
1509 _autoWhoCycleTimer.stop();
1513 void CoreNetwork::onSslErrors(const QList<QSslError>& sslErrors)
1515 Server server = usedServer();
1516 if (server.sslVerify) {
1517 // Treat the SSL error as a hard error
1518 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1519 "since verification is required");
1520 if (!sslErrors.empty()) {
1521 // Add the error reason if known
1522 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1524 showMessage(NetworkInternalMessage(
1526 BufferInfo::StatusBuffer,
1531 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1532 // validity, network trouble, etc.
1533 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1536 // Treat the SSL error as a warning, continue to connect anyways
1537 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1538 "since verification is not required");
1539 if (!sslErrors.empty()) {
1540 // Add the error reason if known
1541 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1543 showMessage(NetworkInternalMessage(
1545 BufferInfo::StatusBuffer,
1550 // Proceed with the connection
1551 socket.ignoreSslErrors();
1555 void CoreNetwork::checkTokenBucket()
1557 if (_skipMessageRates) {
1558 if (_msgQueue.empty()) {
1559 // Message queue emptied; stop the timer and bail out
1560 _tokenBucketTimer.stop();
1563 // Otherwise, we're emptying the queue, continue on as normal
1566 // Process whatever messages are pending
1567 fillBucketAndProcessQueue();
1570 void CoreNetwork::fillBucketAndProcessQueue()
1572 // If there's less tokens than burst size, refill the token bucket by 1
1573 if (_tokenBucket < _burstSize) {
1577 // As long as there's tokens available and messages remaining, sending messages from the queue
1578 while (!_msgQueue.empty() && _tokenBucket > 0) {
1579 writeToSocket(_msgQueue.takeFirst());
1580 if (_metricsServer) {
1581 _metricsServer->messageQueue(userId(), _msgQueue.size());
1586 void CoreNetwork::writeToSocket(const QByteArray& data)
1588 // Log the message if enabled and network ID matches or allows all
1589 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1590 // Include network ID
1591 qDebug() << "IRC net" << networkId() << ">>" << data;
1594 socket.write("\r\n");
1595 if (_metricsServer) {
1596 _metricsServer->transmitDataNetwork(userId(), data.size() + 2);
1598 if (!_skipMessageRates) {
1599 // Only subtract from the token bucket if message rate limiting is enabled
1604 Network::Server CoreNetwork::usedServer() const
1606 if (_lastUsedServerIndex < serverList().count())
1607 return serverList()[_lastUsedServerIndex];
1609 if (!serverList().isEmpty())
1610 return serverList()[0];
1612 return Network::Server();
1615 void CoreNetwork::requestConnect() const
1617 if (_shuttingDown) {
1620 if (connectionState() != Disconnected) {
1621 qWarning() << "Requesting connect while already being connected!";
1624 QMetaObject::invokeMethod(const_cast<CoreNetwork*>(this), "connectToIrc", Qt::QueuedConnection);
1627 void CoreNetwork::requestDisconnect() const
1629 if (_shuttingDown) {
1632 if (connectionState() == Disconnected) {
1633 qWarning() << "Requesting disconnect while not being connected!";
1636 userInputHandler()->handleQuit(BufferInfo(), QString());
1639 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info)
1641 Network::Server currentServer = usedServer();
1642 setNetworkInfo(info);
1643 Core::updateNetwork(coreSession()->user(), info);
1645 // the order of the servers might have changed,
1646 // so we try to find the previously used server
1647 _lastUsedServerIndex = 0;
1648 for (int i = 0; i < serverList().count(); i++) {
1649 Network::Server server = serverList()[i];
1650 if (server.host == currentServer.host && server.port == currentServer.port) {
1651 _lastUsedServerIndex = i;
1657 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString& cmd,
1658 const QString& message,
1659 const std::function<QList<QByteArray>(QString&)>& cmdGenerator)
1661 QString wrkMsg(message);
1662 QList<QList<QByteArray>> msgsToSend;
1664 // do while (wrkMsg.size() > 0)
1666 // First, check to see if the whole message can be sent at once. The
1667 // cmdGenerator function is passed in by the caller and is used to encode
1668 // and encrypt (if applicable) the message, since different callers might
1669 // want to use different encoding or encode different values.
1670 int splitPos = wrkMsg.size();
1671 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1672 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1674 if (initialOverrun) {
1675 // If the message was too long to be sent, first try splitting it along
1676 // word boundaries with QTextBoundaryFinder.
1677 QString splitMsg(wrkMsg);
1678 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1679 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1680 QList<QByteArray> splitMsgEnc;
1681 int overrun = initialOverrun;
1684 splitPos = qtbf.toPreviousBoundary();
1686 // splitPos==-1 means the QTBF couldn't find a split point at all and
1687 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1688 // the string. Neither one of these works for us.
1690 // If a split point could be found, split the message there, calculate the
1691 // overrun, and continue with the loop.
1692 splitMsg = splitMsg.left(splitPos);
1693 splitMsgEnc = cmdGenerator(splitMsg);
1694 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1697 // If a split point could not be found (the beginning of the message
1698 // is reached without finding a split point short enough to send) and we
1699 // are still in Word mode, switch to Grapheme mode. We also need to restore
1700 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1701 // the previous attempt to find a split point.
1702 if (qtbf.type() == QTextBoundaryFinder::Word) {
1704 splitPos = splitMsg.size();
1705 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1706 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1707 qtbf = graphemeQtbf;
1710 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1711 // This should never happen, but it should be handled anyway.
1712 qWarning() << "Unexpected failure to split message!";
1718 // Once a message of sendable length has been found, remove it from the wrkMsg and
1719 // add it to the list of messages to be sent.
1720 wrkMsg.remove(0, splitPos);
1721 msgsToSend.append(splitMsgEnc);
1724 // If the entire remaining message is short enough to be sent all at once, remove
1725 // it from the wrkMsg and add it to the list of messages to be sent.
1726 wrkMsg.remove(0, splitPos);
1727 msgsToSend.append(initialSplitMsgEnc);
1729 } while (wrkMsg.size() > 0);