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 // Request a proper disconnect, but don't count as user-requested disconnect
126 if (socketConnected()) {
127 // Only try if the socket's fully connected (not initializing or disconnecting).
128 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
129 // shown even if other messages are queued.
130 disconnectFromIrc(false, QString(), false, true);
131 // Process the putCmd events that trigger the quit. Without this, shutting down the core
132 // results in abrubtly closing the socket rather than sending the QUIT as expected.
133 QCoreApplication::processEvents();
134 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
135 if (!forceDisconnect()) {
136 qWarning() << "Timed out quitting network" << networkName() <<
137 "(user ID " << userId() << ")";
140 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
141 delete _userInputHandler;
145 bool CoreNetwork::forceDisconnect(int msecs)
147 if (socket.state() == QAbstractSocket::UnconnectedState) {
148 // Socket already disconnected.
151 // Request a socket-level disconnect if not already happened
152 socket.disconnectFromHost();
153 // Return the result of waiting for disconnect; true if successful, otherwise false
154 return socket.waitForDisconnected(msecs);
158 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
160 if (!bufferName.isEmpty()) {
161 IrcChannel *channel = ircChannel(bufferName);
163 return channel->decodeString(string);
165 return decodeString(string);
169 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
171 IrcUser *user = ircUser(userNick);
173 return user->decodeString(string);
174 return decodeString(string);
178 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
180 if (!bufferName.isEmpty()) {
181 IrcChannel *channel = ircChannel(bufferName);
183 return channel->encodeString(string);
185 return encodeString(string);
189 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
191 IrcUser *user = ircUser(userNick);
193 return user->encodeString(string);
194 return encodeString(string);
198 void CoreNetwork::connectToIrc(bool reconnecting)
200 if (Core::instance()->identServer()) {
201 _socketId = Core::instance()->identServer()->addWaitingSocket();
204 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
205 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
206 if (unlimitedReconnectRetries())
207 _autoReconnectCount = -1;
209 _autoReconnectCount = autoReconnectRetries();
211 if (serverList().isEmpty()) {
212 qWarning() << "Server list empty, ignoring connect request!";
215 CoreIdentity *identity = identityPtr();
217 qWarning() << "Invalid identity configures, ignoring connect request!";
221 // cleaning up old quit reason
224 // Reset capability negotiation tracking, also handling server changes during reconnect
225 _capsQueuedIndividual.clear();
226 _capsQueuedBundled.clear();
228 _capNegotiationActive = false;
229 _capInitialNegotiationEnded = false;
231 // use a random server?
232 if (useRandomServer()) {
233 _lastUsedServerIndex = qrand() % serverList().size();
235 else if (_previousConnectionAttemptFailed) {
236 // cycle to next server if previous connection attempt failed
237 _previousConnectionAttemptFailed = false;
238 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
239 if (++_lastUsedServerIndex >= serverList().size()) {
240 _lastUsedServerIndex = 0;
244 // Start out with the top server in the list
245 _lastUsedServerIndex = 0;
248 Server server = usedServer();
249 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
250 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
252 if (server.useProxy) {
253 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
254 socket.setProxy(proxy);
257 socket.setProxy(QNetworkProxy::NoProxy);
262 // Reset tracking for valid timestamps in PONG replies
263 setPongTimestampValid(false);
265 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
266 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
267 if (! server.useProxy) {
268 //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
269 //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
270 QHostInfo::fromName(server.host);
274 CoreIdentity *identity = identityPtr();
276 socket.setLocalCertificate(identity->sslCert());
277 socket.setPrivateKey(identity->sslKey());
279 socket.connectToHostEncrypted(server.host, server.port);
282 socket.connectToHost(server.host, server.port);
285 socket.connectToHost(server.host, server.port);
290 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
293 // Disconnecting from the network, should expect a socket close or error
294 _disconnectExpected = true;
295 _quitRequested = requested; // see socketDisconnected();
296 if (!withReconnect) {
297 _autoReconnectTimer.stop();
298 _autoReconnectCount = 0; // prohibiting auto reconnect
300 disablePingTimeout();
307 awayMsg = me_->awayMessage();
308 Core::setAwayMessage(userId(), networkId(), awayMsg);
311 if (reason.isEmpty() && identityPtr())
312 _quitReason = identityPtr()->quitReason();
314 _quitReason = reason;
316 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
317 if (socket.state() == QAbstractSocket::UnconnectedState) {
318 socketDisconnected();
320 if (socket.state() == QAbstractSocket::ConnectedState) {
321 userInputHandler()->issueQuit(_quitReason, forceImmediate);
325 if (requested || withReconnect) {
326 // the irc server has 10 seconds to close the socket
327 _socketCloseTimer.start(10000);
333 void CoreNetwork::userInput(BufferInfo buf, QString msg)
335 userInputHandler()->handleUserInput(buf, msg);
339 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
341 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.size() == 0)) {
342 // If there's tokens remaining, ...
343 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
344 // Send the message now.
347 // Otherwise, queue the message for later
349 // Jump to the start, skipping other messages
350 _msgQueue.prepend(s);
352 // Add to back, waiting in order
359 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
363 if (!prefix.isEmpty())
364 msg += ":" + prefix + " ";
365 msg += cmd.toUpper().toLatin1();
367 for (int i = 0; i < params.size(); i++) {
370 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
376 putRawLine(msg, prepend);
380 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
382 QListIterator<QList<QByteArray>> i(params);
383 while (i.hasNext()) {
384 QList<QByteArray> msg = i.next();
385 putCmd(cmd, msg, prefix, prependAll);
390 void CoreNetwork::setChannelJoined(const QString &channel)
392 queueAutoWhoOneshot(channel); // check this new channel first
394 Core::setChannelPersistent(userId(), networkId(), channel, true);
395 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
399 void CoreNetwork::setChannelParted(const QString &channel)
401 removeChannelKey(channel);
402 _autoWhoQueue.removeAll(channel.toLower());
403 _autoWhoPending.remove(channel.toLower());
405 Core::setChannelPersistent(userId(), networkId(), channel, false);
409 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
412 removeChannelKey(channel);
415 _channelKeys[channel.toLower()] = key;
420 void CoreNetwork::removeChannelKey(const QString &channel)
422 _channelKeys.remove(channel.toLower());
427 Cipher *CoreNetwork::cipher(const QString &target)
429 if (target.isEmpty())
432 if (!Cipher::neededFeaturesAvailable())
435 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
437 return channel->cipher();
439 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
441 return user->cipher();
442 } else if (!isChannelName(target)) {
443 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
449 QByteArray CoreNetwork::cipherKey(const QString &target) const
451 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
453 return c->cipher()->key();
455 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
457 return u->cipher()->key();
463 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
465 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
467 c->setEncrypted(c->cipher()->setKey(key));
468 coreSession()->setBufferCipher(networkId(), target, key);
472 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
473 if (!u && !isChannelName(target))
474 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
477 u->setEncrypted(u->cipher()->setKey(key));
478 coreSession()->setBufferCipher(networkId(), target, key);
484 bool CoreNetwork::cipherUsesCBC(const QString &target)
486 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
488 return c->cipher()->usesCBC();
489 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
491 return u->cipher()->usesCBC();
495 #endif /* HAVE_QCA2 */
497 bool CoreNetwork::setAutoWhoDone(const QString &channel)
499 QString chan = channel.toLower();
500 if (_autoWhoPending.value(chan, 0) <= 0)
502 if (--_autoWhoPending[chan] <= 0)
503 _autoWhoPending.remove(chan);
508 void CoreNetwork::setMyNick(const QString &mynick)
510 Network::setMyNick(mynick);
511 if (connectionState() == Network::Initializing)
512 networkInitialized();
516 void CoreNetwork::socketHasData()
518 while (socket.canReadLine()) {
519 QByteArray s = socket.readLine();
520 if (s.endsWith("\r\n"))
522 else if (s.endsWith("\n"))
524 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
525 event->setTimestamp(QDateTime::currentDateTimeUtc());
526 emit newEvent(event);
531 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
533 // Ignore socket closed errors if expected
534 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
538 _previousConnectionAttemptFailed = true;
539 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
540 emit connectionError(socket.errorString());
541 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
542 emitConnectionError(socket.errorString());
543 if (socket.state() < QAbstractSocket::ConnectedState) {
544 socketDisconnected();
549 void CoreNetwork::socketInitialized()
551 CoreIdentity *identity = identityPtr();
553 qCritical() << "Identity invalid!";
558 Server server = usedServer();
561 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
562 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
563 if (!server.useSsl || !socket.isEncrypted()) {
564 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
567 if (server.useSsl && !socket.isEncrypted()) {
568 // We'll finish setup once we're encrypted, and called again
572 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
575 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
577 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
578 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
579 // force flag to apply user preferences. When making changes, ensure that this still happens!
580 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
581 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
583 updateRateLimiting(true);
584 // Fill up the token bucket as we're connecting from scratch
587 // Request capabilities as per IRCv3.2 specifications
588 // Older servers should ignore this; newer servers won't downgrade to RFC1459
589 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
590 putRawLine(serverEncode(QString("CAP LS 302")));
592 if (!server.password.isEmpty()) {
593 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
596 if (identity->nicks().isEmpty()) {
598 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
601 nick = identity->nicks()[0];
603 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
604 // Only allow strict-compliant idents when strict mode is enabled
605 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(
606 coreSession()->strictCompliantIdent(identity),
607 identity->realName())));
611 void CoreNetwork::socketDisconnected()
613 disablePingTimeout();
616 _autoWhoCycleTimer.stop();
617 _autoWhoTimer.stop();
618 _autoWhoQueue.clear();
619 _autoWhoPending.clear();
621 _socketCloseTimer.stop();
623 _tokenBucketTimer.stop();
627 foreach(QString channel, me_->channels())
628 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
632 emit disconnected(networkId());
633 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
634 // Reset disconnect expectations
635 _disconnectExpected = false;
636 if (_quitRequested) {
637 _quitRequested = false;
638 setConnectionState(Network::Disconnected);
639 Core::setNetworkConnected(userId(), networkId(), false);
641 else if (_autoReconnectCount != 0) {
642 setConnectionState(Network::Reconnecting);
643 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
644 doAutoReconnect(); // first try is immediate
646 _autoReconnectTimer.start();
651 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
653 Network::ConnectionState state;
654 switch (socketState) {
655 case QAbstractSocket::UnconnectedState:
656 state = Network::Disconnected;
657 socketDisconnected();
659 case QAbstractSocket::HostLookupState:
660 case QAbstractSocket::ConnectingState:
661 state = Network::Connecting;
663 case QAbstractSocket::ConnectedState:
664 state = Network::Initializing;
666 case QAbstractSocket::ClosingState:
667 state = Network::Disconnecting;
670 state = Network::Disconnected;
672 setConnectionState(state);
676 void CoreNetwork::networkInitialized()
678 setConnectionState(Network::Initialized);
680 _disconnectExpected = false;
681 _quitRequested = false;
683 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
684 // flag used for initial registration and capability negotiation.
685 updateRateLimiting();
687 if (useAutoReconnect()) {
689 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
692 // restore away state
693 QString awayMsg = Core::awayMessage(userId(), networkId());
694 if (!awayMsg.isEmpty()) {
695 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
696 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
697 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
704 if (networkConfig()->autoWhoEnabled()) {
705 _autoWhoCycleTimer.start();
706 _autoWhoTimer.start();
707 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
710 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
711 Core::setNetworkConnected(userId(), networkId(), true);
715 void CoreNetwork::sendPerform()
717 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
720 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
721 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
724 // restore old user modes if server default mode is set.
727 if (!me_->userModes().isEmpty()) {
731 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
732 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
737 foreach(QString line, perform()) {
738 if (!line.isEmpty()) userInput(statusBuf, line);
741 // rejoin channels we've been in
742 if (rejoinChannels()) {
743 QStringList channels, keys;
744 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
745 QString key = channelKey(chan);
746 if (!key.isEmpty()) {
747 channels.prepend(chan);
751 channels.append(chan);
754 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
755 if (!joinString.isEmpty())
756 userInputHandler()->handleJoin(statusBuf, joinString);
761 void CoreNetwork::restoreUserModes()
766 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
767 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
769 QString modesDelta = Core::userModes(userId(), networkId());
770 QString currentModes = me_->userModes();
772 QString addModes, removeModes;
773 if (modesDelta.contains('-')) {
774 addModes = modesDelta.section('-', 0, 0);
775 removeModes = modesDelta.section('-', 1);
778 addModes = modesDelta;
781 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
782 if (currentModes.isEmpty())
783 removeModes = QString();
785 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
787 if (addModes.isEmpty() && removeModes.isEmpty())
790 if (!addModes.isEmpty())
791 addModes = '+' + addModes;
792 if (!removeModes.isEmpty())
793 removeModes = '-' + removeModes;
795 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
796 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
800 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
806 for (int i = 0; i < requestedModes.length(); i++) {
807 if (requestedModes[i] == '+') {
811 if (requestedModes[i] == '-') {
816 addModes += requestedModes[i];
819 removeModes += requestedModes[i];
823 QString addModesOld = _requestedUserModes.section('-', 0, 0);
824 QString removeModesOld = _requestedUserModes.section('-', 1);
826 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
827 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
828 addModes += addModesOld;
830 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
831 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
832 removeModes += removeModesOld;
834 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
838 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
840 QString persistentUserModes = Core::userModes(userId(), networkId());
842 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
843 QString requestedRemove = _requestedUserModes.section('-', 1);
845 QString persistentAdd, persistentRemove;
846 if (persistentUserModes.contains('-')) {
847 persistentAdd = persistentUserModes.section('-', 0, 0);
848 persistentRemove = persistentUserModes.section('-', 1);
851 persistentAdd = persistentUserModes;
854 // remove modes we didn't issue
855 if (requestedAdd.isEmpty())
856 addModes = QString();
858 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
860 if (requestedRemove.isEmpty())
861 removeModes = QString();
863 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
866 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
867 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
870 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
871 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
873 // update issued mode list
874 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
875 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
876 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
878 persistentAdd += addModes;
879 persistentRemove += removeModes;
880 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
884 void CoreNetwork::resetPersistentModes()
886 _requestedUserModes = QString('-');
887 Core::setUserModes(userId(), networkId(), QString());
891 void CoreNetwork::setUseAutoReconnect(bool use)
893 Network::setUseAutoReconnect(use);
895 _autoReconnectTimer.stop();
899 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
901 Network::setAutoReconnectInterval(interval);
902 _autoReconnectTimer.setInterval(interval * 1000);
906 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
908 Network::setAutoReconnectRetries(retries);
909 if (_autoReconnectCount != 0) {
910 if (unlimitedReconnectRetries())
911 _autoReconnectCount = -1;
913 _autoReconnectCount = autoReconnectRetries();
918 void CoreNetwork::doAutoReconnect()
920 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
921 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
924 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
925 _autoReconnectCount--; // -2 means we delay the next reconnect
930 void CoreNetwork::sendPing()
932 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
933 if (_pingCount != 0) {
934 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
935 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
937 if ((int)_pingCount >= networkConfig()->maxPingCount()
938 && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
939 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
940 // However, to reduce the risk of breaking things by changing past behavior, we still allow
941 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
943 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
944 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
945 // and unable to even handle a ping answer. So we ignore those misses.
946 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
951 // Don't send pings until the network is initialized
953 // Mark as waiting for a reply
954 _pongReplyPending = true;
955 // Send default timestamp ping
956 userInputHandler()->handlePing(BufferInfo(), QString());
962 void CoreNetwork::enablePingTimeout(bool enable)
965 disablePingTimeout();
968 resetPongReplyPending();
969 if (networkConfig()->pingTimeoutEnabled())
975 void CoreNetwork::disablePingTimeout()
980 resetPongReplyPending();
984 void CoreNetwork::setPingInterval(int interval)
986 _pingTimer.setInterval(interval * 1000);
990 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
992 _pongTimestampValid = validTimestamp;
996 /******** Custom Rate Limiting ********/
998 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
1000 // Verify and apply custom rate limiting options, always resetting the delay and burst size
1001 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
1002 // this may be called while connected to a server.
1004 if (useCustomMessageRate() || forceUnlimited) {
1005 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
1007 _messageDelay = messageRateDelay();
1009 _burstSize = messageRateBurstSize();
1010 if (_burstSize < 1) {
1011 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
1013 // Can't go slower than one message at a time
1017 if (_tokenBucket > _burstSize) {
1018 // Don't let the token bucket exceed the maximum
1019 _tokenBucket = _burstSize;
1020 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1021 // changing the rate-limit settings while connected to a server will incorrectly reset
1022 // the token bucket.
1025 // Toggle the timer according to whether or not rate limiting is enabled
1026 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1027 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1028 // Override user preferences if called with force unlimited, only used during connect.
1029 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1030 if (_skipMessageRates) {
1031 // If the message queue already contains messages, they need sent before disabling the
1032 // timer. Set the timer to a rapid pace and let it disable itself.
1033 if (_msgQueue.size() > 0) {
1034 qDebug() << "Outgoing message queue contains messages while disabling rate "
1035 "limiting. Sending remaining queued messages...";
1036 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1037 // so nothing should cause this to block.. in theory. However, don't directly call
1038 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1040 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1041 // Hesitant to change it without a wide variety of situations to verify behavior.
1042 _tokenBucketTimer.start(100);
1044 // No rate limiting, disable the timer
1045 _tokenBucketTimer.stop();
1048 // Rate limiting enabled, enable the timer
1049 _tokenBucketTimer.start(_messageDelay);
1052 // Custom message rates disabled. Go for the default.
1054 _skipMessageRates = false; // Enable rate-limiting by default
1055 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1056 _burstSize = 5; // 5 messages at once
1057 if (_tokenBucket > _burstSize) {
1058 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1060 _tokenBucket = _burstSize;
1061 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1062 // changing the rate-limit settings while connected to a server will incorrectly reset
1063 // the token bucket.
1065 // Rate limiting enabled, enable the timer
1066 _tokenBucketTimer.start(_messageDelay);
1070 void CoreNetwork::resetTokenBucket()
1072 // Fill up the token bucket to the maximum
1073 _tokenBucket = _burstSize;
1077 /******** IRCv3 Capability Negotiation ********/
1079 void CoreNetwork::serverCapAdded(const QString &capability)
1081 // Check if it's a known capability; if so, add it to the list
1082 // Handle special cases first
1083 if (capability == IrcCap::SASL) {
1084 // Only request SASL if it's enabled
1085 if (networkInfo().useSasl)
1086 queueCap(capability);
1087 } else if (IrcCap::knownCaps.contains(capability)) {
1088 // Handling for general known capabilities
1089 queueCap(capability);
1093 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1095 // This may be called multiple times in certain situations.
1097 // Handle core-side configuration
1098 if (capability == IrcCap::AWAY_NOTIFY) {
1099 // away-notify enabled, stop the autoWho timers, handle manually
1100 setAutoWhoEnabled(false);
1103 // Handle capabilities that require further messages sent to the IRC server
1104 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1105 if (capability == IrcCap::SASL) {
1106 // If SASL mechanisms specified, limit to what's accepted for authentication
1107 // if the current identity has a cert set, use SASL EXTERNAL
1110 if (!identityPtr()->sslCert().isNull()) {
1111 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1112 // EXTERNAL authentication supported, send request
1113 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1115 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1116 tr("SASL EXTERNAL authentication not supported"));
1121 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1122 // PLAIN authentication supported, send request
1123 // Only working with PLAIN atm, blowfish later
1124 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1126 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1127 tr("SASL PLAIN authentication not supported"));
1136 void CoreNetwork::serverCapRemoved(const QString &capability)
1138 // This may be called multiple times in certain situations.
1140 // Handle special cases here
1141 if (capability == IrcCap::AWAY_NOTIFY) {
1142 // away-notify disabled, enable autoWho according to configuration
1143 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1147 void CoreNetwork::queueCap(const QString &capability)
1149 // IRCv3 specs all use lowercase capability names
1150 QString _capLowercase = capability.toLower();
1152 if(capsRequiringConfiguration.contains(_capLowercase)) {
1153 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1154 // so we should negotiate it separately from all other capabilities. Otherwise new
1155 // capabilities will be requested while still configuring the previous one.
1156 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1157 _capsQueuedIndividual.append(_capLowercase);
1160 // The capability doesn't need any special configuration, so it should be safe to try
1161 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1163 if (!_capsQueuedBundled.contains(_capLowercase)) {
1164 _capsQueuedBundled.append(_capLowercase);
1169 QString CoreNetwork::takeQueuedCaps()
1171 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1173 _capsQueuedLastBundle.clear();
1175 // First, negotiate all the standalone capabilities that require additional configuration.
1176 if (!_capsQueuedIndividual.empty()) {
1177 // We have an individual capability available. Take the first and pass it back.
1178 return _capsQueuedIndividual.takeFirst();
1179 } else if (!_capsQueuedBundled.empty()) {
1180 // We have capabilities available that can be grouped. Try to fit in as many as within the
1182 // See CoreNetwork::maxCapRequestLength
1184 // Response must have at least one capability regardless of max length for anything to
1186 QString capBundle = _capsQueuedBundled.takeFirst();
1187 QString nextCap("");
1188 while (!_capsQueuedBundled.empty()) {
1189 // As long as capabilities remain, get the next...
1190 nextCap = _capsQueuedBundled.first();
1191 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1192 // [capability + 1 for a space + this new capability] fit within length limits
1193 // Add it to formatted list
1194 capBundle.append(" " + nextCap);
1195 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1196 _capsQueuedLastBundle.append(nextCap);
1197 // Then remove it from the queue
1198 _capsQueuedBundled.removeFirst();
1200 // We've reached the length limit for a single capability request, stop adding more
1204 // Return this space-separated set of capabilities, removing any extra spaces
1205 return capBundle.trimmed();
1207 // No capabilities left to negotiate, return an empty string.
1212 void CoreNetwork::retryCapsIndividually()
1214 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1215 // denied, try each capability individually.
1216 if (_capsQueuedLastBundle.empty()) {
1217 // No most recently tried capability set, just return.
1219 // Note: there's little point in retrying individually requested caps during negotiation.
1220 // We know the individual capability was the one that failed, and it's not likely it'll
1221 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1222 // handling capability removal and addition.
1225 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1226 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1227 // keeping track of which halves of the group fail, dividing the set each time.
1229 // Add most recently tried capability set to individual list, re-requesting them one at a time
1230 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1231 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1232 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1233 tr("Could not negotiate some capabilities, retrying individually (%1)...")
1234 .arg(_capsQueuedLastBundle.join(", ")));
1235 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1236 // need to remove them here.
1237 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1239 _capsQueuedLastBundle.clear();
1242 void CoreNetwork::beginCapNegotiation()
1244 // Don't begin negotiation if no capabilities are queued to request
1245 if (!capNegotiationInProgress()) {
1246 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1247 // normal connection.
1248 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1249 endCapNegotiation();
1253 _capNegotiationActive = true;
1254 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1255 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1257 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1258 // comma separator between the two if needed (both individual and bundled caps exist).
1259 QString queuedCapsDisplay =
1260 _capsQueuedIndividual.join(", ")
1261 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1262 + _capsQueuedBundled.join(", ");
1263 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1264 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1269 void CoreNetwork::sendNextCap()
1271 if (capNegotiationInProgress()) {
1272 // Request the next set of capabilities and remove them from the list
1273 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1275 // No pending desired capabilities, capability negotiation finished
1276 // If SASL requested but not available, print a warning
1277 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1278 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1279 tr("SASL authentication currently not supported by server"));
1281 if (_capNegotiationActive) {
1282 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1283 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1284 _capNegotiationActive = false;
1287 endCapNegotiation();
1291 void CoreNetwork::endCapNegotiation()
1293 // If nick registration is already complete, CAP END is not required
1294 if (!_capInitialNegotiationEnded) {
1295 putRawLine(serverEncode(QString("CAP END")));
1296 _capInitialNegotiationEnded = true;
1300 /******** AutoWHO ********/
1302 void CoreNetwork::startAutoWhoCycle()
1304 if (!_autoWhoQueue.isEmpty()) {
1305 _autoWhoCycleTimer.stop();
1308 _autoWhoQueue = channels();
1311 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1313 // Prepend so these new channels/nicks are the first to be checked
1314 // Don't allow duplicates
1315 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1316 _autoWhoQueue.prepend(channelOrNick.toLower());
1318 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1319 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1320 setAutoWhoEnabled(true);
1325 void CoreNetwork::setAutoWhoDelay(int delay)
1327 _autoWhoTimer.setInterval(delay * 1000);
1331 void CoreNetwork::setAutoWhoInterval(int interval)
1333 _autoWhoCycleTimer.setInterval(interval * 1000);
1337 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1339 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1340 _autoWhoTimer.start();
1341 else if (!enabled) {
1342 _autoWhoTimer.stop();
1343 _autoWhoCycleTimer.stop();
1348 void CoreNetwork::sendAutoWho()
1350 // Don't send autowho if there are still some pending
1351 if (_autoWhoPending.count())
1354 while (!_autoWhoQueue.isEmpty()) {
1355 QString chanOrNick = _autoWhoQueue.takeFirst();
1356 // Check if it's a known channel or nick
1357 IrcChannel *ircchan = ircChannel(chanOrNick);
1358 IrcUser *ircuser = ircUser(chanOrNick);
1360 // Apply channel limiting rules
1361 // If using away-notify, don't impose channel size limits in order to capture away
1362 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1363 if (networkConfig()->autoWhoNickLimit() > 0
1364 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1365 && !capEnabled(IrcCap::AWAY_NOTIFY))
1367 _autoWhoPending[chanOrNick.toLower()]++;
1368 } else if (ircuser) {
1369 // Checking a nick, add it to the pending list
1370 _autoWhoPending[ircuser->nick().toLower()]++;
1372 // Not a channel or a nick, skip it
1373 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1376 if (supports("WHOX")) {
1377 // Use WHO extended to poll away users and/or user accounts
1378 // See http://faerion.sourceforge.net/doc/irc/whox.var
1379 // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1380 putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1381 .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1383 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1388 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1389 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1390 // Timer was stopped, means a new cycle is due immediately
1391 // Don't run a new cycle if using away-notify; server will notify as appropriate
1392 _autoWhoCycleTimer.start();
1393 startAutoWhoCycle();
1394 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1395 // Don't run another who cycle if away-notify is enabled
1396 _autoWhoCycleTimer.stop();
1402 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1404 Server server = usedServer();
1405 if (server.sslVerify) {
1406 // Treat the SSL error as a hard error
1407 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1408 "since verification is required");
1409 if (!sslErrors.empty()) {
1410 // Add the error reason if known
1411 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1413 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1415 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1416 // validity, network trouble, etc.
1417 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1419 // Treat the SSL error as a warning, continue to connect anyways
1420 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1421 "since verification is not required");
1422 if (!sslErrors.empty()) {
1423 // Add the error reason if known
1424 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1426 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1428 // Proceed with the connection
1429 socket.ignoreSslErrors();
1436 void CoreNetwork::checkTokenBucket()
1438 if (_skipMessageRates) {
1439 if (_msgQueue.size() == 0) {
1440 // Message queue emptied; stop the timer and bail out
1441 _tokenBucketTimer.stop();
1444 // Otherwise, we're emptying the queue, continue on as normal
1447 // Process whatever messages are pending
1448 fillBucketAndProcessQueue();
1452 void CoreNetwork::fillBucketAndProcessQueue()
1454 // If there's less tokens than burst size, refill the token bucket by 1
1455 if (_tokenBucket < _burstSize) {
1459 // As long as there's tokens available and messages remaining, sending messages from the queue
1460 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1461 writeToSocket(_msgQueue.takeFirst());
1466 void CoreNetwork::writeToSocket(const QByteArray &data)
1468 // Log the message if enabled and network ID matches or allows all
1470 && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1471 // Include network ID
1472 qDebug() << "IRC net" << networkId() << ">>" << data;
1475 socket.write("\r\n");
1476 if (!_skipMessageRates) {
1477 // Only subtract from the token bucket if message rate limiting is enabled
1483 Network::Server CoreNetwork::usedServer() const
1485 if (_lastUsedServerIndex < serverList().count())
1486 return serverList()[_lastUsedServerIndex];
1488 if (!serverList().isEmpty())
1489 return serverList()[0];
1491 return Network::Server();
1495 void CoreNetwork::requestConnect() const
1497 if (connectionState() != Disconnected) {
1498 qWarning() << "Requesting connect while already being connected!";
1501 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1505 void CoreNetwork::requestDisconnect() const
1507 if (connectionState() == Disconnected) {
1508 qWarning() << "Requesting disconnect while not being connected!";
1511 userInputHandler()->handleQuit(BufferInfo(), QString());
1515 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1517 Network::Server currentServer = usedServer();
1518 setNetworkInfo(info);
1519 Core::updateNetwork(coreSession()->user(), info);
1521 // the order of the servers might have changed,
1522 // so we try to find the previously used server
1523 _lastUsedServerIndex = 0;
1524 for (int i = 0; i < serverList().count(); i++) {
1525 Network::Server server = serverList()[i];
1526 if (server.host == currentServer.host && server.port == currentServer.port) {
1527 _lastUsedServerIndex = i;
1534 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1536 QString wrkMsg(message);
1537 QList<QList<QByteArray>> msgsToSend;
1539 // do while (wrkMsg.size() > 0)
1541 // First, check to see if the whole message can be sent at once. The
1542 // cmdGenerator function is passed in by the caller and is used to encode
1543 // and encrypt (if applicable) the message, since different callers might
1544 // want to use different encoding or encode different values.
1545 int splitPos = wrkMsg.size();
1546 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1547 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1549 if (initialOverrun) {
1550 // If the message was too long to be sent, first try splitting it along
1551 // word boundaries with QTextBoundaryFinder.
1552 QString splitMsg(wrkMsg);
1553 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1554 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1555 QList<QByteArray> splitMsgEnc;
1556 int overrun = initialOverrun;
1559 splitPos = qtbf.toPreviousBoundary();
1561 // splitPos==-1 means the QTBF couldn't find a split point at all and
1562 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1563 // the string. Neither one of these works for us.
1565 // If a split point could be found, split the message there, calculate the
1566 // overrun, and continue with the loop.
1567 splitMsg = splitMsg.left(splitPos);
1568 splitMsgEnc = cmdGenerator(splitMsg);
1569 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1572 // If a split point could not be found (the beginning of the message
1573 // is reached without finding a split point short enough to send) and we
1574 // are still in Word mode, switch to Grapheme mode. We also need to restore
1575 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1576 // the previous attempt to find a split point.
1577 if (qtbf.type() == QTextBoundaryFinder::Word) {
1579 splitPos = splitMsg.size();
1580 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1581 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1582 qtbf = graphemeQtbf;
1585 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1586 // This should never happen, but it should be handled anyway.
1587 qWarning() << "Unexpected failure to split message!";
1593 // Once a message of sendable length has been found, remove it from the wrkMsg and
1594 // add it to the list of messages to be sent.
1595 wrkMsg.remove(0, splitPos);
1596 msgsToSend.append(splitMsgEnc);
1599 // If the entire remaining message is short enough to be sent all at once, remove
1600 // it from the wrkMsg and add it to the list of messages to be sent.
1601 wrkMsg.remove(0, splitPos);
1602 msgsToSend.append(initialSplitMsgEnc);
1604 } while (wrkMsg.size() > 0);