1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include "corenetwork.h"
27 #include "coreidentity.h"
28 #include "corenetworkconfig.h"
29 #include "coresession.h"
30 #include "coreuserinputhandler.h"
31 #include "networkevent.h"
36 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
37 : Network(networkid, session),
38 _coreSession(session),
39 _userInputHandler(new CoreUserInputHandler(this)),
40 _autoReconnectCount(0),
41 _quitRequested(false),
42 _disconnectExpected(false),
44 _previousConnectionAttemptFailed(false),
45 _lastUsedServerIndex(0),
47 _requestedUserModes('-')
49 // Check if raw IRC logging is enabled
50 _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
51 _debugLogRawNetId = Quassel::optionValue("debug-irc-id").toInt();
53 _autoReconnectTimer.setSingleShot(true);
54 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
56 setPingInterval(networkConfig()->pingInterval());
57 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
59 setAutoWhoDelay(networkConfig()->autoWhoDelay());
60 setAutoWhoInterval(networkConfig()->autoWhoInterval());
62 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
63 foreach(QString chan, channels.keys()) {
64 _channelKeys[chan.toLower()] = channels[chan];
67 QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
68 foreach(QString buffer, bufferCiphers.keys()) {
69 storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
72 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
73 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
74 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
75 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
76 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
78 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
79 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
80 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
81 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(checkTokenBucket()));
83 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
84 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
85 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
86 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
88 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
89 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
91 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
93 // Custom rate limiting
94 // These react to the user changing settings in the client
95 connect(this, SIGNAL(useCustomMessageRateSet(bool)), SLOT(updateRateLimiting()));
96 connect(this, SIGNAL(messageRateBurstSizeSet(quint32)), SLOT(updateRateLimiting()));
97 connect(this, SIGNAL(messageRateDelaySet(quint32)), SLOT(updateRateLimiting()));
98 connect(this, SIGNAL(unlimitedMessageRateSet(bool)), SLOT(updateRateLimiting()));
100 // IRCv3 capability handling
101 // These react to CAP messages from the server
102 connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
103 connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
104 connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
106 if (Quassel::isOptionSet("oidentd")) {
107 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
108 Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Qt::BlockingQueuedConnection);
109 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
110 Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)));
113 if (Quassel::isOptionSet("ident-daemon")) {
114 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
115 Core::instance()->identServer(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Qt::BlockingQueuedConnection);
116 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
117 Core::instance()->identServer(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)));
122 CoreNetwork::~CoreNetwork()
124 // Ensure we don't get any more signals from the socket while shutting down
125 disconnect(&socket, nullptr, this, nullptr);
126 if (!forceDisconnect()) {
127 qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
128 .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
133 bool CoreNetwork::forceDisconnect(int msecs)
135 if (socket.state() == QAbstractSocket::UnconnectedState) {
136 // Socket already disconnected.
139 // Request a socket-level disconnect if not already happened
140 socket.disconnectFromHost();
141 if (socket.state() != QAbstractSocket::UnconnectedState) {
142 return socket.waitForDisconnected(msecs);
148 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
150 if (!bufferName.isEmpty()) {
151 IrcChannel *channel = ircChannel(bufferName);
153 return channel->decodeString(string);
155 return decodeString(string);
159 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
161 IrcUser *user = ircUser(userNick);
163 return user->decodeString(string);
164 return decodeString(string);
168 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
170 if (!bufferName.isEmpty()) {
171 IrcChannel *channel = ircChannel(bufferName);
173 return channel->encodeString(string);
175 return encodeString(string);
179 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
181 IrcUser *user = ircUser(userNick);
183 return user->encodeString(string);
184 return encodeString(string);
188 void CoreNetwork::connectToIrc(bool reconnecting)
194 if (Core::instance()->identServer()) {
195 _socketId = Core::instance()->identServer()->addWaitingSocket();
198 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
199 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
200 if (unlimitedReconnectRetries())
201 _autoReconnectCount = -1;
203 _autoReconnectCount = autoReconnectRetries();
205 if (serverList().isEmpty()) {
206 qWarning() << "Server list empty, ignoring connect request!";
209 CoreIdentity *identity = identityPtr();
211 qWarning() << "Invalid identity configures, ignoring connect request!";
215 // cleaning up old quit reason
218 // Reset capability negotiation tracking, also handling server changes during reconnect
219 _capsQueuedIndividual.clear();
220 _capsQueuedBundled.clear();
222 _capNegotiationActive = false;
223 _capInitialNegotiationEnded = false;
225 // use a random server?
226 if (useRandomServer()) {
227 _lastUsedServerIndex = qrand() % serverList().size();
229 else if (_previousConnectionAttemptFailed) {
230 // cycle to next server if previous connection attempt failed
231 _previousConnectionAttemptFailed = false;
232 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
233 if (++_lastUsedServerIndex >= serverList().size()) {
234 _lastUsedServerIndex = 0;
238 // Start out with the top server in the list
239 _lastUsedServerIndex = 0;
242 Server server = usedServer();
243 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
244 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
246 if (server.useProxy) {
247 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
248 socket.setProxy(proxy);
251 socket.setProxy(QNetworkProxy::NoProxy);
256 // Reset tracking for valid timestamps in PONG replies
257 setPongTimestampValid(false);
259 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
260 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
261 if (! server.useProxy) {
262 //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
263 //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
264 QHostInfo::fromName(server.host);
268 CoreIdentity *identity = identityPtr();
270 socket.setLocalCertificate(identity->sslCert());
271 socket.setPrivateKey(identity->sslKey());
273 socket.connectToHostEncrypted(server.host, server.port);
276 socket.connectToHost(server.host, server.port);
279 socket.connectToHost(server.host, server.port);
284 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
286 // Disconnecting from the network, should expect a socket close or error
287 _disconnectExpected = true;
288 _quitRequested = requested; // see socketDisconnected();
289 if (!withReconnect) {
290 _autoReconnectTimer.stop();
291 _autoReconnectCount = 0; // prohibiting auto reconnect
293 disablePingTimeout();
300 awayMsg = me_->awayMessage();
301 Core::setAwayMessage(userId(), networkId(), awayMsg);
304 if (reason.isEmpty() && identityPtr())
305 _quitReason = identityPtr()->quitReason();
307 _quitReason = reason;
309 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
310 if (socket.state() == QAbstractSocket::UnconnectedState) {
311 socketDisconnected();
314 if (socket.state() == QAbstractSocket::ConnectedState) {
315 // If shutting down, prioritize the QUIT command
316 userInputHandler()->issueQuit(_quitReason, _shuttingDown);
321 if (socket.state() != QAbstractSocket::UnconnectedState) {
322 // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
323 _socketCloseTimer.start(10000);
329 void CoreNetwork::socketCloseTimeout()
331 qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
332 .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
337 void CoreNetwork::shutdown()
339 _shuttingDown = true;
340 disconnectFromIrc(false, {}, false);
344 void CoreNetwork::userInput(BufferInfo buf, QString msg)
346 userInputHandler()->handleUserInput(buf, msg);
350 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
352 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.size() == 0)) {
353 // If there's tokens remaining, ...
354 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
355 // Send the message now.
358 // Otherwise, queue the message for later
360 // Jump to the start, skipping other messages
361 _msgQueue.prepend(s);
363 // Add to back, waiting in order
370 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
374 if (!prefix.isEmpty())
375 msg += ":" + prefix + " ";
376 msg += cmd.toUpper().toLatin1();
378 for (int i = 0; i < params.size(); i++) {
381 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
387 putRawLine(msg, prepend);
391 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
393 QListIterator<QList<QByteArray>> i(params);
394 while (i.hasNext()) {
395 QList<QByteArray> msg = i.next();
396 putCmd(cmd, msg, prefix, prependAll);
401 void CoreNetwork::setChannelJoined(const QString &channel)
403 queueAutoWhoOneshot(channel); // check this new channel first
405 Core::setChannelPersistent(userId(), networkId(), channel, true);
406 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
410 void CoreNetwork::setChannelParted(const QString &channel)
412 removeChannelKey(channel);
413 _autoWhoQueue.removeAll(channel.toLower());
414 _autoWhoPending.remove(channel.toLower());
416 Core::setChannelPersistent(userId(), networkId(), channel, false);
420 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
423 removeChannelKey(channel);
426 _channelKeys[channel.toLower()] = key;
431 void CoreNetwork::removeChannelKey(const QString &channel)
433 _channelKeys.remove(channel.toLower());
438 Cipher *CoreNetwork::cipher(const QString &target)
440 if (target.isEmpty())
443 if (!Cipher::neededFeaturesAvailable())
446 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
448 return channel->cipher();
450 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
452 return user->cipher();
453 } else if (!isChannelName(target)) {
454 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
460 QByteArray CoreNetwork::cipherKey(const QString &target) const
462 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
464 return c->cipher()->key();
466 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
468 return u->cipher()->key();
474 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
476 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
478 c->setEncrypted(c->cipher()->setKey(key));
479 coreSession()->setBufferCipher(networkId(), target, key);
483 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
484 if (!u && !isChannelName(target))
485 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
488 u->setEncrypted(u->cipher()->setKey(key));
489 coreSession()->setBufferCipher(networkId(), target, key);
495 bool CoreNetwork::cipherUsesCBC(const QString &target)
497 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
499 return c->cipher()->usesCBC();
500 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
502 return u->cipher()->usesCBC();
506 #endif /* HAVE_QCA2 */
508 bool CoreNetwork::setAutoWhoDone(const QString &name)
510 QString chanOrNick = name.toLower();
511 if (_autoWhoPending.value(chanOrNick, 0) <= 0)
513 if (--_autoWhoPending[chanOrNick] <= 0)
514 _autoWhoPending.remove(chanOrNick);
519 void CoreNetwork::setMyNick(const QString &mynick)
521 Network::setMyNick(mynick);
522 if (connectionState() == Network::Initializing)
523 networkInitialized();
527 void CoreNetwork::socketHasData()
529 while (socket.canReadLine()) {
530 QByteArray s = socket.readLine();
531 if (s.endsWith("\r\n"))
533 else if (s.endsWith("\n"))
535 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
536 event->setTimestamp(QDateTime::currentDateTimeUtc());
537 emit newEvent(event);
542 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
544 // Ignore socket closed errors if expected
545 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
549 _previousConnectionAttemptFailed = true;
550 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
551 emit connectionError(socket.errorString());
552 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
553 emitConnectionError(socket.errorString());
554 if (socket.state() < QAbstractSocket::ConnectedState) {
555 socketDisconnected();
560 void CoreNetwork::socketInitialized()
562 CoreIdentity *identity = identityPtr();
564 qCritical() << "Identity invalid!";
569 Server server = usedServer();
572 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
573 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
574 if (!server.useSsl || !socket.isEncrypted()) {
575 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
578 if (server.useSsl && !socket.isEncrypted()) {
579 // We'll finish setup once we're encrypted, and called again
583 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
586 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
588 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
589 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
590 // force flag to apply user preferences. When making changes, ensure that this still happens!
591 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
592 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
594 updateRateLimiting(true);
595 // Fill up the token bucket as we're connecting from scratch
598 // Request capabilities as per IRCv3.2 specifications
599 // Older servers should ignore this; newer servers won't downgrade to RFC1459
600 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
601 putRawLine(serverEncode(QString("CAP LS 302")));
603 if (!server.password.isEmpty()) {
604 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
607 if (identity->nicks().isEmpty()) {
609 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
612 nick = identity->nicks()[0];
614 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
615 // Only allow strict-compliant idents when strict mode is enabled
616 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(
617 coreSession()->strictCompliantIdent(identity),
618 identity->realName())));
622 void CoreNetwork::socketDisconnected()
624 disablePingTimeout();
627 _autoWhoCycleTimer.stop();
628 _autoWhoTimer.stop();
629 _autoWhoQueue.clear();
630 _autoWhoPending.clear();
632 _socketCloseTimer.stop();
634 _tokenBucketTimer.stop();
638 foreach(QString channel, me_->channels())
639 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
643 emit disconnected(networkId());
644 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
645 // Reset disconnect expectations
646 _disconnectExpected = false;
647 if (_quitRequested) {
648 _quitRequested = false;
649 setConnectionState(Network::Disconnected);
650 Core::setNetworkConnected(userId(), networkId(), false);
652 else if (_autoReconnectCount != 0) {
653 setConnectionState(Network::Reconnecting);
654 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
655 doAutoReconnect(); // first try is immediate
657 _autoReconnectTimer.start();
662 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
664 Network::ConnectionState state;
665 switch (socketState) {
666 case QAbstractSocket::UnconnectedState:
667 state = Network::Disconnected;
668 socketDisconnected();
670 case QAbstractSocket::HostLookupState:
671 case QAbstractSocket::ConnectingState:
672 state = Network::Connecting;
674 case QAbstractSocket::ConnectedState:
675 state = Network::Initializing;
677 case QAbstractSocket::ClosingState:
678 state = Network::Disconnecting;
681 state = Network::Disconnected;
683 setConnectionState(state);
687 void CoreNetwork::networkInitialized()
689 setConnectionState(Network::Initialized);
691 _disconnectExpected = false;
692 _quitRequested = false;
694 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
695 // flag used for initial registration and capability negotiation.
696 updateRateLimiting();
698 if (useAutoReconnect()) {
700 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
703 // restore away state
704 QString awayMsg = Core::awayMessage(userId(), networkId());
705 if (!awayMsg.isEmpty()) {
706 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
707 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
708 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
715 if (networkConfig()->autoWhoEnabled()) {
716 _autoWhoCycleTimer.start();
717 _autoWhoTimer.start();
718 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
721 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
722 Core::setNetworkConnected(userId(), networkId(), true);
726 void CoreNetwork::sendPerform()
728 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
731 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
732 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
735 // restore old user modes if server default mode is set.
738 if (!me_->userModes().isEmpty()) {
742 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
743 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
748 foreach(QString line, perform()) {
749 if (!line.isEmpty()) userInput(statusBuf, line);
752 // rejoin channels we've been in
753 if (rejoinChannels()) {
754 QStringList channels, keys;
755 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
756 QString key = channelKey(chan);
757 if (!key.isEmpty()) {
758 channels.prepend(chan);
762 channels.append(chan);
765 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
766 if (!joinString.isEmpty())
767 userInputHandler()->handleJoin(statusBuf, joinString);
772 void CoreNetwork::restoreUserModes()
777 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
778 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
780 QString modesDelta = Core::userModes(userId(), networkId());
781 QString currentModes = me_->userModes();
783 QString addModes, removeModes;
784 if (modesDelta.contains('-')) {
785 addModes = modesDelta.section('-', 0, 0);
786 removeModes = modesDelta.section('-', 1);
789 addModes = modesDelta;
792 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
793 if (currentModes.isEmpty())
794 removeModes = QString();
796 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
798 if (addModes.isEmpty() && removeModes.isEmpty())
801 if (!addModes.isEmpty())
802 addModes = '+' + addModes;
803 if (!removeModes.isEmpty())
804 removeModes = '-' + removeModes;
806 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
807 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
811 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
817 for (int i = 0; i < requestedModes.length(); i++) {
818 if (requestedModes[i] == '+') {
822 if (requestedModes[i] == '-') {
827 addModes += requestedModes[i];
830 removeModes += requestedModes[i];
834 QString addModesOld = _requestedUserModes.section('-', 0, 0);
835 QString removeModesOld = _requestedUserModes.section('-', 1);
837 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
838 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
839 addModes += addModesOld;
841 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
842 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
843 removeModes += removeModesOld;
845 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
849 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
851 QString persistentUserModes = Core::userModes(userId(), networkId());
853 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
854 QString requestedRemove = _requestedUserModes.section('-', 1);
856 QString persistentAdd, persistentRemove;
857 if (persistentUserModes.contains('-')) {
858 persistentAdd = persistentUserModes.section('-', 0, 0);
859 persistentRemove = persistentUserModes.section('-', 1);
862 persistentAdd = persistentUserModes;
865 // remove modes we didn't issue
866 if (requestedAdd.isEmpty())
867 addModes = QString();
869 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
871 if (requestedRemove.isEmpty())
872 removeModes = QString();
874 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
877 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
878 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
881 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
882 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
884 // update issued mode list
885 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
886 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
887 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
889 persistentAdd += addModes;
890 persistentRemove += removeModes;
891 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
895 void CoreNetwork::resetPersistentModes()
897 _requestedUserModes = QString('-');
898 Core::setUserModes(userId(), networkId(), QString());
902 void CoreNetwork::setUseAutoReconnect(bool use)
904 Network::setUseAutoReconnect(use);
906 _autoReconnectTimer.stop();
910 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
912 Network::setAutoReconnectInterval(interval);
913 _autoReconnectTimer.setInterval(interval * 1000);
917 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
919 Network::setAutoReconnectRetries(retries);
920 if (_autoReconnectCount != 0) {
921 if (unlimitedReconnectRetries())
922 _autoReconnectCount = -1;
924 _autoReconnectCount = autoReconnectRetries();
929 void CoreNetwork::doAutoReconnect()
931 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
932 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
935 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
936 _autoReconnectCount--; // -2 means we delay the next reconnect
941 void CoreNetwork::sendPing()
943 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
944 if (_pingCount != 0) {
945 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
946 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
948 if ((int)_pingCount >= networkConfig()->maxPingCount()
949 && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
950 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
951 // However, to reduce the risk of breaking things by changing past behavior, we still allow
952 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
954 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
955 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
956 // and unable to even handle a ping answer. So we ignore those misses.
957 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
962 // Don't send pings until the network is initialized
964 // Mark as waiting for a reply
965 _pongReplyPending = true;
966 // Send default timestamp ping
967 userInputHandler()->handlePing(BufferInfo(), QString());
973 void CoreNetwork::enablePingTimeout(bool enable)
976 disablePingTimeout();
979 resetPongReplyPending();
980 if (networkConfig()->pingTimeoutEnabled())
986 void CoreNetwork::disablePingTimeout()
991 resetPongReplyPending();
995 void CoreNetwork::setPingInterval(int interval)
997 _pingTimer.setInterval(interval * 1000);
1001 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
1003 _pongTimestampValid = validTimestamp;
1007 /******** Custom Rate Limiting ********/
1009 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
1011 // Verify and apply custom rate limiting options, always resetting the delay and burst size
1012 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
1013 // this may be called while connected to a server.
1015 if (useCustomMessageRate() || forceUnlimited) {
1016 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
1018 _messageDelay = messageRateDelay();
1020 _burstSize = messageRateBurstSize();
1021 if (_burstSize < 1) {
1022 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
1024 // Can't go slower than one message at a time
1028 if (_tokenBucket > _burstSize) {
1029 // Don't let the token bucket exceed the maximum
1030 _tokenBucket = _burstSize;
1031 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1032 // changing the rate-limit settings while connected to a server will incorrectly reset
1033 // the token bucket.
1036 // Toggle the timer according to whether or not rate limiting is enabled
1037 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1038 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1039 // Override user preferences if called with force unlimited, only used during connect.
1040 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1041 if (_skipMessageRates) {
1042 // If the message queue already contains messages, they need sent before disabling the
1043 // timer. Set the timer to a rapid pace and let it disable itself.
1044 if (_msgQueue.size() > 0) {
1045 qDebug() << "Outgoing message queue contains messages while disabling rate "
1046 "limiting. Sending remaining queued messages...";
1047 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1048 // so nothing should cause this to block.. in theory. However, don't directly call
1049 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1051 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1052 // Hesitant to change it without a wide variety of situations to verify behavior.
1053 _tokenBucketTimer.start(100);
1055 // No rate limiting, disable the timer
1056 _tokenBucketTimer.stop();
1059 // Rate limiting enabled, enable the timer
1060 _tokenBucketTimer.start(_messageDelay);
1063 // Custom message rates disabled. Go for the default.
1065 _skipMessageRates = false; // Enable rate-limiting by default
1066 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1067 _burstSize = 5; // 5 messages at once
1068 if (_tokenBucket > _burstSize) {
1069 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1071 _tokenBucket = _burstSize;
1072 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1073 // changing the rate-limit settings while connected to a server will incorrectly reset
1074 // the token bucket.
1076 // Rate limiting enabled, enable the timer
1077 _tokenBucketTimer.start(_messageDelay);
1081 void CoreNetwork::resetTokenBucket()
1083 // Fill up the token bucket to the maximum
1084 _tokenBucket = _burstSize;
1088 /******** IRCv3 Capability Negotiation ********/
1090 void CoreNetwork::serverCapAdded(const QString &capability)
1092 // Check if it's a known capability; if so, add it to the list
1093 // Handle special cases first
1094 if (capability == IrcCap::SASL) {
1095 // Only request SASL if it's enabled
1096 if (networkInfo().useSasl)
1097 queueCap(capability);
1098 } else if (IrcCap::knownCaps.contains(capability)) {
1099 // Handling for general known capabilities
1100 queueCap(capability);
1104 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1106 // This may be called multiple times in certain situations.
1108 // Handle core-side configuration
1109 if (capability == IrcCap::AWAY_NOTIFY) {
1110 // away-notify enabled, stop the autoWho timers, handle manually
1111 setAutoWhoEnabled(false);
1114 // Handle capabilities that require further messages sent to the IRC server
1115 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1116 if (capability == IrcCap::SASL) {
1117 // If SASL mechanisms specified, limit to what's accepted for authentication
1118 // if the current identity has a cert set, use SASL EXTERNAL
1121 if (!identityPtr()->sslCert().isNull()) {
1122 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1123 // EXTERNAL authentication supported, send request
1124 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1126 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1127 tr("SASL EXTERNAL authentication not supported"));
1132 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1133 // PLAIN authentication supported, send request
1134 // Only working with PLAIN atm, blowfish later
1135 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1137 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1138 tr("SASL PLAIN authentication not supported"));
1147 void CoreNetwork::serverCapRemoved(const QString &capability)
1149 // This may be called multiple times in certain situations.
1151 // Handle special cases here
1152 if (capability == IrcCap::AWAY_NOTIFY) {
1153 // away-notify disabled, enable autoWho according to configuration
1154 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1158 void CoreNetwork::queueCap(const QString &capability)
1160 // IRCv3 specs all use lowercase capability names
1161 QString _capLowercase = capability.toLower();
1163 if(capsRequiringConfiguration.contains(_capLowercase)) {
1164 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1165 // so we should negotiate it separately from all other capabilities. Otherwise new
1166 // capabilities will be requested while still configuring the previous one.
1167 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1168 _capsQueuedIndividual.append(_capLowercase);
1171 // The capability doesn't need any special configuration, so it should be safe to try
1172 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1174 if (!_capsQueuedBundled.contains(_capLowercase)) {
1175 _capsQueuedBundled.append(_capLowercase);
1180 QString CoreNetwork::takeQueuedCaps()
1182 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1184 _capsQueuedLastBundle.clear();
1186 // First, negotiate all the standalone capabilities that require additional configuration.
1187 if (!_capsQueuedIndividual.empty()) {
1188 // We have an individual capability available. Take the first and pass it back.
1189 return _capsQueuedIndividual.takeFirst();
1190 } else if (!_capsQueuedBundled.empty()) {
1191 // We have capabilities available that can be grouped. Try to fit in as many as within the
1193 // See CoreNetwork::maxCapRequestLength
1195 // Response must have at least one capability regardless of max length for anything to
1197 QString capBundle = _capsQueuedBundled.takeFirst();
1198 QString nextCap("");
1199 while (!_capsQueuedBundled.empty()) {
1200 // As long as capabilities remain, get the next...
1201 nextCap = _capsQueuedBundled.first();
1202 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1203 // [capability + 1 for a space + this new capability] fit within length limits
1204 // Add it to formatted list
1205 capBundle.append(" " + nextCap);
1206 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1207 _capsQueuedLastBundle.append(nextCap);
1208 // Then remove it from the queue
1209 _capsQueuedBundled.removeFirst();
1211 // We've reached the length limit for a single capability request, stop adding more
1215 // Return this space-separated set of capabilities, removing any extra spaces
1216 return capBundle.trimmed();
1218 // No capabilities left to negotiate, return an empty string.
1223 void CoreNetwork::retryCapsIndividually()
1225 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1226 // denied, try each capability individually.
1227 if (_capsQueuedLastBundle.empty()) {
1228 // No most recently tried capability set, just return.
1230 // Note: there's little point in retrying individually requested caps during negotiation.
1231 // We know the individual capability was the one that failed, and it's not likely it'll
1232 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1233 // handling capability removal and addition.
1236 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1237 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1238 // keeping track of which halves of the group fail, dividing the set each time.
1240 // Add most recently tried capability set to individual list, re-requesting them one at a time
1241 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1242 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1243 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1244 tr("Could not negotiate some capabilities, retrying individually (%1)...")
1245 .arg(_capsQueuedLastBundle.join(", ")));
1246 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1247 // need to remove them here.
1248 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1250 _capsQueuedLastBundle.clear();
1253 void CoreNetwork::beginCapNegotiation()
1255 // Don't begin negotiation if no capabilities are queued to request
1256 if (!capNegotiationInProgress()) {
1257 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1258 // normal connection.
1259 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1260 endCapNegotiation();
1264 _capNegotiationActive = true;
1265 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1266 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1268 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1269 // comma separator between the two if needed (both individual and bundled caps exist).
1270 QString queuedCapsDisplay =
1271 _capsQueuedIndividual.join(", ")
1272 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1273 + _capsQueuedBundled.join(", ");
1274 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1275 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1280 void CoreNetwork::sendNextCap()
1282 if (capNegotiationInProgress()) {
1283 // Request the next set of capabilities and remove them from the list
1284 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1286 // No pending desired capabilities, capability negotiation finished
1287 // If SASL requested but not available, print a warning
1288 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1289 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1290 tr("SASL authentication currently not supported by server"));
1292 if (_capNegotiationActive) {
1293 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1294 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1295 _capNegotiationActive = false;
1298 endCapNegotiation();
1302 void CoreNetwork::endCapNegotiation()
1304 // If nick registration is already complete, CAP END is not required
1305 if (!_capInitialNegotiationEnded) {
1306 putRawLine(serverEncode(QString("CAP END")));
1307 _capInitialNegotiationEnded = true;
1311 /******** AutoWHO ********/
1313 void CoreNetwork::startAutoWhoCycle()
1315 if (!_autoWhoQueue.isEmpty()) {
1316 _autoWhoCycleTimer.stop();
1319 _autoWhoQueue = channels();
1322 void CoreNetwork::queueAutoWhoOneshot(const QString &name)
1324 // Prepend so these new channels/nicks are the first to be checked
1325 // Don't allow duplicates
1326 if (!_autoWhoQueue.contains(name.toLower())) {
1327 _autoWhoQueue.prepend(name.toLower());
1329 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1330 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1331 setAutoWhoEnabled(true);
1336 void CoreNetwork::setAutoWhoDelay(int delay)
1338 _autoWhoTimer.setInterval(delay * 1000);
1342 void CoreNetwork::setAutoWhoInterval(int interval)
1344 _autoWhoCycleTimer.setInterval(interval * 1000);
1348 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1350 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1351 _autoWhoTimer.start();
1352 else if (!enabled) {
1353 _autoWhoTimer.stop();
1354 _autoWhoCycleTimer.stop();
1359 void CoreNetwork::sendAutoWho()
1361 // Don't send autowho if there are still some pending
1362 if (_autoWhoPending.count())
1365 while (!_autoWhoQueue.isEmpty()) {
1366 QString chanOrNick = _autoWhoQueue.takeFirst();
1367 // Check if it's a known channel or nick
1368 IrcChannel *ircchan = ircChannel(chanOrNick);
1369 IrcUser *ircuser = ircUser(chanOrNick);
1371 // Apply channel limiting rules
1372 // If using away-notify, don't impose channel size limits in order to capture away
1373 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1374 if (networkConfig()->autoWhoNickLimit() > 0
1375 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1376 && !capEnabled(IrcCap::AWAY_NOTIFY))
1378 _autoWhoPending[chanOrNick.toLower()]++;
1379 } else if (ircuser) {
1380 // Checking a nick, add it to the pending list
1381 _autoWhoPending[ircuser->nick().toLower()]++;
1383 // Not a channel or a nick, skip it
1384 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1387 if (supports("WHOX")) {
1388 // Use WHO extended to poll away users and/or user accounts
1389 // Explicitly only match on nickname ("n"), don't rely on server defaults
1391 // WHO <nickname> n%chtsunfra,<unique_number>
1393 // See http://faerion.sourceforge.net/doc/irc/whox.var
1394 // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1395 // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1396 putRawLine(serverEncode(QString("WHO %1 n%chtsunfra,%2")
1397 .arg(serverEncode(chanOrNick),
1398 QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1400 // Fall back to normal WHO
1402 // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1403 // hostmask, etc. There's nothing we can do about that :(
1405 // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1406 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1411 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1412 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1413 // Timer was stopped, means a new cycle is due immediately
1414 // Don't run a new cycle if using away-notify; server will notify as appropriate
1415 _autoWhoCycleTimer.start();
1416 startAutoWhoCycle();
1417 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1418 // Don't run another who cycle if away-notify is enabled
1419 _autoWhoCycleTimer.stop();
1425 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1427 Server server = usedServer();
1428 if (server.sslVerify) {
1429 // Treat the SSL error as a hard error
1430 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1431 "since verification is required");
1432 if (!sslErrors.empty()) {
1433 // Add the error reason if known
1434 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1436 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1438 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1439 // validity, network trouble, etc.
1440 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1442 // Treat the SSL error as a warning, continue to connect anyways
1443 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1444 "since verification is not required");
1445 if (!sslErrors.empty()) {
1446 // Add the error reason if known
1447 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1449 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1451 // Proceed with the connection
1452 socket.ignoreSslErrors();
1459 void CoreNetwork::checkTokenBucket()
1461 if (_skipMessageRates) {
1462 if (_msgQueue.size() == 0) {
1463 // Message queue emptied; stop the timer and bail out
1464 _tokenBucketTimer.stop();
1467 // Otherwise, we're emptying the queue, continue on as normal
1470 // Process whatever messages are pending
1471 fillBucketAndProcessQueue();
1475 void CoreNetwork::fillBucketAndProcessQueue()
1477 // If there's less tokens than burst size, refill the token bucket by 1
1478 if (_tokenBucket < _burstSize) {
1482 // As long as there's tokens available and messages remaining, sending messages from the queue
1483 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1484 writeToSocket(_msgQueue.takeFirst());
1489 void CoreNetwork::writeToSocket(const QByteArray &data)
1491 // Log the message if enabled and network ID matches or allows all
1493 && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1494 // Include network ID
1495 qDebug() << "IRC net" << networkId() << ">>" << data;
1498 socket.write("\r\n");
1499 if (!_skipMessageRates) {
1500 // Only subtract from the token bucket if message rate limiting is enabled
1506 Network::Server CoreNetwork::usedServer() const
1508 if (_lastUsedServerIndex < serverList().count())
1509 return serverList()[_lastUsedServerIndex];
1511 if (!serverList().isEmpty())
1512 return serverList()[0];
1514 return Network::Server();
1518 void CoreNetwork::requestConnect() const
1520 if (_shuttingDown) {
1523 if (connectionState() != Disconnected) {
1524 qWarning() << "Requesting connect while already being connected!";
1527 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1531 void CoreNetwork::requestDisconnect() const
1533 if (_shuttingDown) {
1536 if (connectionState() == Disconnected) {
1537 qWarning() << "Requesting disconnect while not being connected!";
1540 userInputHandler()->handleQuit(BufferInfo(), QString());
1544 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1546 Network::Server currentServer = usedServer();
1547 setNetworkInfo(info);
1548 Core::updateNetwork(coreSession()->user(), info);
1550 // the order of the servers might have changed,
1551 // so we try to find the previously used server
1552 _lastUsedServerIndex = 0;
1553 for (int i = 0; i < serverList().count(); i++) {
1554 Network::Server server = serverList()[i];
1555 if (server.host == currentServer.host && server.port == currentServer.port) {
1556 _lastUsedServerIndex = i;
1563 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1565 QString wrkMsg(message);
1566 QList<QList<QByteArray>> msgsToSend;
1568 // do while (wrkMsg.size() > 0)
1570 // First, check to see if the whole message can be sent at once. The
1571 // cmdGenerator function is passed in by the caller and is used to encode
1572 // and encrypt (if applicable) the message, since different callers might
1573 // want to use different encoding or encode different values.
1574 int splitPos = wrkMsg.size();
1575 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1576 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1578 if (initialOverrun) {
1579 // If the message was too long to be sent, first try splitting it along
1580 // word boundaries with QTextBoundaryFinder.
1581 QString splitMsg(wrkMsg);
1582 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1583 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1584 QList<QByteArray> splitMsgEnc;
1585 int overrun = initialOverrun;
1588 splitPos = qtbf.toPreviousBoundary();
1590 // splitPos==-1 means the QTBF couldn't find a split point at all and
1591 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1592 // the string. Neither one of these works for us.
1594 // If a split point could be found, split the message there, calculate the
1595 // overrun, and continue with the loop.
1596 splitMsg = splitMsg.left(splitPos);
1597 splitMsgEnc = cmdGenerator(splitMsg);
1598 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1601 // If a split point could not be found (the beginning of the message
1602 // is reached without finding a split point short enough to send) and we
1603 // are still in Word mode, switch to Grapheme mode. We also need to restore
1604 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1605 // the previous attempt to find a split point.
1606 if (qtbf.type() == QTextBoundaryFinder::Word) {
1608 splitPos = splitMsg.size();
1609 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1610 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1611 qtbf = graphemeQtbf;
1614 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1615 // This should never happen, but it should be handled anyway.
1616 qWarning() << "Unexpected failure to split message!";
1622 // Once a message of sendable length has been found, remove it from the wrkMsg and
1623 // add it to the list of messages to be sent.
1624 wrkMsg.remove(0, splitPos);
1625 msgsToSend.append(splitMsgEnc);
1628 // If the entire remaining message is short enough to be sent all at once, remove
1629 // it from the wrkMsg and add it to the list of messages to be sent.
1630 wrkMsg.remove(0, splitPos);
1631 msgsToSend.append(initialSplitMsgEnc);
1633 } while (wrkMsg.size() > 0);