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 INIT_SYNCABLE_OBJECT(CoreNetwork)
37 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
38 : Network(networkid, session),
39 _coreSession(session),
40 _userInputHandler(new CoreUserInputHandler(this)),
41 _autoReconnectCount(0),
42 _quitRequested(false),
43 _disconnectExpected(false),
45 _previousConnectionAttemptFailed(false),
46 _lastUsedServerIndex(0),
48 _requestedUserModes('-')
50 // Check if raw IRC logging is enabled
51 _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
52 _debugLogRawNetId = Quassel::optionValue("debug-irc-id").toInt();
54 _autoReconnectTimer.setSingleShot(true);
55 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
57 setPingInterval(networkConfig()->pingInterval());
58 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
60 setAutoWhoDelay(networkConfig()->autoWhoDelay());
61 setAutoWhoInterval(networkConfig()->autoWhoInterval());
63 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
64 foreach(QString chan, channels.keys()) {
65 _channelKeys[chan.toLower()] = channels[chan];
68 QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
69 foreach(QString buffer, bufferCiphers.keys()) {
70 storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
73 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
74 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
75 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
76 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
77 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
79 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
80 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
81 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
82 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(checkTokenBucket()));
84 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
85 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
86 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
87 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
89 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
90 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
92 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
94 // Custom rate limiting
95 // These react to the user changing settings in the client
96 connect(this, SIGNAL(useCustomMessageRateSet(bool)), SLOT(updateRateLimiting()));
97 connect(this, SIGNAL(messageRateBurstSizeSet(quint32)), SLOT(updateRateLimiting()));
98 connect(this, SIGNAL(messageRateDelaySet(quint32)), SLOT(updateRateLimiting()));
99 connect(this, SIGNAL(unlimitedMessageRateSet(bool)), SLOT(updateRateLimiting()));
101 // IRCv3 capability handling
102 // These react to CAP messages from the server
103 connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
104 connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
105 connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
107 if (Quassel::isOptionSet("oidentd")) {
108 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
109 Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Qt::BlockingQueuedConnection);
110 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
111 Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)));
114 if (Quassel::isOptionSet("ident-daemon")) {
115 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
116 Core::instance()->identServer(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Qt::BlockingQueuedConnection);
117 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
118 Core::instance()->identServer(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)));
123 CoreNetwork::~CoreNetwork()
125 // Ensure we don't get any more signals from the socket while shutting down
126 disconnect(&socket, nullptr, this, nullptr);
127 if (!forceDisconnect()) {
128 qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
129 .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
134 bool CoreNetwork::forceDisconnect(int msecs)
136 if (socket.state() == QAbstractSocket::UnconnectedState) {
137 // Socket already disconnected.
140 // Request a socket-level disconnect if not already happened
141 socket.disconnectFromHost();
142 if (socket.state() != QAbstractSocket::UnconnectedState) {
143 return socket.waitForDisconnected(msecs);
149 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
151 if (!bufferName.isEmpty()) {
152 IrcChannel *channel = ircChannel(bufferName);
154 return channel->decodeString(string);
156 return decodeString(string);
160 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
162 IrcUser *user = ircUser(userNick);
164 return user->decodeString(string);
165 return decodeString(string);
169 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
171 if (!bufferName.isEmpty()) {
172 IrcChannel *channel = ircChannel(bufferName);
174 return channel->encodeString(string);
176 return encodeString(string);
180 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
182 IrcUser *user = ircUser(userNick);
184 return user->encodeString(string);
185 return encodeString(string);
189 void CoreNetwork::connectToIrc(bool reconnecting)
195 if (Core::instance()->identServer()) {
196 _socketId = Core::instance()->identServer()->addWaitingSocket();
199 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
200 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
201 if (unlimitedReconnectRetries())
202 _autoReconnectCount = -1;
204 _autoReconnectCount = autoReconnectRetries();
206 if (serverList().isEmpty()) {
207 qWarning() << "Server list empty, ignoring connect request!";
210 CoreIdentity *identity = identityPtr();
212 qWarning() << "Invalid identity configures, ignoring connect request!";
216 // cleaning up old quit reason
219 // Reset capability negotiation tracking, also handling server changes during reconnect
220 _capsQueuedIndividual.clear();
221 _capsQueuedBundled.clear();
223 _capNegotiationActive = false;
224 _capInitialNegotiationEnded = false;
226 // use a random server?
227 if (useRandomServer()) {
228 _lastUsedServerIndex = qrand() % serverList().size();
230 else if (_previousConnectionAttemptFailed) {
231 // cycle to next server if previous connection attempt failed
232 _previousConnectionAttemptFailed = false;
233 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
234 if (++_lastUsedServerIndex >= serverList().size()) {
235 _lastUsedServerIndex = 0;
239 // Start out with the top server in the list
240 _lastUsedServerIndex = 0;
243 Server server = usedServer();
244 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
245 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
247 if (server.useProxy) {
248 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
249 socket.setProxy(proxy);
252 socket.setProxy(QNetworkProxy::NoProxy);
257 // Reset tracking for valid timestamps in PONG replies
258 setPongTimestampValid(false);
260 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
261 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
262 if (! server.useProxy) {
263 //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
264 //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
265 QHostInfo::fromName(server.host);
269 CoreIdentity *identity = identityPtr();
271 socket.setLocalCertificate(identity->sslCert());
272 socket.setPrivateKey(identity->sslKey());
274 socket.connectToHostEncrypted(server.host, server.port);
277 socket.connectToHost(server.host, server.port);
280 socket.connectToHost(server.host, server.port);
285 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
287 // Disconnecting from the network, should expect a socket close or error
288 _disconnectExpected = true;
289 _quitRequested = requested; // see socketDisconnected();
290 if (!withReconnect) {
291 _autoReconnectTimer.stop();
292 _autoReconnectCount = 0; // prohibiting auto reconnect
294 disablePingTimeout();
301 awayMsg = me_->awayMessage();
302 Core::setAwayMessage(userId(), networkId(), awayMsg);
305 if (reason.isEmpty() && identityPtr())
306 _quitReason = identityPtr()->quitReason();
308 _quitReason = reason;
310 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
311 if (socket.state() == QAbstractSocket::UnconnectedState) {
312 socketDisconnected();
315 if (socket.state() == QAbstractSocket::ConnectedState) {
316 // If shutting down, prioritize the QUIT command
317 userInputHandler()->issueQuit(_quitReason, _shuttingDown);
322 if (socket.state() != QAbstractSocket::UnconnectedState) {
323 // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
324 _socketCloseTimer.start(10000);
330 void CoreNetwork::socketCloseTimeout()
332 qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
333 .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
338 void CoreNetwork::shutdown()
340 _shuttingDown = true;
341 disconnectFromIrc(false, {}, false);
345 void CoreNetwork::userInput(BufferInfo buf, QString msg)
347 userInputHandler()->handleUserInput(buf, msg);
351 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
353 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.size() == 0)) {
354 // If there's tokens remaining, ...
355 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
356 // Send the message now.
359 // Otherwise, queue the message for later
361 // Jump to the start, skipping other messages
362 _msgQueue.prepend(s);
364 // Add to back, waiting in order
371 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
375 if (!prefix.isEmpty())
376 msg += ":" + prefix + " ";
377 msg += cmd.toUpper().toLatin1();
379 for (int i = 0; i < params.size(); i++) {
382 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
388 putRawLine(msg, prepend);
392 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
394 QListIterator<QList<QByteArray>> i(params);
395 while (i.hasNext()) {
396 QList<QByteArray> msg = i.next();
397 putCmd(cmd, msg, prefix, prependAll);
402 void CoreNetwork::setChannelJoined(const QString &channel)
404 queueAutoWhoOneshot(channel); // check this new channel first
406 Core::setChannelPersistent(userId(), networkId(), channel, true);
407 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
411 void CoreNetwork::setChannelParted(const QString &channel)
413 removeChannelKey(channel);
414 _autoWhoQueue.removeAll(channel.toLower());
415 _autoWhoPending.remove(channel.toLower());
417 Core::setChannelPersistent(userId(), networkId(), channel, false);
421 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
424 removeChannelKey(channel);
427 _channelKeys[channel.toLower()] = key;
432 void CoreNetwork::removeChannelKey(const QString &channel)
434 _channelKeys.remove(channel.toLower());
439 Cipher *CoreNetwork::cipher(const QString &target)
441 if (target.isEmpty())
444 if (!Cipher::neededFeaturesAvailable())
447 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
449 return channel->cipher();
451 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
453 return user->cipher();
454 } else if (!isChannelName(target)) {
455 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
461 QByteArray CoreNetwork::cipherKey(const QString &target) const
463 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
465 return c->cipher()->key();
467 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
469 return u->cipher()->key();
475 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
477 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
479 c->setEncrypted(c->cipher()->setKey(key));
480 coreSession()->setBufferCipher(networkId(), target, key);
484 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
485 if (!u && !isChannelName(target))
486 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
489 u->setEncrypted(u->cipher()->setKey(key));
490 coreSession()->setBufferCipher(networkId(), target, key);
496 bool CoreNetwork::cipherUsesCBC(const QString &target)
498 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
500 return c->cipher()->usesCBC();
501 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
503 return u->cipher()->usesCBC();
507 #endif /* HAVE_QCA2 */
509 bool CoreNetwork::setAutoWhoDone(const QString &name)
511 QString chanOrNick = name.toLower();
512 if (_autoWhoPending.value(chanOrNick, 0) <= 0)
514 if (--_autoWhoPending[chanOrNick] <= 0)
515 _autoWhoPending.remove(chanOrNick);
520 void CoreNetwork::setMyNick(const QString &mynick)
522 Network::setMyNick(mynick);
523 if (connectionState() == Network::Initializing)
524 networkInitialized();
528 void CoreNetwork::socketHasData()
530 while (socket.canReadLine()) {
531 QByteArray s = socket.readLine();
532 if (s.endsWith("\r\n"))
534 else if (s.endsWith("\n"))
536 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
537 event->setTimestamp(QDateTime::currentDateTimeUtc());
538 emit newEvent(event);
543 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
545 // Ignore socket closed errors if expected
546 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
550 _previousConnectionAttemptFailed = true;
551 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
552 emit connectionError(socket.errorString());
553 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
554 emitConnectionError(socket.errorString());
555 if (socket.state() < QAbstractSocket::ConnectedState) {
556 socketDisconnected();
561 void CoreNetwork::socketInitialized()
563 CoreIdentity *identity = identityPtr();
565 qCritical() << "Identity invalid!";
570 Server server = usedServer();
573 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
574 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
575 if (!server.useSsl || !socket.isEncrypted()) {
576 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
579 if (server.useSsl && !socket.isEncrypted()) {
580 // We'll finish setup once we're encrypted, and called again
584 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
587 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
589 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
590 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
591 // force flag to apply user preferences. When making changes, ensure that this still happens!
592 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
593 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
595 updateRateLimiting(true);
596 // Fill up the token bucket as we're connecting from scratch
599 // Request capabilities as per IRCv3.2 specifications
600 // Older servers should ignore this; newer servers won't downgrade to RFC1459
601 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
602 putRawLine(serverEncode(QString("CAP LS 302")));
604 if (!server.password.isEmpty()) {
605 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
608 if (identity->nicks().isEmpty()) {
610 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
613 nick = identity->nicks()[0];
615 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
616 // Only allow strict-compliant idents when strict mode is enabled
617 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(
618 coreSession()->strictCompliantIdent(identity),
619 identity->realName())));
623 void CoreNetwork::socketDisconnected()
625 disablePingTimeout();
628 _autoWhoCycleTimer.stop();
629 _autoWhoTimer.stop();
630 _autoWhoQueue.clear();
631 _autoWhoPending.clear();
633 _socketCloseTimer.stop();
635 _tokenBucketTimer.stop();
639 foreach(QString channel, me_->channels())
640 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
644 emit disconnected(networkId());
645 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
646 // Reset disconnect expectations
647 _disconnectExpected = false;
648 if (_quitRequested) {
649 _quitRequested = false;
650 setConnectionState(Network::Disconnected);
651 Core::setNetworkConnected(userId(), networkId(), false);
653 else if (_autoReconnectCount != 0) {
654 setConnectionState(Network::Reconnecting);
655 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
656 doAutoReconnect(); // first try is immediate
658 _autoReconnectTimer.start();
663 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
665 Network::ConnectionState state;
666 switch (socketState) {
667 case QAbstractSocket::UnconnectedState:
668 state = Network::Disconnected;
669 socketDisconnected();
671 case QAbstractSocket::HostLookupState:
672 case QAbstractSocket::ConnectingState:
673 state = Network::Connecting;
675 case QAbstractSocket::ConnectedState:
676 state = Network::Initializing;
678 case QAbstractSocket::ClosingState:
679 state = Network::Disconnecting;
682 state = Network::Disconnected;
684 setConnectionState(state);
688 void CoreNetwork::networkInitialized()
690 setConnectionState(Network::Initialized);
692 _disconnectExpected = false;
693 _quitRequested = false;
695 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
696 // flag used for initial registration and capability negotiation.
697 updateRateLimiting();
699 if (useAutoReconnect()) {
701 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
704 // restore away state
705 QString awayMsg = Core::awayMessage(userId(), networkId());
706 if (!awayMsg.isEmpty()) {
707 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
708 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
709 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
716 if (networkConfig()->autoWhoEnabled()) {
717 _autoWhoCycleTimer.start();
718 _autoWhoTimer.start();
719 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
722 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
723 Core::setNetworkConnected(userId(), networkId(), true);
727 void CoreNetwork::sendPerform()
729 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
732 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
733 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
736 // restore old user modes if server default mode is set.
739 if (!me_->userModes().isEmpty()) {
743 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
744 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
749 foreach(QString line, perform()) {
750 if (!line.isEmpty()) userInput(statusBuf, line);
753 // rejoin channels we've been in
754 if (rejoinChannels()) {
755 QStringList channels, keys;
756 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
757 QString key = channelKey(chan);
758 if (!key.isEmpty()) {
759 channels.prepend(chan);
763 channels.append(chan);
766 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
767 if (!joinString.isEmpty())
768 userInputHandler()->handleJoin(statusBuf, joinString);
773 void CoreNetwork::restoreUserModes()
778 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
779 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
781 QString modesDelta = Core::userModes(userId(), networkId());
782 QString currentModes = me_->userModes();
784 QString addModes, removeModes;
785 if (modesDelta.contains('-')) {
786 addModes = modesDelta.section('-', 0, 0);
787 removeModes = modesDelta.section('-', 1);
790 addModes = modesDelta;
793 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
794 if (currentModes.isEmpty())
795 removeModes = QString();
797 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
799 if (addModes.isEmpty() && removeModes.isEmpty())
802 if (!addModes.isEmpty())
803 addModes = '+' + addModes;
804 if (!removeModes.isEmpty())
805 removeModes = '-' + removeModes;
807 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
808 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
812 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
818 for (int i = 0; i < requestedModes.length(); i++) {
819 if (requestedModes[i] == '+') {
823 if (requestedModes[i] == '-') {
828 addModes += requestedModes[i];
831 removeModes += requestedModes[i];
835 QString addModesOld = _requestedUserModes.section('-', 0, 0);
836 QString removeModesOld = _requestedUserModes.section('-', 1);
838 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
839 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
840 addModes += addModesOld;
842 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
843 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
844 removeModes += removeModesOld;
846 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
850 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
852 QString persistentUserModes = Core::userModes(userId(), networkId());
854 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
855 QString requestedRemove = _requestedUserModes.section('-', 1);
857 QString persistentAdd, persistentRemove;
858 if (persistentUserModes.contains('-')) {
859 persistentAdd = persistentUserModes.section('-', 0, 0);
860 persistentRemove = persistentUserModes.section('-', 1);
863 persistentAdd = persistentUserModes;
866 // remove modes we didn't issue
867 if (requestedAdd.isEmpty())
868 addModes = QString();
870 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
872 if (requestedRemove.isEmpty())
873 removeModes = QString();
875 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
878 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
879 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
882 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
883 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
885 // update issued mode list
886 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
887 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
888 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
890 persistentAdd += addModes;
891 persistentRemove += removeModes;
892 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
896 void CoreNetwork::resetPersistentModes()
898 _requestedUserModes = QString('-');
899 Core::setUserModes(userId(), networkId(), QString());
903 void CoreNetwork::setUseAutoReconnect(bool use)
905 Network::setUseAutoReconnect(use);
907 _autoReconnectTimer.stop();
911 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
913 Network::setAutoReconnectInterval(interval);
914 _autoReconnectTimer.setInterval(interval * 1000);
918 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
920 Network::setAutoReconnectRetries(retries);
921 if (_autoReconnectCount != 0) {
922 if (unlimitedReconnectRetries())
923 _autoReconnectCount = -1;
925 _autoReconnectCount = autoReconnectRetries();
930 void CoreNetwork::doAutoReconnect()
932 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
933 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
936 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
937 _autoReconnectCount--; // -2 means we delay the next reconnect
942 void CoreNetwork::sendPing()
944 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
945 if (_pingCount != 0) {
946 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
947 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
949 if ((int)_pingCount >= networkConfig()->maxPingCount()
950 && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
951 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
952 // However, to reduce the risk of breaking things by changing past behavior, we still allow
953 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
955 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
956 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
957 // and unable to even handle a ping answer. So we ignore those misses.
958 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
963 // Don't send pings until the network is initialized
965 // Mark as waiting for a reply
966 _pongReplyPending = true;
967 // Send default timestamp ping
968 userInputHandler()->handlePing(BufferInfo(), QString());
974 void CoreNetwork::enablePingTimeout(bool enable)
977 disablePingTimeout();
980 resetPongReplyPending();
981 if (networkConfig()->pingTimeoutEnabled())
987 void CoreNetwork::disablePingTimeout()
992 resetPongReplyPending();
996 void CoreNetwork::setPingInterval(int interval)
998 _pingTimer.setInterval(interval * 1000);
1002 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
1004 _pongTimestampValid = validTimestamp;
1008 /******** Custom Rate Limiting ********/
1010 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
1012 // Verify and apply custom rate limiting options, always resetting the delay and burst size
1013 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
1014 // this may be called while connected to a server.
1016 if (useCustomMessageRate() || forceUnlimited) {
1017 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
1019 _messageDelay = messageRateDelay();
1021 _burstSize = messageRateBurstSize();
1022 if (_burstSize < 1) {
1023 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
1025 // Can't go slower than one message at a time
1029 if (_tokenBucket > _burstSize) {
1030 // Don't let the token bucket exceed the maximum
1031 _tokenBucket = _burstSize;
1032 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1033 // changing the rate-limit settings while connected to a server will incorrectly reset
1034 // the token bucket.
1037 // Toggle the timer according to whether or not rate limiting is enabled
1038 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1039 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1040 // Override user preferences if called with force unlimited, only used during connect.
1041 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1042 if (_skipMessageRates) {
1043 // If the message queue already contains messages, they need sent before disabling the
1044 // timer. Set the timer to a rapid pace and let it disable itself.
1045 if (_msgQueue.size() > 0) {
1046 qDebug() << "Outgoing message queue contains messages while disabling rate "
1047 "limiting. Sending remaining queued messages...";
1048 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1049 // so nothing should cause this to block.. in theory. However, don't directly call
1050 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1052 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1053 // Hesitant to change it without a wide variety of situations to verify behavior.
1054 _tokenBucketTimer.start(100);
1056 // No rate limiting, disable the timer
1057 _tokenBucketTimer.stop();
1060 // Rate limiting enabled, enable the timer
1061 _tokenBucketTimer.start(_messageDelay);
1064 // Custom message rates disabled. Go for the default.
1066 _skipMessageRates = false; // Enable rate-limiting by default
1067 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1068 _burstSize = 5; // 5 messages at once
1069 if (_tokenBucket > _burstSize) {
1070 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1072 _tokenBucket = _burstSize;
1073 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1074 // changing the rate-limit settings while connected to a server will incorrectly reset
1075 // the token bucket.
1077 // Rate limiting enabled, enable the timer
1078 _tokenBucketTimer.start(_messageDelay);
1082 void CoreNetwork::resetTokenBucket()
1084 // Fill up the token bucket to the maximum
1085 _tokenBucket = _burstSize;
1089 /******** IRCv3 Capability Negotiation ********/
1091 void CoreNetwork::serverCapAdded(const QString &capability)
1093 // Check if it's a known capability; if so, add it to the list
1094 // Handle special cases first
1095 if (capability == IrcCap::SASL) {
1096 // Only request SASL if it's enabled
1097 if (networkInfo().useSasl)
1098 queueCap(capability);
1099 } else if (IrcCap::knownCaps.contains(capability)) {
1100 // Handling for general known capabilities
1101 queueCap(capability);
1105 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1107 // This may be called multiple times in certain situations.
1109 // Handle core-side configuration
1110 if (capability == IrcCap::AWAY_NOTIFY) {
1111 // away-notify enabled, stop the autoWho timers, handle manually
1112 setAutoWhoEnabled(false);
1115 // Handle capabilities that require further messages sent to the IRC server
1116 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1117 if (capability == IrcCap::SASL) {
1118 // If SASL mechanisms specified, limit to what's accepted for authentication
1119 // if the current identity has a cert set, use SASL EXTERNAL
1122 if (!identityPtr()->sslCert().isNull()) {
1123 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1124 // EXTERNAL authentication supported, send request
1125 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1127 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1128 tr("SASL EXTERNAL authentication not supported"));
1133 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1134 // PLAIN authentication supported, send request
1135 // Only working with PLAIN atm, blowfish later
1136 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1138 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1139 tr("SASL PLAIN authentication not supported"));
1148 void CoreNetwork::serverCapRemoved(const QString &capability)
1150 // This may be called multiple times in certain situations.
1152 // Handle special cases here
1153 if (capability == IrcCap::AWAY_NOTIFY) {
1154 // away-notify disabled, enable autoWho according to configuration
1155 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1159 void CoreNetwork::queueCap(const QString &capability)
1161 // IRCv3 specs all use lowercase capability names
1162 QString _capLowercase = capability.toLower();
1164 if(capsRequiringConfiguration.contains(_capLowercase)) {
1165 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1166 // so we should negotiate it separately from all other capabilities. Otherwise new
1167 // capabilities will be requested while still configuring the previous one.
1168 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1169 _capsQueuedIndividual.append(_capLowercase);
1172 // The capability doesn't need any special configuration, so it should be safe to try
1173 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1175 if (!_capsQueuedBundled.contains(_capLowercase)) {
1176 _capsQueuedBundled.append(_capLowercase);
1181 QString CoreNetwork::takeQueuedCaps()
1183 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1185 _capsQueuedLastBundle.clear();
1187 // First, negotiate all the standalone capabilities that require additional configuration.
1188 if (!_capsQueuedIndividual.empty()) {
1189 // We have an individual capability available. Take the first and pass it back.
1190 return _capsQueuedIndividual.takeFirst();
1191 } else if (!_capsQueuedBundled.empty()) {
1192 // We have capabilities available that can be grouped. Try to fit in as many as within the
1194 // See CoreNetwork::maxCapRequestLength
1196 // Response must have at least one capability regardless of max length for anything to
1198 QString capBundle = _capsQueuedBundled.takeFirst();
1199 QString nextCap("");
1200 while (!_capsQueuedBundled.empty()) {
1201 // As long as capabilities remain, get the next...
1202 nextCap = _capsQueuedBundled.first();
1203 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1204 // [capability + 1 for a space + this new capability] fit within length limits
1205 // Add it to formatted list
1206 capBundle.append(" " + nextCap);
1207 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1208 _capsQueuedLastBundle.append(nextCap);
1209 // Then remove it from the queue
1210 _capsQueuedBundled.removeFirst();
1212 // We've reached the length limit for a single capability request, stop adding more
1216 // Return this space-separated set of capabilities, removing any extra spaces
1217 return capBundle.trimmed();
1219 // No capabilities left to negotiate, return an empty string.
1224 void CoreNetwork::retryCapsIndividually()
1226 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1227 // denied, try each capability individually.
1228 if (_capsQueuedLastBundle.empty()) {
1229 // No most recently tried capability set, just return.
1231 // Note: there's little point in retrying individually requested caps during negotiation.
1232 // We know the individual capability was the one that failed, and it's not likely it'll
1233 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1234 // handling capability removal and addition.
1237 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1238 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1239 // keeping track of which halves of the group fail, dividing the set each time.
1241 // Add most recently tried capability set to individual list, re-requesting them one at a time
1242 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1243 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1244 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1245 tr("Could not negotiate some capabilities, retrying individually (%1)...")
1246 .arg(_capsQueuedLastBundle.join(", ")));
1247 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1248 // need to remove them here.
1249 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1251 _capsQueuedLastBundle.clear();
1254 void CoreNetwork::beginCapNegotiation()
1256 // Don't begin negotiation if no capabilities are queued to request
1257 if (!capNegotiationInProgress()) {
1258 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1259 // normal connection.
1260 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1261 endCapNegotiation();
1265 _capNegotiationActive = true;
1266 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1267 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1269 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1270 // comma separator between the two if needed (both individual and bundled caps exist).
1271 QString queuedCapsDisplay =
1272 _capsQueuedIndividual.join(", ")
1273 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1274 + _capsQueuedBundled.join(", ");
1275 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1276 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1281 void CoreNetwork::sendNextCap()
1283 if (capNegotiationInProgress()) {
1284 // Request the next set of capabilities and remove them from the list
1285 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1287 // No pending desired capabilities, capability negotiation finished
1288 // If SASL requested but not available, print a warning
1289 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1290 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1291 tr("SASL authentication currently not supported by server"));
1293 if (_capNegotiationActive) {
1294 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1295 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1296 _capNegotiationActive = false;
1299 endCapNegotiation();
1303 void CoreNetwork::endCapNegotiation()
1305 // If nick registration is already complete, CAP END is not required
1306 if (!_capInitialNegotiationEnded) {
1307 putRawLine(serverEncode(QString("CAP END")));
1308 _capInitialNegotiationEnded = true;
1312 /******** AutoWHO ********/
1314 void CoreNetwork::startAutoWhoCycle()
1316 if (!_autoWhoQueue.isEmpty()) {
1317 _autoWhoCycleTimer.stop();
1320 _autoWhoQueue = channels();
1323 void CoreNetwork::queueAutoWhoOneshot(const QString &name)
1325 // Prepend so these new channels/nicks are the first to be checked
1326 // Don't allow duplicates
1327 if (!_autoWhoQueue.contains(name.toLower())) {
1328 _autoWhoQueue.prepend(name.toLower());
1330 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1331 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1332 setAutoWhoEnabled(true);
1337 void CoreNetwork::setAutoWhoDelay(int delay)
1339 _autoWhoTimer.setInterval(delay * 1000);
1343 void CoreNetwork::setAutoWhoInterval(int interval)
1345 _autoWhoCycleTimer.setInterval(interval * 1000);
1349 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1351 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1352 _autoWhoTimer.start();
1353 else if (!enabled) {
1354 _autoWhoTimer.stop();
1355 _autoWhoCycleTimer.stop();
1360 void CoreNetwork::sendAutoWho()
1362 // Don't send autowho if there are still some pending
1363 if (_autoWhoPending.count())
1366 while (!_autoWhoQueue.isEmpty()) {
1367 QString chanOrNick = _autoWhoQueue.takeFirst();
1368 // Check if it's a known channel or nick
1369 IrcChannel *ircchan = ircChannel(chanOrNick);
1370 IrcUser *ircuser = ircUser(chanOrNick);
1372 // Apply channel limiting rules
1373 // If using away-notify, don't impose channel size limits in order to capture away
1374 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1375 if (networkConfig()->autoWhoNickLimit() > 0
1376 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1377 && !capEnabled(IrcCap::AWAY_NOTIFY))
1379 _autoWhoPending[chanOrNick.toLower()]++;
1380 } else if (ircuser) {
1381 // Checking a nick, add it to the pending list
1382 _autoWhoPending[ircuser->nick().toLower()]++;
1384 // Not a channel or a nick, skip it
1385 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1388 if (supports("WHOX")) {
1389 // Use WHO extended to poll away users and/or user accounts
1390 // Explicitly only match on nickname ("n"), don't rely on server defaults
1392 // WHO <nickname> n%chtsunfra,<unique_number>
1394 // See http://faerion.sourceforge.net/doc/irc/whox.var
1395 // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1396 // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1397 putRawLine(serverEncode(QString("WHO %1 n%chtsunfra,%2")
1398 .arg(serverEncode(chanOrNick),
1399 QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1401 // Fall back to normal WHO
1403 // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1404 // hostmask, etc. There's nothing we can do about that :(
1406 // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1407 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1412 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1413 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1414 // Timer was stopped, means a new cycle is due immediately
1415 // Don't run a new cycle if using away-notify; server will notify as appropriate
1416 _autoWhoCycleTimer.start();
1417 startAutoWhoCycle();
1418 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1419 // Don't run another who cycle if away-notify is enabled
1420 _autoWhoCycleTimer.stop();
1426 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1428 Server server = usedServer();
1429 if (server.sslVerify) {
1430 // Treat the SSL error as a hard error
1431 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1432 "since verification is required");
1433 if (!sslErrors.empty()) {
1434 // Add the error reason if known
1435 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1437 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1439 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1440 // validity, network trouble, etc.
1441 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1443 // Treat the SSL error as a warning, continue to connect anyways
1444 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1445 "since verification is not required");
1446 if (!sslErrors.empty()) {
1447 // Add the error reason if known
1448 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1450 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1452 // Proceed with the connection
1453 socket.ignoreSslErrors();
1460 void CoreNetwork::checkTokenBucket()
1462 if (_skipMessageRates) {
1463 if (_msgQueue.size() == 0) {
1464 // Message queue emptied; stop the timer and bail out
1465 _tokenBucketTimer.stop();
1468 // Otherwise, we're emptying the queue, continue on as normal
1471 // Process whatever messages are pending
1472 fillBucketAndProcessQueue();
1476 void CoreNetwork::fillBucketAndProcessQueue()
1478 // If there's less tokens than burst size, refill the token bucket by 1
1479 if (_tokenBucket < _burstSize) {
1483 // As long as there's tokens available and messages remaining, sending messages from the queue
1484 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1485 writeToSocket(_msgQueue.takeFirst());
1490 void CoreNetwork::writeToSocket(const QByteArray &data)
1492 // Log the message if enabled and network ID matches or allows all
1494 && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1495 // Include network ID
1496 qDebug() << "IRC net" << networkId() << ">>" << data;
1499 socket.write("\r\n");
1500 if (!_skipMessageRates) {
1501 // Only subtract from the token bucket if message rate limiting is enabled
1507 Network::Server CoreNetwork::usedServer() const
1509 if (_lastUsedServerIndex < serverList().count())
1510 return serverList()[_lastUsedServerIndex];
1512 if (!serverList().isEmpty())
1513 return serverList()[0];
1515 return Network::Server();
1519 void CoreNetwork::requestConnect() const
1521 if (_shuttingDown) {
1524 if (connectionState() != Disconnected) {
1525 qWarning() << "Requesting connect while already being connected!";
1528 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1532 void CoreNetwork::requestDisconnect() const
1534 if (_shuttingDown) {
1537 if (connectionState() == Disconnected) {
1538 qWarning() << "Requesting disconnect while not being connected!";
1541 userInputHandler()->handleQuit(BufferInfo(), QString());
1545 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1547 Network::Server currentServer = usedServer();
1548 setNetworkInfo(info);
1549 Core::updateNetwork(coreSession()->user(), info);
1551 // the order of the servers might have changed,
1552 // so we try to find the previously used server
1553 _lastUsedServerIndex = 0;
1554 for (int i = 0; i < serverList().count(); i++) {
1555 Network::Server server = serverList()[i];
1556 if (server.host == currentServer.host && server.port == currentServer.port) {
1557 _lastUsedServerIndex = i;
1564 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1566 QString wrkMsg(message);
1567 QList<QList<QByteArray>> msgsToSend;
1569 // do while (wrkMsg.size() > 0)
1571 // First, check to see if the whole message can be sent at once. The
1572 // cmdGenerator function is passed in by the caller and is used to encode
1573 // and encrypt (if applicable) the message, since different callers might
1574 // want to use different encoding or encode different values.
1575 int splitPos = wrkMsg.size();
1576 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1577 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1579 if (initialOverrun) {
1580 // If the message was too long to be sent, first try splitting it along
1581 // word boundaries with QTextBoundaryFinder.
1582 QString splitMsg(wrkMsg);
1583 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1584 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1585 QList<QByteArray> splitMsgEnc;
1586 int overrun = initialOverrun;
1589 splitPos = qtbf.toPreviousBoundary();
1591 // splitPos==-1 means the QTBF couldn't find a split point at all and
1592 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1593 // the string. Neither one of these works for us.
1595 // If a split point could be found, split the message there, calculate the
1596 // overrun, and continue with the loop.
1597 splitMsg = splitMsg.left(splitPos);
1598 splitMsgEnc = cmdGenerator(splitMsg);
1599 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1602 // If a split point could not be found (the beginning of the message
1603 // is reached without finding a split point short enough to send) and we
1604 // are still in Word mode, switch to Grapheme mode. We also need to restore
1605 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1606 // the previous attempt to find a split point.
1607 if (qtbf.type() == QTextBoundaryFinder::Word) {
1609 splitPos = splitMsg.size();
1610 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1611 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1612 qtbf = graphemeQtbf;
1615 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1616 // This should never happen, but it should be handled anyway.
1617 qWarning() << "Unexpected failure to split message!";
1623 // Once a message of sendable length has been found, remove it from the wrkMsg and
1624 // add it to the list of messages to be sent.
1625 wrkMsg.remove(0, splitPos);
1626 msgsToSend.append(splitMsgEnc);
1629 // If the entire remaining message is short enough to be sent all at once, remove
1630 // it from the wrkMsg and add it to the list of messages to be sent.
1631 wrkMsg.remove(0, splitPos);
1632 msgsToSend.append(initialSplitMsgEnc);
1634 } while (wrkMsg.size() > 0);