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),
44 _previousConnectionAttemptFailed(false),
45 _lastUsedServerIndex(0),
47 _requestedUserModes('-')
49 // Check if raw IRC logging is enabled
50 _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
51 _debugLogRawNetId = Quassel::optionValue("debug-irc-id").toInt();
53 _autoReconnectTimer.setSingleShot(true);
54 connect(&_socketCloseTimer, &QTimer::timeout, this, &CoreNetwork::onSocketCloseTimeout);
56 setPingInterval(networkConfig()->pingInterval());
57 connect(&_pingTimer, &QTimer::timeout, this, &CoreNetwork::sendPing);
59 setAutoWhoDelay(networkConfig()->autoWhoDelay());
60 setAutoWhoInterval(networkConfig()->autoWhoInterval());
62 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
63 foreach(QString chan, channels.keys()) {
64 _channelKeys[chan.toLower()] = channels[chan];
67 QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
68 foreach(QString buffer, bufferCiphers.keys()) {
69 storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
72 connect(networkConfig(), &NetworkConfig::pingTimeoutEnabledSet, this, &CoreNetwork::enablePingTimeout);
73 connect(networkConfig(), &NetworkConfig::pingIntervalSet, this, &CoreNetwork::setPingInterval);
74 connect(networkConfig(), &NetworkConfig::autoWhoEnabledSet, this, &CoreNetwork::setAutoWhoEnabled);
75 connect(networkConfig(), &NetworkConfig::autoWhoIntervalSet, this, &CoreNetwork::setAutoWhoInterval);
76 connect(networkConfig(), &NetworkConfig::autoWhoDelaySet, this, &CoreNetwork::setAutoWhoDelay);
78 connect(&_autoReconnectTimer, &QTimer::timeout, this, &CoreNetwork::doAutoReconnect);
79 connect(&_autoWhoTimer, &QTimer::timeout, this, &CoreNetwork::sendAutoWho);
80 connect(&_autoWhoCycleTimer, &QTimer::timeout, this, &CoreNetwork::startAutoWhoCycle);
81 connect(&_tokenBucketTimer, &QTimer::timeout, this, &CoreNetwork::checkTokenBucket);
83 connect(&socket, &QAbstractSocket::connected, this, &CoreNetwork::onSocketInitialized);
84 connect(&socket, selectOverload<QAbstractSocket::SocketError>(&QAbstractSocket::error), this, &CoreNetwork::onSocketError);
85 connect(&socket, &QAbstractSocket::stateChanged, this, &CoreNetwork::onSocketStateChanged);
86 connect(&socket, &QIODevice::readyRead, this, &CoreNetwork::onSocketHasData);
88 connect(&socket, &QSslSocket::encrypted, this, &CoreNetwork::onSocketInitialized);
89 connect(&socket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &CoreNetwork::onSslErrors);
91 connect(this, &CoreNetwork::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
93 // Custom rate limiting
94 // These react to the user changing settings in the client
95 connect(this, &Network::useCustomMessageRateSet, this, &CoreNetwork::updateRateLimiting);
96 connect(this, &Network::messageRateBurstSizeSet, this, &CoreNetwork::updateRateLimiting);
97 connect(this, &Network::messageRateDelaySet, this, &CoreNetwork::updateRateLimiting);
98 connect(this, &Network::unlimitedMessageRateSet, this, &CoreNetwork::updateRateLimiting);
100 // IRCv3 capability handling
101 // These react to CAP messages from the server
102 connect(this, &Network::capAdded, this, &CoreNetwork::serverCapAdded);
103 connect(this, &Network::capAcknowledged, this, &CoreNetwork::serverCapAcknowledged);
104 connect(this, &Network::capRemoved, this, &CoreNetwork::serverCapRemoved);
106 if (Quassel::isOptionSet("oidentd")) {
107 connect(this, &CoreNetwork::socketInitialized, Core::instance()->oidentdConfigGenerator(), &OidentdConfigGenerator::addSocket);
108 connect(this, &CoreNetwork::socketDisconnected, Core::instance()->oidentdConfigGenerator(), &OidentdConfigGenerator::removeSocket);
111 if (Quassel::isOptionSet("ident-daemon")) {
112 connect(this, &CoreNetwork::socketInitialized, Core::instance()->identServer(), &IdentServer::addSocket);
113 connect(this, &CoreNetwork::socketDisconnected, Core::instance()->identServer(), &IdentServer::removeSocket);
118 CoreNetwork::~CoreNetwork()
120 // Ensure we don't get any more signals from the socket while shutting down
121 disconnect(&socket, nullptr, this, nullptr);
122 if (!forceDisconnect()) {
123 qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
124 .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
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);
144 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
146 if (!bufferName.isEmpty()) {
147 IrcChannel *channel = ircChannel(bufferName);
149 return channel->decodeString(string);
151 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);
164 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
166 if (!bufferName.isEmpty()) {
167 IrcChannel *channel = ircChannel(bufferName);
169 return channel->encodeString(string);
171 return encodeString(string);
175 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
177 IrcUser *user = ircUser(userNick);
179 return user->encodeString(string);
180 return encodeString(string);
184 void CoreNetwork::connectToIrc(bool reconnecting)
190 if (Core::instance()->identServer()) {
191 _socketId = Core::instance()->identServer()->addWaitingSocket();
194 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
195 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
196 if (unlimitedReconnectRetries())
197 _autoReconnectCount = -1;
199 _autoReconnectCount = autoReconnectRetries();
201 if (serverList().isEmpty()) {
202 qWarning() << "Server list empty, ignoring connect request!";
205 CoreIdentity *identity = identityPtr();
207 qWarning() << "Invalid identity configures, ignoring connect request!";
211 // cleaning up old quit reason
214 // Reset capability negotiation tracking, also handling server changes during reconnect
215 _capsQueuedIndividual.clear();
216 _capsQueuedBundled.clear();
218 _capNegotiationActive = false;
219 _capInitialNegotiationEnded = false;
221 // use a random server?
222 if (useRandomServer()) {
223 _lastUsedServerIndex = qrand() % serverList().size();
225 else if (_previousConnectionAttemptFailed) {
226 // cycle to next server if previous connection attempt failed
227 _previousConnectionAttemptFailed = false;
228 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
229 if (++_lastUsedServerIndex >= serverList().size()) {
230 _lastUsedServerIndex = 0;
234 // Start out with the top server in the list
235 _lastUsedServerIndex = 0;
238 Server server = usedServer();
239 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
240 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
242 if (server.useProxy) {
243 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
244 socket.setProxy(proxy);
247 socket.setProxy(QNetworkProxy::NoProxy);
252 // Reset tracking for valid timestamps in PONG replies
253 setPongTimestampValid(false);
255 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
256 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
257 if (! server.useProxy) {
258 //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
259 //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
260 QHostInfo::fromName(server.host);
264 CoreIdentity *identity = identityPtr();
266 socket.setLocalCertificate(identity->sslCert());
267 socket.setPrivateKey(identity->sslKey());
269 socket.connectToHostEncrypted(server.host, server.port);
272 socket.connectToHost(server.host, server.port);
275 socket.connectToHost(server.host, server.port);
280 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
282 // Disconnecting from the network, should expect a socket close or error
283 _disconnectExpected = true;
284 _quitRequested = requested; // see socketDisconnected();
285 if (!withReconnect) {
286 _autoReconnectTimer.stop();
287 _autoReconnectCount = 0; // prohibiting auto reconnect
289 disablePingTimeout();
296 awayMsg = me_->awayMessage();
297 Core::setAwayMessage(userId(), networkId(), awayMsg);
300 if (reason.isEmpty() && identityPtr())
301 _quitReason = identityPtr()->quitReason();
303 _quitReason = reason;
305 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
306 if (socket.state() == QAbstractSocket::UnconnectedState) {
307 onSocketDisconnected();
310 if (socket.state() == QAbstractSocket::ConnectedState) {
311 // If shutting down, prioritize the QUIT command
312 userInputHandler()->issueQuit(_quitReason, _shuttingDown);
317 if (socket.state() != QAbstractSocket::UnconnectedState) {
318 // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
319 _socketCloseTimer.start(10000);
325 void CoreNetwork::onSocketCloseTimeout()
327 qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
328 .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
333 void CoreNetwork::shutdown()
335 _shuttingDown = true;
336 disconnectFromIrc(false, {}, false);
340 void CoreNetwork::userInput(const BufferInfo &buf, QString msg)
342 userInputHandler()->handleUserInput(buf, msg);
346 void CoreNetwork::putRawLine(const QByteArray &s, bool prepend)
348 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.isEmpty())) {
349 // If there's tokens remaining, ...
350 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
351 // Send the message now.
354 // Otherwise, queue the message for later
356 // Jump to the start, skipping other messages
357 _msgQueue.prepend(s);
359 // Add to back, waiting in order
366 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
370 if (!prefix.isEmpty())
371 msg += ":" + prefix + " ";
372 msg += cmd.toUpper().toLatin1();
374 for (int i = 0; i < params.size(); i++) {
377 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
383 putRawLine(msg, prepend);
387 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
389 QListIterator<QList<QByteArray>> i(params);
390 while (i.hasNext()) {
391 QList<QByteArray> msg = i.next();
392 putCmd(cmd, msg, prefix, prependAll);
397 void CoreNetwork::setChannelJoined(const QString &channel)
399 queueAutoWhoOneshot(channel); // check this new channel first
401 Core::setChannelPersistent(userId(), networkId(), channel, true);
402 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
406 void CoreNetwork::setChannelParted(const QString &channel)
408 removeChannelKey(channel);
409 _autoWhoQueue.removeAll(channel.toLower());
410 _autoWhoPending.remove(channel.toLower());
412 Core::setChannelPersistent(userId(), networkId(), channel, false);
416 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
419 removeChannelKey(channel);
422 _channelKeys[channel.toLower()] = key;
427 void CoreNetwork::removeChannelKey(const QString &channel)
429 _channelKeys.remove(channel.toLower());
434 Cipher *CoreNetwork::cipher(const QString &target)
436 if (target.isEmpty())
439 if (!Cipher::neededFeaturesAvailable())
442 auto *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
444 return channel->cipher();
446 auto *user = qobject_cast<CoreIrcUser *>(ircUser(target));
448 return user->cipher();
449 } else if (!isChannelName(target)) {
450 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
456 QByteArray CoreNetwork::cipherKey(const QString &target) const
458 auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
460 return c->cipher()->key();
462 auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
464 return u->cipher()->key();
470 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
472 auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
474 c->setEncrypted(c->cipher()->setKey(key));
475 coreSession()->setBufferCipher(networkId(), target, key);
479 auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
480 if (!u && !isChannelName(target))
481 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
484 u->setEncrypted(u->cipher()->setKey(key));
485 coreSession()->setBufferCipher(networkId(), target, key);
491 bool CoreNetwork::cipherUsesCBC(const QString &target)
493 auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
495 return c->cipher()->usesCBC();
496 auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
498 return u->cipher()->usesCBC();
502 #endif /* HAVE_QCA2 */
504 bool CoreNetwork::setAutoWhoDone(const QString &name)
506 QString chanOrNick = name.toLower();
507 if (_autoWhoPending.value(chanOrNick, 0) <= 0)
509 if (--_autoWhoPending[chanOrNick] <= 0)
510 _autoWhoPending.remove(chanOrNick);
515 void CoreNetwork::setMyNick(const QString &mynick)
517 Network::setMyNick(mynick);
518 if (connectionState() == Network::Initializing)
519 networkInitialized();
523 void CoreNetwork::onSocketHasData()
525 while (socket.canReadLine()) {
526 QByteArray s = socket.readLine();
527 if (s.endsWith("\r\n"))
529 else if (s.endsWith("\n"))
531 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
532 event->setTimestamp(QDateTime::currentDateTimeUtc());
533 emit newEvent(event);
538 void CoreNetwork::onSocketError(QAbstractSocket::SocketError error)
540 // Ignore socket closed errors if expected
541 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
545 _previousConnectionAttemptFailed = true;
546 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
547 emit connectionError(socket.errorString());
548 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
549 emitConnectionError(socket.errorString());
550 if (socket.state() < QAbstractSocket::ConnectedState) {
551 onSocketDisconnected();
556 void CoreNetwork::onSocketInitialized()
558 CoreIdentity *identity = identityPtr();
560 qCritical() << "Identity invalid!";
565 Server server = usedServer();
568 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
569 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
570 if (!server.useSsl || !socket.isEncrypted()) {
571 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
574 if (server.useSsl && !socket.isEncrypted()) {
575 // We'll finish setup once we're encrypted, and called again
579 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
582 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
584 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
585 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
586 // force flag to apply user preferences. When making changes, ensure that this still happens!
587 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
588 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
590 updateRateLimiting(true);
591 // Fill up the token bucket as we're connecting from scratch
594 // Request capabilities as per IRCv3.2 specifications
595 // Older servers should ignore this; newer servers won't downgrade to RFC1459
596 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
597 putRawLine(serverEncode(QString("CAP LS 302")));
599 if (!server.password.isEmpty()) {
600 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
603 if (identity->nicks().isEmpty()) {
605 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
608 nick = identity->nicks()[0];
610 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
611 // Only allow strict-compliant idents when strict mode is enabled
612 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(
613 coreSession()->strictCompliantIdent(identity),
614 identity->realName())));
618 void CoreNetwork::onSocketDisconnected()
620 disablePingTimeout();
623 _autoWhoCycleTimer.stop();
624 _autoWhoTimer.stop();
625 _autoWhoQueue.clear();
626 _autoWhoPending.clear();
628 _socketCloseTimer.stop();
630 _tokenBucketTimer.stop();
634 foreach(QString channel, me_->channels())
635 showMessage(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
639 emit disconnected(networkId());
640 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
641 // Reset disconnect expectations
642 _disconnectExpected = false;
643 if (_quitRequested) {
644 _quitRequested = false;
645 setConnectionState(Network::Disconnected);
646 Core::setNetworkConnected(userId(), networkId(), false);
648 else if (_autoReconnectCount != 0) {
649 setConnectionState(Network::Reconnecting);
650 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
651 doAutoReconnect(); // first try is immediate
653 _autoReconnectTimer.start();
658 void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState)
660 Network::ConnectionState state;
661 switch (socketState) {
662 case QAbstractSocket::UnconnectedState:
663 state = Network::Disconnected;
664 onSocketDisconnected();
666 case QAbstractSocket::HostLookupState:
667 case QAbstractSocket::ConnectingState:
668 state = Network::Connecting;
670 case QAbstractSocket::ConnectedState:
671 state = Network::Initializing;
673 case QAbstractSocket::ClosingState:
674 state = Network::Disconnecting;
677 state = Network::Disconnected;
679 setConnectionState(state);
683 void CoreNetwork::networkInitialized()
685 setConnectionState(Network::Initialized);
687 _disconnectExpected = false;
688 _quitRequested = false;
690 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
691 // flag used for initial registration and capability negotiation.
692 updateRateLimiting();
694 if (useAutoReconnect()) {
696 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
699 // restore away state
700 QString awayMsg = Core::awayMessage(userId(), networkId());
701 if (!awayMsg.isEmpty()) {
702 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
703 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
704 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
711 if (networkConfig()->autoWhoEnabled()) {
712 _autoWhoCycleTimer.start();
713 _autoWhoTimer.start();
714 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
717 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
718 Core::setNetworkConnected(userId(), networkId(), true);
722 void CoreNetwork::sendPerform()
724 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
727 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
728 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
731 // restore old user modes if server default mode is set.
734 if (!me_->userModes().isEmpty()) {
738 connect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
739 connect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
744 foreach(QString line, perform()) {
745 if (!line.isEmpty()) userInput(statusBuf, line);
748 // rejoin channels we've been in
749 if (rejoinChannels()) {
750 QStringList channels, keys;
751 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
752 QString key = channelKey(chan);
753 if (!key.isEmpty()) {
754 channels.prepend(chan);
758 channels.append(chan);
761 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
762 if (!joinString.isEmpty())
763 userInputHandler()->handleJoin(statusBuf, joinString);
768 void CoreNetwork::restoreUserModes()
773 disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
774 disconnect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
776 QString modesDelta = Core::userModes(userId(), networkId());
777 QString currentModes = me_->userModes();
779 QString addModes, removeModes;
780 if (modesDelta.contains('-')) {
781 addModes = modesDelta.section('-', 0, 0);
782 removeModes = modesDelta.section('-', 1);
785 addModes = modesDelta;
788 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
789 if (currentModes.isEmpty())
790 removeModes = QString();
792 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
794 if (addModes.isEmpty() && removeModes.isEmpty())
797 if (!addModes.isEmpty())
798 addModes = '+' + addModes;
799 if (!removeModes.isEmpty())
800 removeModes = '-' + removeModes;
802 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
803 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
807 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
813 for (auto requestedMode : requestedModes) {
814 if (requestedMode == '+') {
818 if (requestedMode == '-') {
823 addModes += requestedMode;
826 removeModes += requestedMode;
830 QString addModesOld = _requestedUserModes.section('-', 0, 0);
831 QString removeModesOld = _requestedUserModes.section('-', 1);
833 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
834 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
835 addModes += addModesOld;
837 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
838 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
839 removeModes += removeModesOld;
841 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
845 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
847 QString persistentUserModes = Core::userModes(userId(), networkId());
849 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
850 QString requestedRemove = _requestedUserModes.section('-', 1);
852 QString persistentAdd, persistentRemove;
853 if (persistentUserModes.contains('-')) {
854 persistentAdd = persistentUserModes.section('-', 0, 0);
855 persistentRemove = persistentUserModes.section('-', 1);
858 persistentAdd = persistentUserModes;
861 // remove modes we didn't issue
862 if (requestedAdd.isEmpty())
863 addModes = QString();
865 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
867 if (requestedRemove.isEmpty())
868 removeModes = QString();
870 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
873 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
874 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
877 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
878 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
880 // update issued mode list
881 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
882 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
883 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
885 persistentAdd += addModes;
886 persistentRemove += removeModes;
887 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
891 void CoreNetwork::resetPersistentModes()
893 _requestedUserModes = QString('-');
894 Core::setUserModes(userId(), networkId(), QString());
898 void CoreNetwork::setUseAutoReconnect(bool use)
900 Network::setUseAutoReconnect(use);
902 _autoReconnectTimer.stop();
906 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
908 Network::setAutoReconnectInterval(interval);
909 _autoReconnectTimer.setInterval(interval * 1000);
913 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
915 Network::setAutoReconnectRetries(retries);
916 if (_autoReconnectCount != 0) {
917 if (unlimitedReconnectRetries())
918 _autoReconnectCount = -1;
920 _autoReconnectCount = autoReconnectRetries();
925 void CoreNetwork::doAutoReconnect()
927 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
928 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
931 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
932 _autoReconnectCount--; // -2 means we delay the next reconnect
937 void CoreNetwork::sendPing()
939 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
940 if (_pingCount != 0) {
941 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
942 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
944 if ((int)_pingCount >= networkConfig()->maxPingCount()
945 && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
946 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
947 // However, to reduce the risk of breaking things by changing past behavior, we still allow
948 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
950 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
951 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
952 // and unable to even handle a ping answer. So we ignore those misses.
953 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
958 // Don't send pings until the network is initialized
960 // Mark as waiting for a reply
961 _pongReplyPending = true;
962 // Send default timestamp ping
963 userInputHandler()->handlePing(BufferInfo(), QString());
969 void CoreNetwork::enablePingTimeout(bool enable)
972 disablePingTimeout();
975 resetPongReplyPending();
976 if (networkConfig()->pingTimeoutEnabled())
982 void CoreNetwork::disablePingTimeout()
987 resetPongReplyPending();
991 void CoreNetwork::setPingInterval(int interval)
993 _pingTimer.setInterval(interval * 1000);
997 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
999 _pongTimestampValid = validTimestamp;
1003 /******** Custom Rate Limiting ********/
1005 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
1007 // Verify and apply custom rate limiting options, always resetting the delay and burst size
1008 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
1009 // this may be called while connected to a server.
1011 if (useCustomMessageRate() || forceUnlimited) {
1012 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
1014 _messageDelay = messageRateDelay();
1016 _burstSize = messageRateBurstSize();
1017 if (_burstSize < 1) {
1018 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
1020 // Can't go slower than one message at a time
1024 if (_tokenBucket > _burstSize) {
1025 // Don't let the token bucket exceed the maximum
1026 _tokenBucket = _burstSize;
1027 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1028 // changing the rate-limit settings while connected to a server will incorrectly reset
1029 // the token bucket.
1032 // Toggle the timer according to whether or not rate limiting is enabled
1033 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1034 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1035 // Override user preferences if called with force unlimited, only used during connect.
1036 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1037 if (_skipMessageRates) {
1038 // If the message queue already contains messages, they need sent before disabling the
1039 // timer. Set the timer to a rapid pace and let it disable itself.
1040 if (!_msgQueue.isEmpty()) {
1041 qDebug() << "Outgoing message queue contains messages while disabling rate "
1042 "limiting. Sending remaining queued messages...";
1043 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1044 // so nothing should cause this to block.. in theory. However, don't directly call
1045 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1047 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1048 // Hesitant to change it without a wide variety of situations to verify behavior.
1049 _tokenBucketTimer.start(100);
1051 // No rate limiting, disable the timer
1052 _tokenBucketTimer.stop();
1055 // Rate limiting enabled, enable the timer
1056 _tokenBucketTimer.start(_messageDelay);
1059 // Custom message rates disabled. Go for the default.
1061 _skipMessageRates = false; // Enable rate-limiting by default
1062 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1063 _burstSize = 5; // 5 messages at once
1064 if (_tokenBucket > _burstSize) {
1065 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1067 _tokenBucket = _burstSize;
1068 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1069 // changing the rate-limit settings while connected to a server will incorrectly reset
1070 // the token bucket.
1072 // Rate limiting enabled, enable the timer
1073 _tokenBucketTimer.start(_messageDelay);
1077 void CoreNetwork::resetTokenBucket()
1079 // Fill up the token bucket to the maximum
1080 _tokenBucket = _burstSize;
1084 /******** IRCv3 Capability Negotiation ********/
1086 void CoreNetwork::serverCapAdded(const QString &capability)
1088 // Check if it's a known capability; if so, add it to the list
1089 // Handle special cases first
1090 if (capability == IrcCap::SASL) {
1091 // Only request SASL if it's enabled
1092 if (networkInfo().useSasl)
1093 queueCap(capability);
1094 } else if (IrcCap::knownCaps.contains(capability)) {
1095 // Handling for general known capabilities
1096 queueCap(capability);
1100 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1102 // This may be called multiple times in certain situations.
1104 // Handle core-side configuration
1105 if (capability == IrcCap::AWAY_NOTIFY) {
1106 // away-notify enabled, stop the autoWho timers, handle manually
1107 setAutoWhoEnabled(false);
1110 // Handle capabilities that require further messages sent to the IRC server
1111 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1112 if (capability == IrcCap::SASL) {
1113 // If SASL mechanisms specified, limit to what's accepted for authentication
1114 // if the current identity has a cert set, use SASL EXTERNAL
1117 if (!identityPtr()->sslCert().isNull()) {
1118 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1119 // EXTERNAL authentication supported, send request
1120 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1122 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL EXTERNAL authentication not supported"));
1127 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1128 // PLAIN authentication supported, send request
1129 // Only working with PLAIN atm, blowfish later
1130 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1132 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL PLAIN authentication not supported"));
1141 void CoreNetwork::serverCapRemoved(const QString &capability)
1143 // This may be called multiple times in certain situations.
1145 // Handle special cases here
1146 if (capability == IrcCap::AWAY_NOTIFY) {
1147 // away-notify disabled, enable autoWho according to configuration
1148 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1152 void CoreNetwork::queueCap(const QString &capability)
1154 // IRCv3 specs all use lowercase capability names
1155 QString _capLowercase = capability.toLower();
1157 if(capsRequiringConfiguration.contains(_capLowercase)) {
1158 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1159 // so we should negotiate it separately from all other capabilities. Otherwise new
1160 // capabilities will be requested while still configuring the previous one.
1161 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1162 _capsQueuedIndividual.append(_capLowercase);
1165 // The capability doesn't need any special configuration, so it should be safe to try
1166 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1168 if (!_capsQueuedBundled.contains(_capLowercase)) {
1169 _capsQueuedBundled.append(_capLowercase);
1174 QString CoreNetwork::takeQueuedCaps()
1176 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1178 _capsQueuedLastBundle.clear();
1180 // First, negotiate all the standalone capabilities that require additional configuration.
1181 if (!_capsQueuedIndividual.empty()) {
1182 // We have an individual capability available. Take the first and pass it back.
1183 return _capsQueuedIndividual.takeFirst();
1184 } else if (!_capsQueuedBundled.empty()) {
1185 // We have capabilities available that can be grouped. Try to fit in as many as within the
1187 // See CoreNetwork::maxCapRequestLength
1189 // Response must have at least one capability regardless of max length for anything to
1191 QString capBundle = _capsQueuedBundled.takeFirst();
1192 QString nextCap("");
1193 while (!_capsQueuedBundled.empty()) {
1194 // As long as capabilities remain, get the next...
1195 nextCap = _capsQueuedBundled.first();
1196 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1197 // [capability + 1 for a space + this new capability] fit within length limits
1198 // Add it to formatted list
1199 capBundle.append(" " + nextCap);
1200 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1201 _capsQueuedLastBundle.append(nextCap);
1202 // Then remove it from the queue
1203 _capsQueuedBundled.removeFirst();
1205 // We've reached the length limit for a single capability request, stop adding more
1209 // Return this space-separated set of capabilities, removing any extra spaces
1210 return capBundle.trimmed();
1212 // No capabilities left to negotiate, return an empty string.
1217 void CoreNetwork::retryCapsIndividually()
1219 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1220 // denied, try each capability individually.
1221 if (_capsQueuedLastBundle.empty()) {
1222 // No most recently tried capability set, just return.
1224 // Note: there's little point in retrying individually requested caps during negotiation.
1225 // We know the individual capability was the one that failed, and it's not likely it'll
1226 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1227 // handling capability removal and addition.
1230 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1231 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1232 // keeping track of which halves of the group fail, dividing the set each time.
1234 // Add most recently tried capability set to individual list, re-requesting them one at a time
1235 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1236 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1237 showMessage(Message::Server, BufferInfo::StatusBuffer, "",
1238 tr("Could not negotiate some capabilities, retrying individually (%1)...")
1239 .arg(_capsQueuedLastBundle.join(", ")));
1240 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1241 // need to remove them here.
1242 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1244 _capsQueuedLastBundle.clear();
1247 void CoreNetwork::beginCapNegotiation()
1249 // Don't begin negotiation if no capabilities are queued to request
1250 if (!capNegotiationInProgress()) {
1251 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1252 // normal connection.
1253 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1254 endCapNegotiation();
1258 _capNegotiationActive = true;
1259 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1261 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1262 // comma separator between the two if needed (both individual and bundled caps exist).
1263 QString queuedCapsDisplay =
1264 _capsQueuedIndividual.join(", ")
1265 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1266 + _capsQueuedBundled.join(", ");
1267 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1272 void CoreNetwork::sendNextCap()
1274 if (capNegotiationInProgress()) {
1275 // Request the next set of capabilities and remove them from the list
1276 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1278 // No pending desired capabilities, capability negotiation finished
1279 // If SASL requested but not available, print a warning
1280 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1281 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL authentication currently not supported by server"));
1283 if (_capNegotiationActive) {
1284 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1285 _capNegotiationActive = false;
1288 endCapNegotiation();
1292 void CoreNetwork::endCapNegotiation()
1294 // If nick registration is already complete, CAP END is not required
1295 if (!_capInitialNegotiationEnded) {
1296 putRawLine(serverEncode(QString("CAP END")));
1297 _capInitialNegotiationEnded = true;
1301 /******** AutoWHO ********/
1303 void CoreNetwork::startAutoWhoCycle()
1305 if (!_autoWhoQueue.isEmpty()) {
1306 _autoWhoCycleTimer.stop();
1309 _autoWhoQueue = channels();
1312 void CoreNetwork::queueAutoWhoOneshot(const QString &name)
1314 // Prepend so these new channels/nicks are the first to be checked
1315 // Don't allow duplicates
1316 if (!_autoWhoQueue.contains(name.toLower())) {
1317 _autoWhoQueue.prepend(name.toLower());
1319 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1320 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1321 setAutoWhoEnabled(true);
1326 void CoreNetwork::setAutoWhoDelay(int delay)
1328 _autoWhoTimer.setInterval(delay * 1000);
1332 void CoreNetwork::setAutoWhoInterval(int interval)
1334 _autoWhoCycleTimer.setInterval(interval * 1000);
1338 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1340 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1341 _autoWhoTimer.start();
1342 else if (!enabled) {
1343 _autoWhoTimer.stop();
1344 _autoWhoCycleTimer.stop();
1349 void CoreNetwork::sendAutoWho()
1351 // Don't send autowho if there are still some pending
1352 if (_autoWhoPending.count())
1355 while (!_autoWhoQueue.isEmpty()) {
1356 QString chanOrNick = _autoWhoQueue.takeFirst();
1357 // Check if it's a known channel or nick
1358 IrcChannel *ircchan = ircChannel(chanOrNick);
1359 IrcUser *ircuser = ircUser(chanOrNick);
1361 // Apply channel limiting rules
1362 // If using away-notify, don't impose channel size limits in order to capture away
1363 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1364 if (networkConfig()->autoWhoNickLimit() > 0
1365 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1366 && !capEnabled(IrcCap::AWAY_NOTIFY))
1368 _autoWhoPending[chanOrNick.toLower()]++;
1369 } else if (ircuser) {
1370 // Checking a nick, add it to the pending list
1371 _autoWhoPending[ircuser->nick().toLower()]++;
1373 // Not a channel or a nick, skip it
1374 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1377 if (supports("WHOX")) {
1378 // Use WHO extended to poll away users and/or user accounts
1379 // Explicitly only match on nickname ("n"), don't rely on server defaults
1381 // WHO <nickname> n%chtsunfra,<unique_number>
1383 // See http://faerion.sourceforge.net/doc/irc/whox.var
1384 // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1385 // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1386 putRawLine(serverEncode(QString("WHO %1 n%chtsunfra,%2")
1387 .arg(serverEncode(chanOrNick),
1388 QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1390 // Fall back to normal WHO
1392 // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1393 // hostmask, etc. There's nothing we can do about that :(
1395 // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1396 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1401 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1402 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1403 // Timer was stopped, means a new cycle is due immediately
1404 // Don't run a new cycle if using away-notify; server will notify as appropriate
1405 _autoWhoCycleTimer.start();
1406 startAutoWhoCycle();
1407 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1408 // Don't run another who cycle if away-notify is enabled
1409 _autoWhoCycleTimer.stop();
1415 void CoreNetwork::onSslErrors(const QList<QSslError> &sslErrors)
1417 Server server = usedServer();
1418 if (server.sslVerify) {
1419 // Treat the SSL error as a hard error
1420 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1421 "since verification is required");
1422 if (!sslErrors.empty()) {
1423 // Add the error reason if known
1424 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1426 showMessage(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1428 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1429 // validity, network trouble, etc.
1430 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1432 // Treat the SSL error as a warning, continue to connect anyways
1433 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1434 "since verification is not required");
1435 if (!sslErrors.empty()) {
1436 // Add the error reason if known
1437 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1439 showMessage(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1441 // Proceed with the connection
1442 socket.ignoreSslErrors();
1449 void CoreNetwork::checkTokenBucket()
1451 if (_skipMessageRates) {
1452 if (_msgQueue.size() == 0) {
1453 // Message queue emptied; stop the timer and bail out
1454 _tokenBucketTimer.stop();
1457 // Otherwise, we're emptying the queue, continue on as normal
1460 // Process whatever messages are pending
1461 fillBucketAndProcessQueue();
1465 void CoreNetwork::fillBucketAndProcessQueue()
1467 // If there's less tokens than burst size, refill the token bucket by 1
1468 if (_tokenBucket < _burstSize) {
1472 // As long as there's tokens available and messages remaining, sending messages from the queue
1473 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1474 writeToSocket(_msgQueue.takeFirst());
1479 void CoreNetwork::writeToSocket(const QByteArray &data)
1481 // Log the message if enabled and network ID matches or allows all
1483 && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1484 // Include network ID
1485 qDebug() << "IRC net" << networkId() << ">>" << data;
1488 socket.write("\r\n");
1489 if (!_skipMessageRates) {
1490 // Only subtract from the token bucket if message rate limiting is enabled
1496 Network::Server CoreNetwork::usedServer() const
1498 if (_lastUsedServerIndex < serverList().count())
1499 return serverList()[_lastUsedServerIndex];
1501 if (!serverList().isEmpty())
1502 return serverList()[0];
1504 return Network::Server();
1508 void CoreNetwork::requestConnect() const
1510 if (_shuttingDown) {
1513 if (connectionState() != Disconnected) {
1514 qWarning() << "Requesting connect while already being connected!";
1517 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1521 void CoreNetwork::requestDisconnect() const
1523 if (_shuttingDown) {
1526 if (connectionState() == Disconnected) {
1527 qWarning() << "Requesting disconnect while not being connected!";
1530 userInputHandler()->handleQuit(BufferInfo(), QString());
1534 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1536 Network::Server currentServer = usedServer();
1537 setNetworkInfo(info);
1538 Core::updateNetwork(coreSession()->user(), info);
1540 // the order of the servers might have changed,
1541 // so we try to find the previously used server
1542 _lastUsedServerIndex = 0;
1543 for (int i = 0; i < serverList().count(); i++) {
1544 Network::Server server = serverList()[i];
1545 if (server.host == currentServer.host && server.port == currentServer.port) {
1546 _lastUsedServerIndex = i;
1553 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, const std::function<QList<QByteArray>(QString &)> &cmdGenerator)
1555 QString wrkMsg(message);
1556 QList<QList<QByteArray>> msgsToSend;
1558 // do while (wrkMsg.size() > 0)
1560 // First, check to see if the whole message can be sent at once. The
1561 // cmdGenerator function is passed in by the caller and is used to encode
1562 // and encrypt (if applicable) the message, since different callers might
1563 // want to use different encoding or encode different values.
1564 int splitPos = wrkMsg.size();
1565 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1566 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1568 if (initialOverrun) {
1569 // If the message was too long to be sent, first try splitting it along
1570 // word boundaries with QTextBoundaryFinder.
1571 QString splitMsg(wrkMsg);
1572 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1573 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1574 QList<QByteArray> splitMsgEnc;
1575 int overrun = initialOverrun;
1578 splitPos = qtbf.toPreviousBoundary();
1580 // splitPos==-1 means the QTBF couldn't find a split point at all and
1581 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1582 // the string. Neither one of these works for us.
1584 // If a split point could be found, split the message there, calculate the
1585 // overrun, and continue with the loop.
1586 splitMsg = splitMsg.left(splitPos);
1587 splitMsgEnc = cmdGenerator(splitMsg);
1588 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1591 // If a split point could not be found (the beginning of the message
1592 // is reached without finding a split point short enough to send) and we
1593 // are still in Word mode, switch to Grapheme mode. We also need to restore
1594 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1595 // the previous attempt to find a split point.
1596 if (qtbf.type() == QTextBoundaryFinder::Word) {
1598 splitPos = splitMsg.size();
1599 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1600 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1601 qtbf = graphemeQtbf;
1604 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1605 // This should never happen, but it should be handled anyway.
1606 qWarning() << "Unexpected failure to split message!";
1612 // Once a message of sendable length has been found, remove it from the wrkMsg and
1613 // add it to the list of messages to be sent.
1614 wrkMsg.remove(0, splitPos);
1615 msgsToSend.append(splitMsgEnc);
1618 // If the entire remaining message is short enough to be sent all at once, remove
1619 // it from the wrkMsg and add it to the list of messages to be sent.
1620 wrkMsg.remove(0, splitPos);
1621 msgsToSend.append(initialSplitMsgEnc);
1623 } while (wrkMsg.size() > 0);