1 /***************************************************************************
2 * Copyright (C) 2005-2019 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 "ircencoder.h"
34 #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 QHash<IrcTagKey, QString> &tags, const bool prepend)
366 putRawLine(IrcEncoder::writeMessage(tags, prefix, cmd, params), prepend);
369 void CoreNetwork::putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix, const QHash<IrcTagKey, QString> &tags, const bool prependAll)
371 QListIterator<QList<QByteArray>> i(params);
372 while (i.hasNext()) {
373 QList<QByteArray> msg = i.next();
374 putCmd(cmd, msg, prefix, tags, prependAll);
378 void CoreNetwork::setChannelJoined(const QString& channel)
380 queueAutoWhoOneshot(channel); // check this new channel first
382 Core::setChannelPersistent(userId(), networkId(), channel, true);
383 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
386 void CoreNetwork::setChannelParted(const QString& channel)
388 removeChannelKey(channel);
389 _autoWhoQueue.removeAll(channel.toLower());
390 _autoWhoPending.remove(channel.toLower());
392 Core::setChannelPersistent(userId(), networkId(), channel, false);
395 void CoreNetwork::addChannelKey(const QString& channel, const QString& key)
398 removeChannelKey(channel);
401 _channelKeys[channel.toLower()] = key;
405 void CoreNetwork::removeChannelKey(const QString& channel)
407 _channelKeys.remove(channel.toLower());
411 Cipher* CoreNetwork::cipher(const QString& target)
413 if (target.isEmpty())
416 if (!Cipher::neededFeaturesAvailable())
419 auto* channel = qobject_cast<CoreIrcChannel*>(ircChannel(target));
421 return channel->cipher();
423 auto* user = qobject_cast<CoreIrcUser*>(ircUser(target));
425 return user->cipher();
427 else if (!isChannelName(target)) {
428 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
433 QByteArray CoreNetwork::cipherKey(const QString& target) const
435 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
437 return c->cipher()->key();
439 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
441 return u->cipher()->key();
446 void CoreNetwork::setCipherKey(const QString& target, const QByteArray& key)
448 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
450 c->setEncrypted(c->cipher()->setKey(key));
451 coreSession()->setBufferCipher(networkId(), target, key);
455 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
456 if (!u && !isChannelName(target))
457 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
460 u->setEncrypted(u->cipher()->setKey(key));
461 coreSession()->setBufferCipher(networkId(), target, key);
466 bool CoreNetwork::cipherUsesCBC(const QString& target)
468 auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
470 return c->cipher()->usesCBC();
471 auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
473 return u->cipher()->usesCBC();
477 #endif /* HAVE_QCA2 */
479 bool CoreNetwork::setAutoWhoDone(const QString& name)
481 QString chanOrNick = name.toLower();
482 if (_autoWhoPending.value(chanOrNick, 0) <= 0)
484 if (--_autoWhoPending[chanOrNick] <= 0)
485 _autoWhoPending.remove(chanOrNick);
489 void CoreNetwork::setMyNick(const QString& mynick)
491 Network::setMyNick(mynick);
492 if (connectionState() == Network::Initializing)
493 networkInitialized();
496 void CoreNetwork::onSocketHasData()
498 while (socket.canReadLine()) {
499 QByteArray s = socket.readLine();
500 if (s.endsWith("\r\n"))
502 else if (s.endsWith("\n"))
504 NetworkDataEvent* event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
505 event->setTimestamp(QDateTime::currentDateTimeUtc());
506 emit newEvent(event);
510 void CoreNetwork::onSocketError(QAbstractSocket::SocketError error)
512 // Ignore socket closed errors if expected
513 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
517 _previousConnectionAttemptFailed = true;
518 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
519 emit connectionError(socket.errorString());
520 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
521 emitConnectionError(socket.errorString());
522 if (socket.state() < QAbstractSocket::ConnectedState) {
523 onSocketDisconnected();
527 void CoreNetwork::onSocketInitialized()
529 CoreIdentity* identity = identityPtr();
531 qCritical() << "Identity invalid!";
536 Server server = usedServer();
539 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
540 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
541 if (!server.useSsl || !socket.isEncrypted()) {
542 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
545 if (server.useSsl && !socket.isEncrypted()) {
546 // We'll finish setup once we're encrypted, and called again
550 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
553 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
555 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
556 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
557 // force flag to apply user preferences. When making changes, ensure that this still happens!
558 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
559 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
561 updateRateLimiting(true);
562 // Fill up the token bucket as we're connecting from scratch
565 // Request capabilities as per IRCv3.2 specifications
566 // Older servers should ignore this; newer servers won't downgrade to RFC1459
567 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
568 putRawLine(serverEncode(QString("CAP LS 302")));
570 if (!server.password.isEmpty()) {
571 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
574 if (identity->nicks().isEmpty()) {
576 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
579 nick = identity->nicks()[0];
581 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
582 // Only allow strict-compliant idents when strict mode is enabled
583 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(coreSession()->strictCompliantIdent(identity), identity->realName())));
586 void CoreNetwork::onSocketDisconnected()
588 disablePingTimeout();
591 _autoWhoCycleTimer.stop();
592 _autoWhoTimer.stop();
593 _autoWhoQueue.clear();
594 _autoWhoPending.clear();
596 _socketCloseTimer.stop();
598 _tokenBucketTimer.stop();
602 foreach (QString channel, me_->channels())
603 showMessage(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
607 emit disconnected(networkId());
608 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
609 // Reset disconnect expectations
610 _disconnectExpected = false;
611 if (_quitRequested) {
612 _quitRequested = false;
613 setConnectionState(Network::Disconnected);
614 Core::setNetworkConnected(userId(), networkId(), false);
616 else if (_autoReconnectCount != 0) {
617 setConnectionState(Network::Reconnecting);
618 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
619 doAutoReconnect(); // first try is immediate
621 _autoReconnectTimer.start();
625 void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState)
627 Network::ConnectionState state;
628 switch (socketState) {
629 case QAbstractSocket::UnconnectedState:
630 state = Network::Disconnected;
631 onSocketDisconnected();
633 case QAbstractSocket::HostLookupState:
634 case QAbstractSocket::ConnectingState:
635 state = Network::Connecting;
637 case QAbstractSocket::ConnectedState:
638 state = Network::Initializing;
640 case QAbstractSocket::ClosingState:
641 state = Network::Disconnecting;
644 state = Network::Disconnected;
646 setConnectionState(state);
649 void CoreNetwork::networkInitialized()
651 setConnectionState(Network::Initialized);
653 _disconnectExpected = false;
654 _quitRequested = false;
656 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
657 // flag used for initial registration and capability negotiation.
658 updateRateLimiting();
660 if (useAutoReconnect()) {
662 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
665 // restore away state
666 QString awayMsg = Core::awayMessage(userId(), networkId());
667 if (!awayMsg.isEmpty()) {
668 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
669 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
670 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
677 if (networkConfig()->autoWhoEnabled()) {
678 _autoWhoCycleTimer.start();
679 _autoWhoTimer.start();
680 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
683 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
684 Core::setNetworkConnected(userId(), networkId(), true);
687 void CoreNetwork::sendPerform()
689 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
692 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
693 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
696 // restore old user modes if server default mode is set.
699 if (!me_->userModes().isEmpty()) {
703 connect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
704 connect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
709 foreach (QString line, perform()) {
711 userInput(statusBuf, line);
714 // rejoin channels we've been in
715 if (rejoinChannels()) {
716 QStringList channels, keys;
717 foreach (QString chan, coreSession()->persistentChannels(networkId()).keys()) {
718 QString key = channelKey(chan);
719 if (!key.isEmpty()) {
720 channels.prepend(chan);
724 channels.append(chan);
727 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
728 if (!joinString.isEmpty())
729 userInputHandler()->handleJoin(statusBuf, joinString);
733 void CoreNetwork::restoreUserModes()
738 disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
739 disconnect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
741 QString modesDelta = Core::userModes(userId(), networkId());
742 QString currentModes = me_->userModes();
744 QString addModes, removeModes;
745 if (modesDelta.contains('-')) {
746 addModes = modesDelta.section('-', 0, 0);
747 removeModes = modesDelta.section('-', 1);
750 addModes = modesDelta;
753 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
754 if (currentModes.isEmpty())
755 removeModes = QString();
757 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
759 if (addModes.isEmpty() && removeModes.isEmpty())
762 if (!addModes.isEmpty())
763 addModes = '+' + addModes;
764 if (!removeModes.isEmpty())
765 removeModes = '-' + removeModes;
767 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
768 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
771 void CoreNetwork::updateIssuedModes(const QString& requestedModes)
777 for (auto requestedMode : requestedModes) {
778 if (requestedMode == '+') {
782 if (requestedMode == '-') {
787 addModes += requestedMode;
790 removeModes += requestedMode;
794 QString addModesOld = _requestedUserModes.section('-', 0, 0);
795 QString removeModesOld = _requestedUserModes.section('-', 1);
797 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
798 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
799 addModes += addModesOld;
801 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
802 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
803 removeModes += removeModesOld;
805 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
808 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
810 QString persistentUserModes = Core::userModes(userId(), networkId());
812 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
813 QString requestedRemove = _requestedUserModes.section('-', 1);
815 QString persistentAdd, persistentRemove;
816 if (persistentUserModes.contains('-')) {
817 persistentAdd = persistentUserModes.section('-', 0, 0);
818 persistentRemove = persistentUserModes.section('-', 1);
821 persistentAdd = persistentUserModes;
824 // remove modes we didn't issue
825 if (requestedAdd.isEmpty())
826 addModes = QString();
828 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
830 if (requestedRemove.isEmpty())
831 removeModes = QString();
833 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
836 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
837 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
840 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
841 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
843 // update issued mode list
844 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
845 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
846 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
848 persistentAdd += addModes;
849 persistentRemove += removeModes;
850 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
853 void CoreNetwork::resetPersistentModes()
855 _requestedUserModes = QString('-');
856 Core::setUserModes(userId(), networkId(), QString());
859 void CoreNetwork::setUseAutoReconnect(bool use)
861 Network::setUseAutoReconnect(use);
863 _autoReconnectTimer.stop();
866 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
868 Network::setAutoReconnectInterval(interval);
869 _autoReconnectTimer.setInterval(interval * 1000);
872 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
874 Network::setAutoReconnectRetries(retries);
875 if (_autoReconnectCount != 0) {
876 if (unlimitedReconnectRetries())
877 _autoReconnectCount = -1;
879 _autoReconnectCount = autoReconnectRetries();
883 void CoreNetwork::doAutoReconnect()
885 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
886 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
889 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
890 _autoReconnectCount--; // -2 means we delay the next reconnect
894 void CoreNetwork::sendPing()
896 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
897 if (_pingCount != 0) {
898 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
899 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
901 if ((int)_pingCount >= networkConfig()->maxPingCount() && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
902 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
903 // However, to reduce the risk of breaking things by changing past behavior, we still allow
904 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
906 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
907 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
908 // and unable to even handle a ping answer. So we ignore those misses.
909 disconnectFromIrc(false,
910 QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000),
911 true /* withReconnect */);
916 // Don't send pings until the network is initialized
918 // Mark as waiting for a reply
919 _pongReplyPending = true;
920 // Send default timestamp ping
921 userInputHandler()->handlePing(BufferInfo(), QString());
926 void CoreNetwork::enablePingTimeout(bool enable)
929 disablePingTimeout();
932 resetPongReplyPending();
933 if (networkConfig()->pingTimeoutEnabled())
938 void CoreNetwork::disablePingTimeout()
943 resetPongReplyPending();
946 void CoreNetwork::setPingInterval(int interval)
948 _pingTimer.setInterval(interval * 1000);
951 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
953 _pongTimestampValid = validTimestamp;
956 /******** Custom Rate Limiting ********/
958 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
960 // Verify and apply custom rate limiting options, always resetting the delay and burst size
961 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
962 // this may be called while connected to a server.
964 if (useCustomMessageRate() || forceUnlimited) {
965 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
967 _messageDelay = messageRateDelay();
969 _burstSize = messageRateBurstSize();
970 if (_burstSize < 1) {
971 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" << _burstSize;
972 // Can't go slower than one message at a time
976 if (_tokenBucket > _burstSize) {
977 // Don't let the token bucket exceed the maximum
978 _tokenBucket = _burstSize;
979 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
980 // changing the rate-limit settings while connected to a server will incorrectly reset
984 // Toggle the timer according to whether or not rate limiting is enabled
985 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
986 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
987 // Override user preferences if called with force unlimited, only used during connect.
988 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
989 if (_skipMessageRates) {
990 // If the message queue already contains messages, they need sent before disabling the
991 // timer. Set the timer to a rapid pace and let it disable itself.
992 if (!_msgQueue.isEmpty()) {
993 qDebug() << "Outgoing message queue contains messages while disabling rate "
994 "limiting. Sending remaining queued messages...";
995 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
996 // so nothing should cause this to block.. in theory. However, don't directly call
997 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
999 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1000 // Hesitant to change it without a wide variety of situations to verify behavior.
1001 _tokenBucketTimer.start(100);
1004 // No rate limiting, disable the timer
1005 _tokenBucketTimer.stop();
1009 // Rate limiting enabled, enable the timer
1010 _tokenBucketTimer.start(_messageDelay);
1014 // Custom message rates disabled. Go for the default.
1016 _skipMessageRates = false; // Enable rate-limiting by default
1017 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1018 _burstSize = 5; // 5 messages at once
1019 if (_tokenBucket > _burstSize) {
1020 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1022 _tokenBucket = _burstSize;
1023 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1024 // changing the rate-limit settings while connected to a server will incorrectly reset
1025 // the token bucket.
1027 // Rate limiting enabled, enable the timer
1028 _tokenBucketTimer.start(_messageDelay);
1032 void CoreNetwork::resetTokenBucket()
1034 // Fill up the token bucket to the maximum
1035 _tokenBucket = _burstSize;
1038 /******** IRCv3 Capability Negotiation ********/
1040 void CoreNetwork::serverCapAdded(const QString& capability)
1042 // Check if it's a known capability; if so, add it to the list
1043 // Handle special cases first
1044 if (capability == IrcCap::SASL) {
1045 // Only request SASL if it's enabled
1046 if (networkInfo().useSasl)
1047 queueCap(capability);
1049 else if (IrcCap::knownCaps.contains(capability)) {
1050 // Handling for general known capabilities
1051 queueCap(capability);
1055 void CoreNetwork::serverCapAcknowledged(const QString& capability)
1057 // This may be called multiple times in certain situations.
1059 // Handle core-side configuration
1060 if (capability == IrcCap::AWAY_NOTIFY) {
1061 // away-notify enabled, stop the autoWho timers, handle manually
1062 setAutoWhoEnabled(false);
1065 // Handle capabilities that require further messages sent to the IRC server
1066 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1067 if (capability == IrcCap::SASL) {
1068 // If SASL mechanisms specified, limit to what's accepted for authentication
1069 // if the current identity has a cert set, use SASL EXTERNAL
1072 if (!identityPtr()->sslCert().isNull()) {
1073 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1074 // EXTERNAL authentication supported, send request
1075 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1078 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL EXTERNAL authentication not supported"));
1084 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1085 // PLAIN authentication supported, send request
1086 // Only working with PLAIN atm, blowfish later
1087 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1090 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL PLAIN authentication not supported"));
1099 void CoreNetwork::serverCapRemoved(const QString& capability)
1101 // This may be called multiple times in certain situations.
1103 // Handle special cases here
1104 if (capability == IrcCap::AWAY_NOTIFY) {
1105 // away-notify disabled, enable autoWho according to configuration
1106 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1110 void CoreNetwork::queueCap(const QString& capability)
1112 // IRCv3 specs all use lowercase capability names
1113 QString _capLowercase = capability.toLower();
1115 if (capsRequiringConfiguration.contains(_capLowercase)) {
1116 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1117 // so we should negotiate it separately from all other capabilities. Otherwise new
1118 // capabilities will be requested while still configuring the previous one.
1119 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1120 _capsQueuedIndividual.append(_capLowercase);
1124 // The capability doesn't need any special configuration, so it should be safe to try
1125 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1127 if (!_capsQueuedBundled.contains(_capLowercase)) {
1128 _capsQueuedBundled.append(_capLowercase);
1133 QString CoreNetwork::takeQueuedCaps()
1135 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1137 _capsQueuedLastBundle.clear();
1139 // First, negotiate all the standalone capabilities that require additional configuration.
1140 if (!_capsQueuedIndividual.empty()) {
1141 // We have an individual capability available. Take the first and pass it back.
1142 return _capsQueuedIndividual.takeFirst();
1144 else if (!_capsQueuedBundled.empty()) {
1145 // We have capabilities available that can be grouped. Try to fit in as many as within the
1147 // See CoreNetwork::maxCapRequestLength
1149 // Response must have at least one capability regardless of max length for anything to
1151 QString capBundle = _capsQueuedBundled.takeFirst();
1152 QString nextCap("");
1153 while (!_capsQueuedBundled.empty()) {
1154 // As long as capabilities remain, get the next...
1155 nextCap = _capsQueuedBundled.first();
1156 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1157 // [capability + 1 for a space + this new capability] fit within length limits
1158 // Add it to formatted list
1159 capBundle.append(" " + nextCap);
1160 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1161 _capsQueuedLastBundle.append(nextCap);
1162 // Then remove it from the queue
1163 _capsQueuedBundled.removeFirst();
1166 // We've reached the length limit for a single capability request, stop adding more
1170 // Return this space-separated set of capabilities, removing any extra spaces
1171 return capBundle.trimmed();
1174 // No capabilities left to negotiate, return an empty string.
1179 void CoreNetwork::retryCapsIndividually()
1181 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1182 // denied, try each capability individually.
1183 if (_capsQueuedLastBundle.empty()) {
1184 // No most recently tried capability set, just return.
1186 // Note: there's little point in retrying individually requested caps during negotiation.
1187 // We know the individual capability was the one that failed, and it's not likely it'll
1188 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1189 // handling capability removal and addition.
1192 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1193 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1194 // keeping track of which halves of the group fail, dividing the set each time.
1196 // Add most recently tried capability set to individual list, re-requesting them one at a time
1197 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1198 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1199 showMessage(Message::Server,
1200 BufferInfo::StatusBuffer,
1202 tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", ")));
1203 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1204 // need to remove them here.
1205 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1207 _capsQueuedLastBundle.clear();
1210 void CoreNetwork::beginCapNegotiation()
1212 // Don't begin negotiation if no capabilities are queued to request
1213 if (!capNegotiationInProgress()) {
1214 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1215 // normal connection.
1216 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1217 endCapNegotiation();
1221 _capNegotiationActive = true;
1222 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1224 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1225 // comma separator between the two if needed (both individual and bundled caps exist).
1226 QString queuedCapsDisplay = _capsQueuedIndividual.join(", ")
1227 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1228 + _capsQueuedBundled.join(", ");
1229 showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1234 void CoreNetwork::sendNextCap()
1236 if (capNegotiationInProgress()) {
1237 // Request the next set of capabilities and remove them from the list
1238 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1241 // No pending desired capabilities, capability negotiation finished
1242 // If SASL requested but not available, print a warning
1243 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1244 showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL authentication currently not supported by server"));
1246 if (_capNegotiationActive) {
1247 showMessage(Message::Server,
1248 BufferInfo::StatusBuffer,
1250 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1251 _capNegotiationActive = false;
1254 endCapNegotiation();
1258 void CoreNetwork::endCapNegotiation()
1260 // If nick registration is already complete, CAP END is not required
1261 if (!_capInitialNegotiationEnded) {
1262 putRawLine(serverEncode(QString("CAP END")));
1263 _capInitialNegotiationEnded = true;
1267 /******** AutoWHO ********/
1269 void CoreNetwork::startAutoWhoCycle()
1271 if (!_autoWhoQueue.isEmpty()) {
1272 _autoWhoCycleTimer.stop();
1275 _autoWhoQueue = channels();
1278 void CoreNetwork::queueAutoWhoOneshot(const QString& name)
1280 // Prepend so these new channels/nicks are the first to be checked
1281 // Don't allow duplicates
1282 if (!_autoWhoQueue.contains(name.toLower())) {
1283 _autoWhoQueue.prepend(name.toLower());
1285 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1286 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1287 setAutoWhoEnabled(true);
1291 void CoreNetwork::setAutoWhoDelay(int delay)
1293 _autoWhoTimer.setInterval(delay * 1000);
1296 void CoreNetwork::setAutoWhoInterval(int interval)
1298 _autoWhoCycleTimer.setInterval(interval * 1000);
1301 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1303 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1304 _autoWhoTimer.start();
1305 else if (!enabled) {
1306 _autoWhoTimer.stop();
1307 _autoWhoCycleTimer.stop();
1311 void CoreNetwork::sendAutoWho()
1313 // Don't send autowho if there are still some pending
1314 if (_autoWhoPending.count())
1317 while (!_autoWhoQueue.isEmpty()) {
1318 QString chanOrNick = _autoWhoQueue.takeFirst();
1319 // Check if it's a known channel or nick
1320 IrcChannel* ircchan = ircChannel(chanOrNick);
1321 IrcUser* ircuser = ircUser(chanOrNick);
1323 // Apply channel limiting rules
1324 // If using away-notify, don't impose channel size limits in order to capture away
1325 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1326 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1327 && !capEnabled(IrcCap::AWAY_NOTIFY))
1329 _autoWhoPending[chanOrNick.toLower()]++;
1332 // Checking a nick, add it to the pending list
1333 _autoWhoPending[ircuser->nick().toLower()]++;
1336 // Not a channel or a nick, skip it
1337 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1340 if (supports("WHOX")) {
1341 // Use WHO extended to poll away users and/or user accounts
1342 // Explicitly only match on nickname ("n"), don't rely on server defaults
1344 // WHO <nickname> n%chtsunfra,<unique_number>
1346 // See http://faerion.sourceforge.net/doc/irc/whox.var
1347 // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1348 // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1349 putRawLine(serverEncode(
1350 QString("WHO %1 n%chtsunfra,%2").arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1353 // Fall back to normal WHO
1355 // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1356 // hostmask, etc. There's nothing we can do about that :(
1358 // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1359 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1364 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1365 // Timer was stopped, means a new cycle is due immediately
1366 // Don't run a new cycle if using away-notify; server will notify as appropriate
1367 _autoWhoCycleTimer.start();
1368 startAutoWhoCycle();
1370 else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1371 // Don't run another who cycle if away-notify is enabled
1372 _autoWhoCycleTimer.stop();
1377 void CoreNetwork::onSslErrors(const QList<QSslError>& sslErrors)
1379 Server server = usedServer();
1380 if (server.sslVerify) {
1381 // Treat the SSL error as a hard error
1382 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1383 "since verification is required");
1384 if (!sslErrors.empty()) {
1385 // Add the error reason if known
1386 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1388 showMessage(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1390 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1391 // validity, network trouble, etc.
1392 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1395 // Treat the SSL error as a warning, continue to connect anyways
1396 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1397 "since verification is not required");
1398 if (!sslErrors.empty()) {
1399 // Add the error reason if known
1400 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1402 showMessage(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1404 // Proceed with the connection
1405 socket.ignoreSslErrors();
1411 void CoreNetwork::checkTokenBucket()
1413 if (_skipMessageRates) {
1414 if (_msgQueue.size() == 0) {
1415 // Message queue emptied; stop the timer and bail out
1416 _tokenBucketTimer.stop();
1419 // Otherwise, we're emptying the queue, continue on as normal
1422 // Process whatever messages are pending
1423 fillBucketAndProcessQueue();
1426 void CoreNetwork::fillBucketAndProcessQueue()
1428 // If there's less tokens than burst size, refill the token bucket by 1
1429 if (_tokenBucket < _burstSize) {
1433 // As long as there's tokens available and messages remaining, sending messages from the queue
1434 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1435 writeToSocket(_msgQueue.takeFirst());
1439 void CoreNetwork::writeToSocket(const QByteArray& data)
1441 // Log the message if enabled and network ID matches or allows all
1442 if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1443 // Include network ID
1444 qDebug() << "IRC net" << networkId() << ">>" << data;
1447 socket.write("\r\n");
1448 if (!_skipMessageRates) {
1449 // Only subtract from the token bucket if message rate limiting is enabled
1454 Network::Server CoreNetwork::usedServer() const
1456 if (_lastUsedServerIndex < serverList().count())
1457 return serverList()[_lastUsedServerIndex];
1459 if (!serverList().isEmpty())
1460 return serverList()[0];
1462 return Network::Server();
1465 void CoreNetwork::requestConnect() const
1467 if (_shuttingDown) {
1470 if (connectionState() != Disconnected) {
1471 qWarning() << "Requesting connect while already being connected!";
1474 QMetaObject::invokeMethod(const_cast<CoreNetwork*>(this), "connectToIrc", Qt::QueuedConnection);
1477 void CoreNetwork::requestDisconnect() const
1479 if (_shuttingDown) {
1482 if (connectionState() == Disconnected) {
1483 qWarning() << "Requesting disconnect while not being connected!";
1486 userInputHandler()->handleQuit(BufferInfo(), QString());
1489 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info)
1491 Network::Server currentServer = usedServer();
1492 setNetworkInfo(info);
1493 Core::updateNetwork(coreSession()->user(), info);
1495 // the order of the servers might have changed,
1496 // so we try to find the previously used server
1497 _lastUsedServerIndex = 0;
1498 for (int i = 0; i < serverList().count(); i++) {
1499 Network::Server server = serverList()[i];
1500 if (server.host == currentServer.host && server.port == currentServer.port) {
1501 _lastUsedServerIndex = i;
1507 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString& cmd,
1508 const QString& message,
1509 const std::function<QList<QByteArray>(QString&)>& cmdGenerator)
1511 QString wrkMsg(message);
1512 QList<QList<QByteArray>> msgsToSend;
1514 // do while (wrkMsg.size() > 0)
1516 // First, check to see if the whole message can be sent at once. The
1517 // cmdGenerator function is passed in by the caller and is used to encode
1518 // and encrypt (if applicable) the message, since different callers might
1519 // want to use different encoding or encode different values.
1520 int splitPos = wrkMsg.size();
1521 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1522 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1524 if (initialOverrun) {
1525 // If the message was too long to be sent, first try splitting it along
1526 // word boundaries with QTextBoundaryFinder.
1527 QString splitMsg(wrkMsg);
1528 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1529 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1530 QList<QByteArray> splitMsgEnc;
1531 int overrun = initialOverrun;
1534 splitPos = qtbf.toPreviousBoundary();
1536 // splitPos==-1 means the QTBF couldn't find a split point at all and
1537 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1538 // the string. Neither one of these works for us.
1540 // If a split point could be found, split the message there, calculate the
1541 // overrun, and continue with the loop.
1542 splitMsg = splitMsg.left(splitPos);
1543 splitMsgEnc = cmdGenerator(splitMsg);
1544 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1547 // If a split point could not be found (the beginning of the message
1548 // is reached without finding a split point short enough to send) and we
1549 // are still in Word mode, switch to Grapheme mode. We also need to restore
1550 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1551 // the previous attempt to find a split point.
1552 if (qtbf.type() == QTextBoundaryFinder::Word) {
1554 splitPos = splitMsg.size();
1555 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1556 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1557 qtbf = graphemeQtbf;
1560 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1561 // This should never happen, but it should be handled anyway.
1562 qWarning() << "Unexpected failure to split message!";
1568 // Once a message of sendable length has been found, remove it from the wrkMsg and
1569 // add it to the list of messages to be sent.
1570 wrkMsg.remove(0, splitPos);
1571 msgsToSend.append(splitMsgEnc);
1574 // If the entire remaining message is short enough to be sent all at once, remove
1575 // it from the wrkMsg and add it to the list of messages to be sent.
1576 wrkMsg.remove(0, splitPos);
1577 msgsToSend.append(initialSplitMsgEnc);
1579 } while (wrkMsg.size() > 0);