1 /***************************************************************************
2 * Copyright (C) 2005-2018 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 "coreidentity.h"
28 #include "corenetworkconfig.h"
29 #include "coresession.h"
30 #include "coreuserinputhandler.h"
31 #include "networkevent.h"
36 CoreNetwork::CoreNetwork(const NetworkId& networkid, CoreSession* session)
37 : Network(networkid, session)
38 , _coreSession(session)
39 , _userInputHandler(new CoreUserInputHandler(this))
40 , _autoReconnectCount(0)
41 , _quitRequested(false)
42 , _disconnectExpected(false)
45 _previousConnectionAttemptFailed(false)
46 , _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 foreach (QString chan, channels.keys()) {
66 _channelKeys[chan.toLower()] = channels[chan];
69 QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
70 foreach (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);
90 connect(&socket, &QSslSocket::encrypted, this, &CoreNetwork::onSocketInitialized);
91 connect(&socket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &CoreNetwork::onSslErrors);
93 connect(this, &CoreNetwork::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
95 // Custom rate limiting
96 // These react to the user changing settings in the client
97 connect(this, &Network::useCustomMessageRateSet, this, &CoreNetwork::updateRateLimiting);
98 connect(this, &Network::messageRateBurstSizeSet, this, &CoreNetwork::updateRateLimiting);
99 connect(this, &Network::messageRateDelaySet, this, &CoreNetwork::updateRateLimiting);
100 connect(this, &Network::unlimitedMessageRateSet, this, &CoreNetwork::updateRateLimiting);
102 // IRCv3 capability handling
103 // These react to CAP messages from the server
104 connect(this, &Network::capAdded, this, &CoreNetwork::serverCapAdded);
105 connect(this, &Network::capAcknowledged, this, &CoreNetwork::serverCapAcknowledged);
106 connect(this, &Network::capRemoved, this, &CoreNetwork::serverCapRemoved);
108 if (Quassel::isOptionSet("oidentd")) {
109 connect(this, &CoreNetwork::socketInitialized, Core::instance()->oidentdConfigGenerator(), &OidentdConfigGenerator::addSocket);
110 connect(this, &CoreNetwork::socketDisconnected, Core::instance()->oidentdConfigGenerator(), &OidentdConfigGenerator::removeSocket);
113 if (Quassel::isOptionSet("ident-daemon")) {
114 connect(this, &CoreNetwork::socketInitialized, Core::instance()->identServer(), &IdentServer::addSocket);
115 connect(this, &CoreNetwork::socketDisconnected, Core::instance()->identServer(), &IdentServer::removeSocket);
119 CoreNetwork::~CoreNetwork()
121 // Ensure we don't get any more signals from the socket while shutting down
122 disconnect(&socket, nullptr, this, nullptr);
123 if (!forceDisconnect()) {
124 qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
126 .arg(networkId().toInt())
127 .arg(userId().toInt());
131 bool CoreNetwork::forceDisconnect(int msecs)
133 if (socket.state() == QAbstractSocket::UnconnectedState) {
134 // Socket already disconnected.
137 // Request a socket-level disconnect if not already happened
138 socket.disconnectFromHost();
139 if (socket.state() != QAbstractSocket::UnconnectedState) {
140 return socket.waitForDisconnected(msecs);
145 QString CoreNetwork::channelDecode(const QString& bufferName, const QByteArray& string) const
147 if (!bufferName.isEmpty()) {
148 IrcChannel* channel = ircChannel(bufferName);
150 return channel->decodeString(string);
152 return decodeString(string);
155 QString CoreNetwork::userDecode(const QString& userNick, const QByteArray& string) const
157 IrcUser* user = ircUser(userNick);
159 return user->decodeString(string);
160 return decodeString(string);
163 QByteArray CoreNetwork::channelEncode(const QString& bufferName, const QString& string) const
165 if (!bufferName.isEmpty()) {
166 IrcChannel* channel = ircChannel(bufferName);
168 return channel->encodeString(string);
170 return encodeString(string);
173 QByteArray CoreNetwork::userEncode(const QString& userNick, const QString& string) const
175 IrcUser* user = ircUser(userNick);
177 return user->encodeString(string);
178 return encodeString(string);
181 void CoreNetwork::connectToIrc(bool reconnecting)
187 if (Core::instance()->identServer()) {
188 _socketId = Core::instance()->identServer()->addWaitingSocket();
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(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
226 if (++_lastUsedServerIndex >= serverList().size()) {
227 _lastUsedServerIndex = 0;
231 // Start out with the top server in the list
232 _lastUsedServerIndex = 0;
235 Server server = usedServer();
236 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
237 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
239 if (server.useProxy) {
240 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
241 socket.setProxy(proxy);
244 socket.setProxy(QNetworkProxy::NoProxy);
249 // Reset tracking for valid timestamps in PONG replies
250 setPongTimestampValid(false);
252 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
253 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
254 if (!server.useProxy) {
255 // Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
256 // hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
257 QHostInfo::fromName(server.host);
261 CoreIdentity* identity = identityPtr();
263 socket.setLocalCertificate(identity->sslCert());
264 socket.setPrivateKey(identity->sslKey());
266 socket.connectToHostEncrypted(server.host, server.port);
269 socket.connectToHost(server.host, server.port);
272 socket.connectToHost(server.host, server.port);
276 void CoreNetwork::disconnectFromIrc(bool requested, const QString& reason, bool withReconnect)
278 // Disconnecting from the network, should expect a socket close or error
279 _disconnectExpected = true;
280 _quitRequested = requested; // see socketDisconnected();
281 if (!withReconnect) {
282 _autoReconnectTimer.stop();
283 _autoReconnectCount = 0; // prohibiting auto reconnect
285 disablePingTimeout();
292 awayMsg = me_->awayMessage();
293 Core::setAwayMessage(userId(), networkId(), awayMsg);
296 if (reason.isEmpty() && identityPtr())
297 _quitReason = identityPtr()->quitReason();
299 _quitReason = reason;
301 showMessage(Message::Server,
302 BufferInfo::StatusBuffer,
304 tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
305 if (socket.state() == QAbstractSocket::UnconnectedState) {
306 onSocketDisconnected();
309 if (socket.state() == QAbstractSocket::ConnectedState) {
310 // If shutting down, prioritize the QUIT command
311 userInputHandler()->issueQuit(_quitReason, _shuttingDown);
316 if (socket.state() != QAbstractSocket::UnconnectedState) {
317 // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
318 _socketCloseTimer.start(10000);
323 void CoreNetwork::onSocketCloseTimeout()
325 qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
327 .arg(networkId().toInt())
328 .arg(userId().toInt());
332 void CoreNetwork::shutdown()
334 _shuttingDown = true;
335 disconnectFromIrc(false, {}, false);
338 void CoreNetwork::userInput(const BufferInfo& buf, QString msg)
340 userInputHandler()->handleUserInput(buf, msg);
343 void CoreNetwork::putRawLine(const QByteArray& s, bool prepend)
345 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.isEmpty())) {
346 // If there's tokens remaining, ...
347 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
348 // Send the message now.
352 // Otherwise, queue the message for later
354 // Jump to the start, skipping other messages
355 _msgQueue.prepend(s);
358 // Add to back, waiting in order
364 void CoreNetwork::putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix, const bool prepend)
368 if (!prefix.isEmpty())
369 msg += ":" + prefix + " ";
370 msg += cmd.toUpper().toLatin1();
372 for (int i = 0; i < params.size(); i++) {
375 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
381 putRawLine(msg, prepend);
384 void CoreNetwork::putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix, const bool prependAll)
386 QListIterator<QList<QByteArray>> i(params);
387 while (i.hasNext()) {
388 QList<QByteArray> msg = i.next();
389 putCmd(cmd, msg, prefix, prependAll);
393 void CoreNetwork::setChannelJoined(const QString& channel)
395 queueAutoWhoOneshot(channel); // check this new channel first
397 Core::setChannelPersistent(userId(), networkId(), channel, true);
398 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
401 void CoreNetwork::setChannelParted(const QString& channel)
403 removeChannelKey(channel);
404 _autoWhoQueue.removeAll(channel.toLower());
405 _autoWhoPending.remove(channel.toLower());
407 Core::setChannelPersistent(userId(), networkId(), channel, false);
410 void CoreNetwork::addChannelKey(const QString& channel, const QString& key)
413 removeChannelKey(channel);
416 _channelKeys[channel.toLower()] = key;
420 void CoreNetwork::removeChannelKey(const QString& channel)
422 _channelKeys.remove(channel.toLower());
426 Cipher* CoreNetwork::cipher(const QString& target)
428 if (target.isEmpty())
431 if (!Cipher::neededFeaturesAvailable())
434 auto* channel = qobject_cast<CoreIrcChannel*>(ircChannel(target));
436 return channel->cipher();
438 auto* user = qobject_cast<CoreIrcUser*>(ircUser(target));
440 return user->cipher();
442 else if (!isChannelName(target)) {
443 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
448 QByteArray CoreNetwork::cipherKey(const QString& target) const
450 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
452 return c->cipher()->key();
454 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
456 return u->cipher()->key();
461 void CoreNetwork::setCipherKey(const QString& target, const QByteArray& key)
463 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
465 c->setEncrypted(c->cipher()->setKey(key));
466 coreSession()->setBufferCipher(networkId(), target, key);
470 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
471 if (!u && !isChannelName(target))
472 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
475 u->setEncrypted(u->cipher()->setKey(key));
476 coreSession()->setBufferCipher(networkId(), target, key);
481 bool CoreNetwork::cipherUsesCBC(const QString& target)
483 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
485 return c->cipher()->usesCBC();
486 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
488 return u->cipher()->usesCBC();
492 #endif /* HAVE_QCA2 */
494 bool CoreNetwork::setAutoWhoDone(const QString& name)
496 QString chanOrNick = name.toLower();
497 if (_autoWhoPending.value(chanOrNick, 0) <= 0)
499 if (--_autoWhoPending[chanOrNick] <= 0)
500 _autoWhoPending.remove(chanOrNick);
504 void CoreNetwork::setMyNick(const QString& mynick)
506 Network::setMyNick(mynick);
507 if (connectionState() == Network::Initializing)
508 networkInitialized();
511 void CoreNetwork::onSocketHasData()
513 while (socket.canReadLine()) {
514 QByteArray s = socket.readLine();
515 if (s.endsWith("\r\n"))
517 else if (s.endsWith("\n"))
519 NetworkDataEvent* event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
520 event->setTimestamp(QDateTime::currentDateTimeUtc());
521 emit newEvent(event);
525 void CoreNetwork::onSocketError(QAbstractSocket::SocketError error)
527 // Ignore socket closed errors if expected
528 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
532 _previousConnectionAttemptFailed = true;
533 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
534 emit connectionError(socket.errorString());
535 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
536 emitConnectionError(socket.errorString());
537 if (socket.state() < QAbstractSocket::ConnectedState) {
538 onSocketDisconnected();
542 void CoreNetwork::onSocketInitialized()
544 CoreIdentity* identity = identityPtr();
546 qCritical() << "Identity invalid!";
551 Server server = usedServer();
554 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
555 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
556 if (!server.useSsl || !socket.isEncrypted()) {
557 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
560 if (server.useSsl && !socket.isEncrypted()) {
561 // We'll finish setup once we're encrypted, and called again
565 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
568 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
570 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
571 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
572 // force flag to apply user preferences. When making changes, ensure that this still happens!
573 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
574 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
576 updateRateLimiting(true);
577 // Fill up the token bucket as we're connecting from scratch
580 // Request capabilities as per IRCv3.2 specifications
581 // Older servers should ignore this; newer servers won't downgrade to RFC1459
582 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
583 putRawLine(serverEncode(QString("CAP LS 302")));
585 if (!server.password.isEmpty()) {
586 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
589 if (identity->nicks().isEmpty()) {
591 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
594 nick = identity->nicks()[0];
596 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
597 // Only allow strict-compliant idents when strict mode is enabled
598 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(coreSession()->strictCompliantIdent(identity), identity->realName())));
601 void CoreNetwork::onSocketDisconnected()
603 disablePingTimeout();
606 _autoWhoCycleTimer.stop();
607 _autoWhoTimer.stop();
608 _autoWhoQueue.clear();
609 _autoWhoPending.clear();
611 _socketCloseTimer.stop();
613 _tokenBucketTimer.stop();
617 foreach (QString channel, me_->channels())
618 showMessage(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
622 emit disconnected(networkId());
623 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
624 // Reset disconnect expectations
625 _disconnectExpected = false;
626 if (_quitRequested) {
627 _quitRequested = false;
628 setConnectionState(Network::Disconnected);
629 Core::setNetworkConnected(userId(), networkId(), false);
631 else if (_autoReconnectCount != 0) {
632 setConnectionState(Network::Reconnecting);
633 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
634 doAutoReconnect(); // first try is immediate
636 _autoReconnectTimer.start();
640 void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState)
642 Network::ConnectionState state;
643 switch (socketState) {
644 case QAbstractSocket::UnconnectedState:
645 state = Network::Disconnected;
646 onSocketDisconnected();
648 case QAbstractSocket::HostLookupState:
649 case QAbstractSocket::ConnectingState:
650 state = Network::Connecting;
652 case QAbstractSocket::ConnectedState:
653 state = Network::Initializing;
655 case QAbstractSocket::ClosingState:
656 state = Network::Disconnecting;
659 state = Network::Disconnected;
661 setConnectionState(state);
664 void CoreNetwork::networkInitialized()
666 setConnectionState(Network::Initialized);
668 _disconnectExpected = false;
669 _quitRequested = false;
671 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
672 // flag used for initial registration and capability negotiation.
673 updateRateLimiting();
675 if (useAutoReconnect()) {
677 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
680 // restore away state
681 QString awayMsg = Core::awayMessage(userId(), networkId());
682 if (!awayMsg.isEmpty()) {
683 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
684 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
685 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
692 if (networkConfig()->autoWhoEnabled()) {
693 _autoWhoCycleTimer.start();
694 _autoWhoTimer.start();
695 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
698 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
699 Core::setNetworkConnected(userId(), networkId(), true);
702 void CoreNetwork::sendPerform()
704 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
707 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
708 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
711 // restore old user modes if server default mode is set.
714 if (!me_->userModes().isEmpty()) {
718 connect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
719 connect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
724 foreach (QString line, perform()) {
726 userInput(statusBuf, line);
729 // rejoin channels we've been in
730 if (rejoinChannels()) {
731 QStringList channels, keys;
732 foreach (QString chan, coreSession()->persistentChannels(networkId()).keys()) {
733 QString key = channelKey(chan);
734 if (!key.isEmpty()) {
735 channels.prepend(chan);
739 channels.append(chan);
742 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
743 if (!joinString.isEmpty())
744 userInputHandler()->handleJoin(statusBuf, joinString);
748 void CoreNetwork::restoreUserModes()
753 disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
754 disconnect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
756 QString modesDelta = Core::userModes(userId(), networkId());
757 QString currentModes = me_->userModes();
759 QString addModes, removeModes;
760 if (modesDelta.contains('-')) {
761 addModes = modesDelta.section('-', 0, 0);
762 removeModes = modesDelta.section('-', 1);
765 addModes = modesDelta;
768 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
769 if (currentModes.isEmpty())
770 removeModes = QString();
772 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
774 if (addModes.isEmpty() && removeModes.isEmpty())
777 if (!addModes.isEmpty())
778 addModes = '+' + addModes;
779 if (!removeModes.isEmpty())
780 removeModes = '-' + removeModes;
782 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
783 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
786 void CoreNetwork::updateIssuedModes(const QString& requestedModes)
792 for (auto requestedMode : requestedModes) {
793 if (requestedMode == '+') {
797 if (requestedMode == '-') {
802 addModes += requestedMode;
805 removeModes += requestedMode;
809 QString addModesOld = _requestedUserModes.section('-', 0, 0);
810 QString removeModesOld = _requestedUserModes.section('-', 1);
812 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
813 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
814 addModes += addModesOld;
816 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
817 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
818 removeModes += removeModesOld;
820 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
823 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
825 QString persistentUserModes = Core::userModes(userId(), networkId());
827 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
828 QString requestedRemove = _requestedUserModes.section('-', 1);
830 QString persistentAdd, persistentRemove;
831 if (persistentUserModes.contains('-')) {
832 persistentAdd = persistentUserModes.section('-', 0, 0);
833 persistentRemove = persistentUserModes.section('-', 1);
836 persistentAdd = persistentUserModes;
839 // remove modes we didn't issue
840 if (requestedAdd.isEmpty())
841 addModes = QString();
843 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
845 if (requestedRemove.isEmpty())
846 removeModes = QString();
848 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
851 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
852 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
855 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
856 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
858 // update issued mode list
859 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
860 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
861 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
863 persistentAdd += addModes;
864 persistentRemove += removeModes;
865 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
868 void CoreNetwork::resetPersistentModes()
870 _requestedUserModes = QString('-');
871 Core::setUserModes(userId(), networkId(), QString());
874 void CoreNetwork::setUseAutoReconnect(bool use)
876 Network::setUseAutoReconnect(use);
878 _autoReconnectTimer.stop();
881 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
883 Network::setAutoReconnectInterval(interval);
884 _autoReconnectTimer.setInterval(interval * 1000);
887 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
889 Network::setAutoReconnectRetries(retries);
890 if (_autoReconnectCount != 0) {
891 if (unlimitedReconnectRetries())
892 _autoReconnectCount = -1;
894 _autoReconnectCount = autoReconnectRetries();
898 void CoreNetwork::doAutoReconnect()
900 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
901 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
904 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
905 _autoReconnectCount--; // -2 means we delay the next reconnect
909 void CoreNetwork::sendPing()
911 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
912 if (_pingCount != 0) {
913 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
914 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
916 if ((int)_pingCount >= networkConfig()->maxPingCount() && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
917 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
918 // However, to reduce the risk of breaking things by changing past behavior, we still allow
919 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
921 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
922 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
923 // and unable to even handle a ping answer. So we ignore those misses.
924 disconnectFromIrc(false,
925 QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000),
926 true /* withReconnect */);
931 // Don't send pings until the network is initialized
933 // Mark as waiting for a reply
934 _pongReplyPending = true;
935 // Send default timestamp ping
936 userInputHandler()->handlePing(BufferInfo(), QString());
941 void CoreNetwork::enablePingTimeout(bool enable)
944 disablePingTimeout();
947 resetPongReplyPending();
948 if (networkConfig()->pingTimeoutEnabled())
953 void CoreNetwork::disablePingTimeout()
958 resetPongReplyPending();
961 void CoreNetwork::setPingInterval(int interval)
963 _pingTimer.setInterval(interval * 1000);
966 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
968 _pongTimestampValid = validTimestamp;
971 /******** Custom Rate Limiting ********/
973 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
975 // Verify and apply custom rate limiting options, always resetting the delay and burst size
976 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
977 // this may be called while connected to a server.
979 if (useCustomMessageRate() || forceUnlimited) {
980 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
982 _messageDelay = messageRateDelay();
984 _burstSize = messageRateBurstSize();
985 if (_burstSize < 1) {
986 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" << _burstSize;
987 // Can't go slower than one message at a time
991 if (_tokenBucket > _burstSize) {
992 // Don't let the token bucket exceed the maximum
993 _tokenBucket = _burstSize;
994 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
995 // changing the rate-limit settings while connected to a server will incorrectly reset
999 // Toggle the timer according to whether or not rate limiting is enabled
1000 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1001 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1002 // Override user preferences if called with force unlimited, only used during connect.
1003 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1004 if (_skipMessageRates) {
1005 // If the message queue already contains messages, they need sent before disabling the
1006 // timer. Set the timer to a rapid pace and let it disable itself.
1007 if (!_msgQueue.isEmpty()) {
1008 qDebug() << "Outgoing message queue contains messages while disabling rate "
1009 "limiting. Sending remaining queued messages...";
1010 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1011 // so nothing should cause this to block.. in theory. However, don't directly call
1012 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1014 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1015 // Hesitant to change it without a wide variety of situations to verify behavior.
1016 _tokenBucketTimer.start(100);
1019 // No rate limiting, disable the timer
1020 _tokenBucketTimer.stop();
1024 // Rate limiting enabled, enable the timer
1025 _tokenBucketTimer.start(_messageDelay);
1029 // Custom message rates disabled. Go for the default.
1031 _skipMessageRates = false; // Enable rate-limiting by default
1032 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1033 _burstSize = 5; // 5 messages at once
1034 if (_tokenBucket > _burstSize) {
1035 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1037 _tokenBucket = _burstSize;
1038 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1039 // changing the rate-limit settings while connected to a server will incorrectly reset
1040 // the token bucket.
1042 // Rate limiting enabled, enable the timer
1043 _tokenBucketTimer.start(_messageDelay);
1047 void CoreNetwork::resetTokenBucket()
1049 // Fill up the token bucket to the maximum
1050 _tokenBucket = _burstSize;
1053 /******** IRCv3 Capability Negotiation ********/
1055 void CoreNetwork::serverCapAdded(const QString& capability)
1057 // Check if it's a known capability; if so, add it to the list
1058 // Handle special cases first
1059 if (capability == IrcCap::SASL) {
1060 // Only request SASL if it's enabled
1061 if (networkInfo().useSasl)
1062 queueCap(capability);
1064 else if (IrcCap::knownCaps.contains(capability)) {
1065 // Handling for general known capabilities
1066 queueCap(capability);
1070 void CoreNetwork::serverCapAcknowledged(const QString& capability)
1072 // This may be called multiple times in certain situations.
1074 // Handle core-side configuration
1075 if (capability == IrcCap::AWAY_NOTIFY) {
1076 // away-notify enabled, stop the autoWho timers, handle manually
1077 setAutoWhoEnabled(false);
1080 // Handle capabilities that require further messages sent to the IRC server
1081 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1082 if (capability == IrcCap::SASL) {
1083 // If SASL mechanisms specified, limit to what's accepted for authentication
1084 // if the current identity has a cert set, use SASL EXTERNAL
1087 if (!identityPtr()->sslCert().isNull()) {
1088 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1089 // EXTERNAL authentication supported, send request
1090 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1093 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL EXTERNAL authentication not supported"));
1099 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1100 // PLAIN authentication supported, send request
1101 // Only working with PLAIN atm, blowfish later
1102 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1105 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL PLAIN authentication not supported"));
1114 void CoreNetwork::serverCapRemoved(const QString& capability)
1116 // This may be called multiple times in certain situations.
1118 // Handle special cases here
1119 if (capability == IrcCap::AWAY_NOTIFY) {
1120 // away-notify disabled, enable autoWho according to configuration
1121 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1125 void CoreNetwork::queueCap(const QString& capability)
1127 // IRCv3 specs all use lowercase capability names
1128 QString _capLowercase = capability.toLower();
1130 if (capsRequiringConfiguration.contains(_capLowercase)) {
1131 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1132 // so we should negotiate it separately from all other capabilities. Otherwise new
1133 // capabilities will be requested while still configuring the previous one.
1134 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1135 _capsQueuedIndividual.append(_capLowercase);
1139 // The capability doesn't need any special configuration, so it should be safe to try
1140 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1142 if (!_capsQueuedBundled.contains(_capLowercase)) {
1143 _capsQueuedBundled.append(_capLowercase);
1148 QString CoreNetwork::takeQueuedCaps()
1150 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1152 _capsQueuedLastBundle.clear();
1154 // First, negotiate all the standalone capabilities that require additional configuration.
1155 if (!_capsQueuedIndividual.empty()) {
1156 // We have an individual capability available. Take the first and pass it back.
1157 return _capsQueuedIndividual.takeFirst();
1159 else if (!_capsQueuedBundled.empty()) {
1160 // We have capabilities available that can be grouped. Try to fit in as many as within the
1162 // See CoreNetwork::maxCapRequestLength
1164 // Response must have at least one capability regardless of max length for anything to
1166 QString capBundle = _capsQueuedBundled.takeFirst();
1167 QString nextCap("");
1168 while (!_capsQueuedBundled.empty()) {
1169 // As long as capabilities remain, get the next...
1170 nextCap = _capsQueuedBundled.first();
1171 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1172 // [capability + 1 for a space + this new capability] fit within length limits
1173 // Add it to formatted list
1174 capBundle.append(" " + nextCap);
1175 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1176 _capsQueuedLastBundle.append(nextCap);
1177 // Then remove it from the queue
1178 _capsQueuedBundled.removeFirst();
1181 // We've reached the length limit for a single capability request, stop adding more
1185 // Return this space-separated set of capabilities, removing any extra spaces
1186 return capBundle.trimmed();
1189 // No capabilities left to negotiate, return an empty string.
1194 void CoreNetwork::retryCapsIndividually()
1196 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1197 // denied, try each capability individually.
1198 if (_capsQueuedLastBundle.empty()) {
1199 // No most recently tried capability set, just return.
1201 // Note: there's little point in retrying individually requested caps during negotiation.
1202 // We know the individual capability was the one that failed, and it's not likely it'll
1203 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1204 // handling capability removal and addition.
1207 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1208 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1209 // keeping track of which halves of the group fail, dividing the set each time.
1211 // Add most recently tried capability set to individual list, re-requesting them one at a time
1212 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1213 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1214 showMessage(Message::Server,
1215 BufferInfo::StatusBuffer,
1217 tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", ")));
1218 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1219 // need to remove them here.
1220 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1222 _capsQueuedLastBundle.clear();
1225 void CoreNetwork::beginCapNegotiation()
1227 // Don't begin negotiation if no capabilities are queued to request
1228 if (!capNegotiationInProgress()) {
1229 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1230 // normal connection.
1231 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1232 endCapNegotiation();
1236 _capNegotiationActive = true;
1237 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1239 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1240 // comma separator between the two if needed (both individual and bundled caps exist).
1241 QString queuedCapsDisplay = _capsQueuedIndividual.join(", ")
1242 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1243 + _capsQueuedBundled.join(", ");
1244 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1249 void CoreNetwork::sendNextCap()
1251 if (capNegotiationInProgress()) {
1252 // Request the next set of capabilities and remove them from the list
1253 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1256 // No pending desired capabilities, capability negotiation finished
1257 // If SASL requested but not available, print a warning
1258 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1259 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL authentication currently not supported by server"));
1261 if (_capNegotiationActive) {
1262 showMessage(Message::Server,
1263 BufferInfo::StatusBuffer,
1265 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1266 _capNegotiationActive = false;
1269 endCapNegotiation();
1273 void CoreNetwork::endCapNegotiation()
1275 // If nick registration is already complete, CAP END is not required
1276 if (!_capInitialNegotiationEnded) {
1277 putRawLine(serverEncode(QString("CAP END")));
1278 _capInitialNegotiationEnded = true;
1282 /******** AutoWHO ********/
1284 void CoreNetwork::startAutoWhoCycle()
1286 if (!_autoWhoQueue.isEmpty()) {
1287 _autoWhoCycleTimer.stop();
1290 _autoWhoQueue = channels();
1293 void CoreNetwork::queueAutoWhoOneshot(const QString& name)
1295 // Prepend so these new channels/nicks are the first to be checked
1296 // Don't allow duplicates
1297 if (!_autoWhoQueue.contains(name.toLower())) {
1298 _autoWhoQueue.prepend(name.toLower());
1300 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1301 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1302 setAutoWhoEnabled(true);
1306 void CoreNetwork::setAutoWhoDelay(int delay)
1308 _autoWhoTimer.setInterval(delay * 1000);
1311 void CoreNetwork::setAutoWhoInterval(int interval)
1313 _autoWhoCycleTimer.setInterval(interval * 1000);
1316 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1318 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1319 _autoWhoTimer.start();
1320 else if (!enabled) {
1321 _autoWhoTimer.stop();
1322 _autoWhoCycleTimer.stop();
1326 void CoreNetwork::sendAutoWho()
1328 // Don't send autowho if there are still some pending
1329 if (_autoWhoPending.count())
1332 while (!_autoWhoQueue.isEmpty()) {
1333 QString chanOrNick = _autoWhoQueue.takeFirst();
1334 // Check if it's a known channel or nick
1335 IrcChannel* ircchan = ircChannel(chanOrNick);
1336 IrcUser* ircuser = ircUser(chanOrNick);
1338 // Apply channel limiting rules
1339 // If using away-notify, don't impose channel size limits in order to capture away
1340 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1341 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1342 && !capEnabled(IrcCap::AWAY_NOTIFY))
1344 _autoWhoPending[chanOrNick.toLower()]++;
1347 // Checking a nick, add it to the pending list
1348 _autoWhoPending[ircuser->nick().toLower()]++;
1351 // Not a channel or a nick, skip it
1352 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1355 if (supports("WHOX")) {
1356 // Use WHO extended to poll away users and/or user accounts
1357 // Explicitly only match on nickname ("n"), don't rely on server defaults
1359 // WHO <nickname> n%chtsunfra,<unique_number>
1361 // See http://faerion.sourceforge.net/doc/irc/whox.var
1362 // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1363 // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1364 putRawLine(serverEncode(
1365 QString("WHO %1 n%chtsunfra,%2").arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1368 // Fall back to normal WHO
1370 // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1371 // hostmask, etc. There's nothing we can do about that :(
1373 // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1374 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1379 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1380 // Timer was stopped, means a new cycle is due immediately
1381 // Don't run a new cycle if using away-notify; server will notify as appropriate
1382 _autoWhoCycleTimer.start();
1383 startAutoWhoCycle();
1385 else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1386 // Don't run another who cycle if away-notify is enabled
1387 _autoWhoCycleTimer.stop();
1392 void CoreNetwork::onSslErrors(const QList<QSslError>& sslErrors)
1394 Server server = usedServer();
1395 if (server.sslVerify) {
1396 // Treat the SSL error as a hard error
1397 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1398 "since verification is required");
1399 if (!sslErrors.empty()) {
1400 // Add the error reason if known
1401 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1403 showMessage(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1405 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1406 // validity, network trouble, etc.
1407 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1410 // Treat the SSL error as a warning, continue to connect anyways
1411 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1412 "since verification is not required");
1413 if (!sslErrors.empty()) {
1414 // Add the error reason if known
1415 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1417 showMessage(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1419 // Proceed with the connection
1420 socket.ignoreSslErrors();
1426 void CoreNetwork::checkTokenBucket()
1428 if (_skipMessageRates) {
1429 if (_msgQueue.size() == 0) {
1430 // Message queue emptied; stop the timer and bail out
1431 _tokenBucketTimer.stop();
1434 // Otherwise, we're emptying the queue, continue on as normal
1437 // Process whatever messages are pending
1438 fillBucketAndProcessQueue();
1441 void CoreNetwork::fillBucketAndProcessQueue()
1443 // If there's less tokens than burst size, refill the token bucket by 1
1444 if (_tokenBucket < _burstSize) {
1448 // As long as there's tokens available and messages remaining, sending messages from the queue
1449 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1450 writeToSocket(_msgQueue.takeFirst());
1454 void CoreNetwork::writeToSocket(const QByteArray& data)
1456 // Log the message if enabled and network ID matches or allows all
1457 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1458 // Include network ID
1459 qDebug() << "IRC net" << networkId() << ">>" << data;
1462 socket.write("\r\n");
1463 if (!_skipMessageRates) {
1464 // Only subtract from the token bucket if message rate limiting is enabled
1469 Network::Server CoreNetwork::usedServer() const
1471 if (_lastUsedServerIndex < serverList().count())
1472 return serverList()[_lastUsedServerIndex];
1474 if (!serverList().isEmpty())
1475 return serverList()[0];
1477 return Network::Server();
1480 void CoreNetwork::requestConnect() const
1482 if (_shuttingDown) {
1485 if (connectionState() != Disconnected) {
1486 qWarning() << "Requesting connect while already being connected!";
1489 QMetaObject::invokeMethod(const_cast<CoreNetwork*>(this), "connectToIrc", Qt::QueuedConnection);
1492 void CoreNetwork::requestDisconnect() const
1494 if (_shuttingDown) {
1497 if (connectionState() == Disconnected) {
1498 qWarning() << "Requesting disconnect while not being connected!";
1501 userInputHandler()->handleQuit(BufferInfo(), QString());
1504 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info)
1506 Network::Server currentServer = usedServer();
1507 setNetworkInfo(info);
1508 Core::updateNetwork(coreSession()->user(), info);
1510 // the order of the servers might have changed,
1511 // so we try to find the previously used server
1512 _lastUsedServerIndex = 0;
1513 for (int i = 0; i < serverList().count(); i++) {
1514 Network::Server server = serverList()[i];
1515 if (server.host == currentServer.host && server.port == currentServer.port) {
1516 _lastUsedServerIndex = i;
1522 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString& cmd,
1523 const QString& message,
1524 const std::function<QList<QByteArray>(QString&)>& cmdGenerator)
1526 QString wrkMsg(message);
1527 QList<QList<QByteArray>> msgsToSend;
1529 // do while (wrkMsg.size() > 0)
1531 // First, check to see if the whole message can be sent at once. The
1532 // cmdGenerator function is passed in by the caller and is used to encode
1533 // and encrypt (if applicable) the message, since different callers might
1534 // want to use different encoding or encode different values.
1535 int splitPos = wrkMsg.size();
1536 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1537 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1539 if (initialOverrun) {
1540 // If the message was too long to be sent, first try splitting it along
1541 // word boundaries with QTextBoundaryFinder.
1542 QString splitMsg(wrkMsg);
1543 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1544 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1545 QList<QByteArray> splitMsgEnc;
1546 int overrun = initialOverrun;
1549 splitPos = qtbf.toPreviousBoundary();
1551 // splitPos==-1 means the QTBF couldn't find a split point at all and
1552 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1553 // the string. Neither one of these works for us.
1555 // If a split point could be found, split the message there, calculate the
1556 // overrun, and continue with the loop.
1557 splitMsg = splitMsg.left(splitPos);
1558 splitMsgEnc = cmdGenerator(splitMsg);
1559 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1562 // If a split point could not be found (the beginning of the message
1563 // is reached without finding a split point short enough to send) and we
1564 // are still in Word mode, switch to Grapheme mode. We also need to restore
1565 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1566 // the previous attempt to find a split point.
1567 if (qtbf.type() == QTextBoundaryFinder::Word) {
1569 splitPos = splitMsg.size();
1570 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1571 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1572 qtbf = graphemeQtbf;
1575 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1576 // This should never happen, but it should be handled anyway.
1577 qWarning() << "Unexpected failure to split message!";
1583 // Once a message of sendable length has been found, remove it from the wrkMsg and
1584 // add it to the list of messages to be sent.
1585 wrkMsg.remove(0, splitPos);
1586 msgsToSend.append(splitMsgEnc);
1589 // If the entire remaining message is short enough to be sent all at once, remove
1590 // it from the wrkMsg and add it to the list of messages to be sent.
1591 wrkMsg.remove(0, splitPos);
1592 msgsToSend.append(initialSplitMsgEnc);
1594 } while (wrkMsg.size() > 0);