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 ***************************************************************************/
23 #include "corenetwork.h"
26 #include "coreidentity.h"
27 #include "corenetworkconfig.h"
28 #include "coresession.h"
29 #include "coreuserinputhandler.h"
30 #include "networkevent.h"
35 INIT_SYNCABLE_OBJECT(CoreNetwork)
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),
50 _requestedUserModes('-')
52 _autoReconnectTimer.setSingleShot(true);
53 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
55 setPingInterval(networkConfig()->pingInterval());
56 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
58 setAutoWhoDelay(networkConfig()->autoWhoDelay());
59 setAutoWhoInterval(networkConfig()->autoWhoInterval());
61 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
62 foreach(QString chan, channels.keys()) {
63 _channelKeys[chan.toLower()] = channels[chan];
66 QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
67 foreach(QString buffer, bufferCiphers.keys()) {
68 storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
71 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
72 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
73 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
74 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
75 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
77 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
78 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
79 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
80 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(checkTokenBucket()));
82 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
83 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
84 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
85 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
87 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
88 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
90 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
92 // Custom rate limiting
93 // These react to the user changing settings in the client
94 connect(this, SIGNAL(useCustomMessageRateSet(bool)), SLOT(updateRateLimiting()));
95 connect(this, SIGNAL(messageRateBurstSizeSet(quint32)), SLOT(updateRateLimiting()));
96 connect(this, SIGNAL(messageRateDelaySet(quint32)), SLOT(updateRateLimiting()));
97 connect(this, SIGNAL(unlimitedMessageRateSet(bool)), SLOT(updateRateLimiting()));
99 // IRCv3 capability handling
100 // These react to CAP messages from the server
101 connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
102 connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
103 connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
105 if (Quassel::isOptionSet("oidentd")) {
106 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
107 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
110 if (Quassel::isOptionSet("ident-daemon")) {
111 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Core::instance()->identServer(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Qt::BlockingQueuedConnection);
112 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Core::instance()->identServer(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)));
117 CoreNetwork::~CoreNetwork()
119 // Request a proper disconnect, but don't count as user-requested disconnect
120 if (socketConnected()) {
121 // Only try if the socket's fully connected (not initializing or disconnecting).
122 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
123 // shown even if other messages are queued.
124 disconnectFromIrc(false, QString(), false, true);
125 // Process the putCmd events that trigger the quit. Without this, shutting down the core
126 // results in abrubtly closing the socket rather than sending the QUIT as expected.
127 QCoreApplication::processEvents();
128 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
129 if (!forceDisconnect()) {
130 qWarning() << "Timed out quitting network" << networkName() <<
131 "(user ID " << userId() << ")";
134 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
135 delete _userInputHandler;
139 bool CoreNetwork::forceDisconnect(int msecs)
141 if (socket.state() == QAbstractSocket::UnconnectedState) {
142 // Socket already disconnected.
145 // Request a socket-level disconnect if not already happened
146 socket.disconnectFromHost();
147 // Return the result of waiting for disconnect; true if successful, otherwise false
148 return socket.waitForDisconnected(msecs);
152 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
154 if (!bufferName.isEmpty()) {
155 IrcChannel *channel = ircChannel(bufferName);
157 return channel->decodeString(string);
159 return decodeString(string);
163 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
165 IrcUser *user = ircUser(userNick);
167 return user->decodeString(string);
168 return decodeString(string);
172 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
174 if (!bufferName.isEmpty()) {
175 IrcChannel *channel = ircChannel(bufferName);
177 return channel->encodeString(string);
179 return encodeString(string);
183 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
185 IrcUser *user = ircUser(userNick);
187 return user->encodeString(string);
188 return encodeString(string);
192 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 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
257 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
258 if (! server.useProxy) {
259 //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
260 //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
261 QHostInfo::fromName(server.host);
265 CoreIdentity *identity = identityPtr();
267 socket.setLocalCertificate(identity->sslCert());
268 socket.setPrivateKey(identity->sslKey());
270 socket.connectToHostEncrypted(server.host, server.port);
273 socket.connectToHost(server.host, server.port);
276 socket.connectToHost(server.host, server.port);
281 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
284 // Disconnecting from the network, should expect a socket close or error
285 _disconnectExpected = true;
286 _quitRequested = requested; // see socketDisconnected();
287 if (!withReconnect) {
288 _autoReconnectTimer.stop();
289 _autoReconnectCount = 0; // prohibiting auto reconnect
291 disablePingTimeout();
298 awayMsg = me_->awayMessage();
299 Core::setAwayMessage(userId(), networkId(), awayMsg);
302 if (reason.isEmpty() && identityPtr())
303 _quitReason = identityPtr()->quitReason();
305 _quitReason = reason;
307 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
308 if (socket.state() == QAbstractSocket::UnconnectedState) {
309 socketDisconnected();
311 if (socket.state() == QAbstractSocket::ConnectedState) {
312 userInputHandler()->issueQuit(_quitReason, forceImmediate);
316 if (requested || withReconnect) {
317 // the irc server has 10 seconds to close the socket
318 _socketCloseTimer.start(10000);
324 void CoreNetwork::userInput(BufferInfo buf, QString msg)
326 userInputHandler()->handleUserInput(buf, msg);
330 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
332 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.size() == 0)) {
333 // If there's tokens remaining, ...
334 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
335 // Send the message now.
338 // Otherwise, queue the message for later
340 // Jump to the start, skipping other messages
341 _msgQueue.prepend(s);
343 // Add to back, waiting in order
350 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
354 if (!prefix.isEmpty())
355 msg += ":" + prefix + " ";
356 msg += cmd.toUpper().toLatin1();
358 for (int i = 0; i < params.size(); i++) {
361 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
367 putRawLine(msg, prepend);
371 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
373 QListIterator<QList<QByteArray>> i(params);
374 while (i.hasNext()) {
375 QList<QByteArray> msg = i.next();
376 putCmd(cmd, msg, prefix, prependAll);
381 void CoreNetwork::setChannelJoined(const QString &channel)
383 queueAutoWhoOneshot(channel); // check this new channel first
385 Core::setChannelPersistent(userId(), networkId(), channel, true);
386 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
390 void CoreNetwork::setChannelParted(const QString &channel)
392 removeChannelKey(channel);
393 _autoWhoQueue.removeAll(channel.toLower());
394 _autoWhoPending.remove(channel.toLower());
396 Core::setChannelPersistent(userId(), networkId(), channel, false);
400 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
403 removeChannelKey(channel);
406 _channelKeys[channel.toLower()] = key;
411 void CoreNetwork::removeChannelKey(const QString &channel)
413 _channelKeys.remove(channel.toLower());
418 Cipher *CoreNetwork::cipher(const QString &target)
420 if (target.isEmpty())
423 if (!Cipher::neededFeaturesAvailable())
426 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
428 return channel->cipher();
430 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
432 return user->cipher();
433 } else if (!isChannelName(target)) {
434 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
440 QByteArray CoreNetwork::cipherKey(const QString &target) const
442 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
444 return c->cipher()->key();
446 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
448 return u->cipher()->key();
454 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
456 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
458 c->setEncrypted(c->cipher()->setKey(key));
459 coreSession()->setBufferCipher(networkId(), target, key);
463 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
464 if (!u && !isChannelName(target))
465 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
468 u->setEncrypted(u->cipher()->setKey(key));
469 coreSession()->setBufferCipher(networkId(), target, key);
475 bool CoreNetwork::cipherUsesCBC(const QString &target)
477 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
479 return c->cipher()->usesCBC();
480 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
482 return u->cipher()->usesCBC();
486 #endif /* HAVE_QCA2 */
488 bool CoreNetwork::setAutoWhoDone(const QString &channel)
490 QString chan = channel.toLower();
491 if (_autoWhoPending.value(chan, 0) <= 0)
493 if (--_autoWhoPending[chan] <= 0)
494 _autoWhoPending.remove(chan);
499 void CoreNetwork::setMyNick(const QString &mynick)
501 Network::setMyNick(mynick);
502 if (connectionState() == Network::Initializing)
503 networkInitialized();
507 void CoreNetwork::socketHasData()
509 while (socket.canReadLine()) {
510 QByteArray s = socket.readLine();
511 if (s.endsWith("\r\n"))
513 else if (s.endsWith("\n"))
515 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
516 event->setTimestamp(QDateTime::currentDateTimeUtc());
517 emit newEvent(event);
522 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
524 // Ignore socket closed errors if expected
525 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
529 _previousConnectionAttemptFailed = true;
530 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
531 emit connectionError(socket.errorString());
532 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
533 emitConnectionError(socket.errorString());
534 if (socket.state() < QAbstractSocket::ConnectedState) {
535 socketDisconnected();
540 void CoreNetwork::socketInitialized()
542 CoreIdentity *identity = identityPtr();
544 qCritical() << "Identity invalid!";
549 Server server = usedServer();
552 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
553 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
554 if (!server.useSsl || !socket.isEncrypted()) {
555 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
558 if (server.useSsl && !socket.isEncrypted()) {
559 // We'll finish setup once we're encrypted, and called again
563 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
566 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
568 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
569 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
570 // force flag to apply user preferences. When making changes, ensure that this still happens!
571 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
572 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
574 updateRateLimiting(true);
575 // Fill up the token bucket as we're connecting from scratch
578 // Request capabilities as per IRCv3.2 specifications
579 // Older servers should ignore this; newer servers won't downgrade to RFC1459
580 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
581 putRawLine(serverEncode(QString("CAP LS 302")));
583 if (!server.password.isEmpty()) {
584 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
587 if (identity->nicks().isEmpty()) {
589 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
592 nick = identity->nicks()[0];
594 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
595 // Only allow strict-compliant idents when strict mode is enabled
596 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(
597 coreSession()->strictCompliantIdent(identity),
598 identity->realName())));
602 void CoreNetwork::socketDisconnected()
604 disablePingTimeout();
607 _autoWhoCycleTimer.stop();
608 _autoWhoTimer.stop();
609 _autoWhoQueue.clear();
610 _autoWhoPending.clear();
612 _socketCloseTimer.stop();
614 _tokenBucketTimer.stop();
618 foreach(QString channel, me_->channels())
619 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
623 emit disconnected(networkId());
624 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
625 // Reset disconnect expectations
626 _disconnectExpected = false;
627 if (_quitRequested) {
628 _quitRequested = false;
629 setConnectionState(Network::Disconnected);
630 Core::setNetworkConnected(userId(), networkId(), false);
632 else if (_autoReconnectCount != 0) {
633 setConnectionState(Network::Reconnecting);
634 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
635 doAutoReconnect(); // first try is immediate
637 _autoReconnectTimer.start();
642 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
644 Network::ConnectionState state;
645 switch (socketState) {
646 case QAbstractSocket::UnconnectedState:
647 state = Network::Disconnected;
648 socketDisconnected();
650 case QAbstractSocket::HostLookupState:
651 case QAbstractSocket::ConnectingState:
652 state = Network::Connecting;
654 case QAbstractSocket::ConnectedState:
655 state = Network::Initializing;
657 case QAbstractSocket::ClosingState:
658 state = Network::Disconnecting;
661 state = Network::Disconnected;
663 setConnectionState(state);
667 void CoreNetwork::networkInitialized()
669 setConnectionState(Network::Initialized);
671 _disconnectExpected = false;
672 _quitRequested = false;
674 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
675 // flag used for initial registration and capability negotiation.
676 updateRateLimiting();
678 if (useAutoReconnect()) {
680 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
683 // restore away state
684 QString awayMsg = Core::awayMessage(userId(), networkId());
685 if (!awayMsg.isEmpty()) {
686 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
687 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
688 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
695 if (networkConfig()->autoWhoEnabled()) {
696 _autoWhoCycleTimer.start();
697 _autoWhoTimer.start();
698 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
701 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
702 Core::setNetworkConnected(userId(), networkId(), true);
706 void CoreNetwork::sendPerform()
708 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
711 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
712 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
715 // restore old user modes if server default mode is set.
718 if (!me_->userModes().isEmpty()) {
722 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
723 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
728 foreach(QString line, perform()) {
729 if (!line.isEmpty()) userInput(statusBuf, line);
732 // rejoin channels we've been in
733 if (rejoinChannels()) {
734 QStringList channels, keys;
735 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
736 QString key = channelKey(chan);
737 if (!key.isEmpty()) {
738 channels.prepend(chan);
742 channels.append(chan);
745 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
746 if (!joinString.isEmpty())
747 userInputHandler()->handleJoin(statusBuf, joinString);
752 void CoreNetwork::restoreUserModes()
757 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
758 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
760 QString modesDelta = Core::userModes(userId(), networkId());
761 QString currentModes = me_->userModes();
763 QString addModes, removeModes;
764 if (modesDelta.contains('-')) {
765 addModes = modesDelta.section('-', 0, 0);
766 removeModes = modesDelta.section('-', 1);
769 addModes = modesDelta;
772 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
773 if (currentModes.isEmpty())
774 removeModes = QString();
776 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
778 if (addModes.isEmpty() && removeModes.isEmpty())
781 if (!addModes.isEmpty())
782 addModes = '+' + addModes;
783 if (!removeModes.isEmpty())
784 removeModes = '-' + removeModes;
786 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
787 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
791 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
797 for (int i = 0; i < requestedModes.length(); i++) {
798 if (requestedModes[i] == '+') {
802 if (requestedModes[i] == '-') {
807 addModes += requestedModes[i];
810 removeModes += requestedModes[i];
814 QString addModesOld = _requestedUserModes.section('-', 0, 0);
815 QString removeModesOld = _requestedUserModes.section('-', 1);
817 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
818 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
819 addModes += addModesOld;
821 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
822 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
823 removeModes += removeModesOld;
825 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
829 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
831 QString persistentUserModes = Core::userModes(userId(), networkId());
833 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
834 QString requestedRemove = _requestedUserModes.section('-', 1);
836 QString persistentAdd, persistentRemove;
837 if (persistentUserModes.contains('-')) {
838 persistentAdd = persistentUserModes.section('-', 0, 0);
839 persistentRemove = persistentUserModes.section('-', 1);
842 persistentAdd = persistentUserModes;
845 // remove modes we didn't issue
846 if (requestedAdd.isEmpty())
847 addModes = QString();
849 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
851 if (requestedRemove.isEmpty())
852 removeModes = QString();
854 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
857 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
858 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
861 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
862 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
864 // update issued mode list
865 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
866 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
867 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
869 persistentAdd += addModes;
870 persistentRemove += removeModes;
871 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
875 void CoreNetwork::resetPersistentModes()
877 _requestedUserModes = QString('-');
878 Core::setUserModes(userId(), networkId(), QString());
882 void CoreNetwork::setUseAutoReconnect(bool use)
884 Network::setUseAutoReconnect(use);
886 _autoReconnectTimer.stop();
890 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
892 Network::setAutoReconnectInterval(interval);
893 _autoReconnectTimer.setInterval(interval * 1000);
897 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
899 Network::setAutoReconnectRetries(retries);
900 if (_autoReconnectCount != 0) {
901 if (unlimitedReconnectRetries())
902 _autoReconnectCount = -1;
904 _autoReconnectCount = autoReconnectRetries();
909 void CoreNetwork::doAutoReconnect()
911 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
912 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
915 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
916 _autoReconnectCount--; // -2 means we delay the next reconnect
921 void CoreNetwork::sendPing()
923 qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
924 if (_pingCount != 0) {
925 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
926 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
928 if ((int)_pingCount >= networkConfig()->maxPingCount()
929 && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
930 // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
931 // However, to reduce the risk of breaking things by changing past behavior, we still allow
932 // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
934 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
935 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
936 // and unable to even handle a ping answer. So we ignore those misses.
937 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
942 // Don't send pings until the network is initialized
944 userInputHandler()->handlePing(BufferInfo(), QString());
949 void CoreNetwork::enablePingTimeout(bool enable)
952 disablePingTimeout();
955 if (networkConfig()->pingTimeoutEnabled())
961 void CoreNetwork::disablePingTimeout()
969 void CoreNetwork::setPingInterval(int interval)
971 _pingTimer.setInterval(interval * 1000);
975 /******** Custom Rate Limiting ********/
977 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
979 // Verify and apply custom rate limiting options, always resetting the delay and burst size
980 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
981 // this may be called while connected to a server.
983 if (useCustomMessageRate() || forceUnlimited) {
984 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
986 _messageDelay = messageRateDelay();
988 _burstSize = messageRateBurstSize();
989 if (_burstSize < 1) {
990 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
992 // Can't go slower than one message at a time
996 if (_tokenBucket > _burstSize) {
997 // Don't let the token bucket exceed the maximum
998 _tokenBucket = _burstSize;
999 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1000 // changing the rate-limit settings while connected to a server will incorrectly reset
1001 // the token bucket.
1004 // Toggle the timer according to whether or not rate limiting is enabled
1005 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
1006 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1007 // Override user preferences if called with force unlimited, only used during connect.
1008 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1009 if (_skipMessageRates) {
1010 // If the message queue already contains messages, they need sent before disabling the
1011 // timer. Set the timer to a rapid pace and let it disable itself.
1012 if (_msgQueue.size() > 0) {
1013 qDebug() << "Outgoing message queue contains messages while disabling rate "
1014 "limiting. Sending remaining queued messages...";
1015 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
1016 // so nothing should cause this to block.. in theory. However, don't directly call
1017 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1019 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1020 // Hesitant to change it without a wide variety of situations to verify behavior.
1021 _tokenBucketTimer.start(100);
1023 // No rate limiting, disable the timer
1024 _tokenBucketTimer.stop();
1027 // Rate limiting enabled, enable the timer
1028 _tokenBucketTimer.start(_messageDelay);
1031 // Custom message rates disabled. Go for the default.
1033 _skipMessageRates = false; // Enable rate-limiting by default
1034 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1035 _burstSize = 5; // 5 messages at once
1036 if (_tokenBucket > _burstSize) {
1037 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1039 _tokenBucket = _burstSize;
1040 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1041 // changing the rate-limit settings while connected to a server will incorrectly reset
1042 // the token bucket.
1044 // Rate limiting enabled, enable the timer
1045 _tokenBucketTimer.start(_messageDelay);
1049 void CoreNetwork::resetTokenBucket()
1051 // Fill up the token bucket to the maximum
1052 _tokenBucket = _burstSize;
1056 /******** IRCv3 Capability Negotiation ********/
1058 void CoreNetwork::serverCapAdded(const QString &capability)
1060 // Check if it's a known capability; if so, add it to the list
1061 // Handle special cases first
1062 if (capability == IrcCap::SASL) {
1063 // Only request SASL if it's enabled
1064 if (networkInfo().useSasl)
1065 queueCap(capability);
1066 } else if (IrcCap::knownCaps.contains(capability)) {
1067 // Handling for general known capabilities
1068 queueCap(capability);
1072 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1074 // This may be called multiple times in certain situations.
1076 // Handle core-side configuration
1077 if (capability == IrcCap::AWAY_NOTIFY) {
1078 // away-notify enabled, stop the autoWho timers, handle manually
1079 setAutoWhoEnabled(false);
1082 // Handle capabilities that require further messages sent to the IRC server
1083 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1084 if (capability == IrcCap::SASL) {
1085 // If SASL mechanisms specified, limit to what's accepted for authentication
1086 // if the current identity has a cert set, use SASL EXTERNAL
1089 if (!identityPtr()->sslCert().isNull()) {
1090 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1091 // EXTERNAL authentication supported, send request
1092 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1094 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1095 tr("SASL EXTERNAL authentication not supported"));
1100 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1101 // PLAIN authentication supported, send request
1102 // Only working with PLAIN atm, blowfish later
1103 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1105 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1106 tr("SASL PLAIN authentication not supported"));
1115 void CoreNetwork::serverCapRemoved(const QString &capability)
1117 // This may be called multiple times in certain situations.
1119 // Handle special cases here
1120 if (capability == IrcCap::AWAY_NOTIFY) {
1121 // away-notify disabled, enable autoWho according to configuration
1122 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1126 void CoreNetwork::queueCap(const QString &capability)
1128 // IRCv3 specs all use lowercase capability names
1129 QString _capLowercase = capability.toLower();
1131 if(capsRequiringConfiguration.contains(_capLowercase)) {
1132 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1133 // so we should negotiate it separately from all other capabilities. Otherwise new
1134 // capabilities will be requested while still configuring the previous one.
1135 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1136 _capsQueuedIndividual.append(_capLowercase);
1139 // The capability doesn't need any special configuration, so it should be safe to try
1140 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1142 if (!_capsQueuedBundled.contains(_capLowercase)) {
1143 _capsQueuedBundled.append(_capLowercase);
1148 QString CoreNetwork::takeQueuedCaps()
1150 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1152 _capsQueuedLastBundle.clear();
1154 // First, negotiate all the standalone capabilities that require additional configuration.
1155 if (!_capsQueuedIndividual.empty()) {
1156 // We have an individual capability available. Take the first and pass it back.
1157 return _capsQueuedIndividual.takeFirst();
1158 } else if (!_capsQueuedBundled.empty()) {
1159 // We have capabilities available that can be grouped. Try to fit in as many as within the
1161 // See CoreNetwork::maxCapRequestLength
1163 // Response must have at least one capability regardless of max length for anything to
1165 QString capBundle = _capsQueuedBundled.takeFirst();
1166 QString nextCap("");
1167 while (!_capsQueuedBundled.empty()) {
1168 // As long as capabilities remain, get the next...
1169 nextCap = _capsQueuedBundled.first();
1170 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1171 // [capability + 1 for a space + this new capability] fit within length limits
1172 // Add it to formatted list
1173 capBundle.append(" " + nextCap);
1174 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1175 _capsQueuedLastBundle.append(nextCap);
1176 // Then remove it from the queue
1177 _capsQueuedBundled.removeFirst();
1179 // We've reached the length limit for a single capability request, stop adding more
1183 // Return this space-separated set of capabilities, removing any extra spaces
1184 return capBundle.trimmed();
1186 // No capabilities left to negotiate, return an empty string.
1191 void CoreNetwork::retryCapsIndividually()
1193 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1194 // denied, try each capability individually.
1195 if (_capsQueuedLastBundle.empty()) {
1196 // No most recently tried capability set, just return.
1198 // Note: there's little point in retrying individually requested caps during negotiation.
1199 // We know the individual capability was the one that failed, and it's not likely it'll
1200 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1201 // handling capability removal and addition.
1204 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1205 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1206 // keeping track of which halves of the group fail, dividing the set each time.
1208 // Add most recently tried capability set to individual list, re-requesting them one at a time
1209 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1210 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1211 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1212 tr("Could not negotiate some capabilities, retrying individually (%1)...")
1213 .arg(_capsQueuedLastBundle.join(", ")));
1214 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1215 // need to remove them here.
1216 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1218 _capsQueuedLastBundle.clear();
1221 void CoreNetwork::beginCapNegotiation()
1223 // Don't begin negotiation if no capabilities are queued to request
1224 if (!capNegotiationInProgress()) {
1225 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1226 // normal connection.
1227 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1228 endCapNegotiation();
1232 _capNegotiationActive = true;
1233 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1234 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1236 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1237 // comma separator between the two if needed (both individual and bundled caps exist).
1238 QString queuedCapsDisplay =
1239 _capsQueuedIndividual.join(", ")
1240 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1241 + _capsQueuedBundled.join(", ");
1242 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1243 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1248 void CoreNetwork::sendNextCap()
1250 if (capNegotiationInProgress()) {
1251 // Request the next set of capabilities and remove them from the list
1252 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1254 // No pending desired capabilities, capability negotiation finished
1255 // If SASL requested but not available, print a warning
1256 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1257 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1258 tr("SASL authentication currently not supported by server"));
1260 if (_capNegotiationActive) {
1261 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1262 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1263 _capNegotiationActive = false;
1266 endCapNegotiation();
1270 void CoreNetwork::endCapNegotiation()
1272 // If nick registration is already complete, CAP END is not required
1273 if (!_capInitialNegotiationEnded) {
1274 putRawLine(serverEncode(QString("CAP END")));
1275 _capInitialNegotiationEnded = true;
1279 /******** AutoWHO ********/
1281 void CoreNetwork::startAutoWhoCycle()
1283 if (!_autoWhoQueue.isEmpty()) {
1284 _autoWhoCycleTimer.stop();
1287 _autoWhoQueue = channels();
1290 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1292 // Prepend so these new channels/nicks are the first to be checked
1293 // Don't allow duplicates
1294 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1295 _autoWhoQueue.prepend(channelOrNick.toLower());
1297 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1298 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1299 setAutoWhoEnabled(true);
1304 void CoreNetwork::setAutoWhoDelay(int delay)
1306 _autoWhoTimer.setInterval(delay * 1000);
1310 void CoreNetwork::setAutoWhoInterval(int interval)
1312 _autoWhoCycleTimer.setInterval(interval * 1000);
1316 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1318 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1319 _autoWhoTimer.start();
1320 else if (!enabled) {
1321 _autoWhoTimer.stop();
1322 _autoWhoCycleTimer.stop();
1327 void CoreNetwork::sendAutoWho()
1329 // Don't send autowho if there are still some pending
1330 if (_autoWhoPending.count())
1333 while (!_autoWhoQueue.isEmpty()) {
1334 QString chanOrNick = _autoWhoQueue.takeFirst();
1335 // Check if it's a known channel or nick
1336 IrcChannel *ircchan = ircChannel(chanOrNick);
1337 IrcUser *ircuser = ircUser(chanOrNick);
1339 // Apply channel limiting rules
1340 // If using away-notify, don't impose channel size limits in order to capture away
1341 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1342 if (networkConfig()->autoWhoNickLimit() > 0
1343 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1344 && !capEnabled(IrcCap::AWAY_NOTIFY))
1346 _autoWhoPending[chanOrNick.toLower()]++;
1347 } else if (ircuser) {
1348 // Checking a nick, add it to the pending list
1349 _autoWhoPending[ircuser->nick().toLower()]++;
1351 // Not a channel or a nick, skip it
1352 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1355 if (supports("WHOX")) {
1356 // Use WHO extended to poll away users and/or user accounts
1357 // See http://faerion.sourceforge.net/doc/irc/whox.var
1358 // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1359 putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1360 .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1362 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1367 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1368 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1369 // Timer was stopped, means a new cycle is due immediately
1370 // Don't run a new cycle if using away-notify; server will notify as appropriate
1371 _autoWhoCycleTimer.start();
1372 startAutoWhoCycle();
1373 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1374 // Don't run another who cycle if away-notify is enabled
1375 _autoWhoCycleTimer.stop();
1381 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1383 Server server = usedServer();
1384 if (server.sslVerify) {
1385 // Treat the SSL error as a hard error
1386 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1387 "since verification is required");
1388 if (!sslErrors.empty()) {
1389 // Add the error reason if known
1390 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1392 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1394 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1395 // validity, network trouble, etc.
1396 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1398 // Treat the SSL error as a warning, continue to connect anyways
1399 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1400 "since verification is not required");
1401 if (!sslErrors.empty()) {
1402 // Add the error reason if known
1403 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1405 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1407 // Proceed with the connection
1408 socket.ignoreSslErrors();
1415 void CoreNetwork::checkTokenBucket()
1417 if (_skipMessageRates) {
1418 if (_msgQueue.size() == 0) {
1419 // Message queue emptied; stop the timer and bail out
1420 _tokenBucketTimer.stop();
1423 // Otherwise, we're emptying the queue, continue on as normal
1426 // Process whatever messages are pending
1427 fillBucketAndProcessQueue();
1431 void CoreNetwork::fillBucketAndProcessQueue()
1433 // If there's less tokens than burst size, refill the token bucket by 1
1434 if (_tokenBucket < _burstSize) {
1438 // As long as there's tokens available and messages remaining, sending messages from the queue
1439 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1440 writeToSocket(_msgQueue.takeFirst());
1445 void CoreNetwork::writeToSocket(const QByteArray &data)
1448 socket.write("\r\n");
1449 if (!_skipMessageRates) {
1450 // Only subtract from the token bucket if message rate limiting is enabled
1456 Network::Server CoreNetwork::usedServer() const
1458 if (_lastUsedServerIndex < serverList().count())
1459 return serverList()[_lastUsedServerIndex];
1461 if (!serverList().isEmpty())
1462 return serverList()[0];
1464 return Network::Server();
1468 void CoreNetwork::requestConnect() const
1470 if (connectionState() != Disconnected) {
1471 qWarning() << "Requesting connect while already being connected!";
1474 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1478 void CoreNetwork::requestDisconnect() const
1480 if (connectionState() == Disconnected) {
1481 qWarning() << "Requesting disconnect while not being connected!";
1484 userInputHandler()->handleQuit(BufferInfo(), QString());
1488 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1490 Network::Server currentServer = usedServer();
1491 setNetworkInfo(info);
1492 Core::updateNetwork(coreSession()->user(), info);
1494 // the order of the servers might have changed,
1495 // so we try to find the previously used server
1496 _lastUsedServerIndex = 0;
1497 for (int i = 0; i < serverList().count(); i++) {
1498 Network::Server server = serverList()[i];
1499 if (server.host == currentServer.host && server.port == currentServer.port) {
1500 _lastUsedServerIndex = i;
1507 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1509 QString wrkMsg(message);
1510 QList<QList<QByteArray>> msgsToSend;
1512 // do while (wrkMsg.size() > 0)
1514 // First, check to see if the whole message can be sent at once. The
1515 // cmdGenerator function is passed in by the caller and is used to encode
1516 // and encrypt (if applicable) the message, since different callers might
1517 // want to use different encoding or encode different values.
1518 int splitPos = wrkMsg.size();
1519 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1520 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1522 if (initialOverrun) {
1523 // If the message was too long to be sent, first try splitting it along
1524 // word boundaries with QTextBoundaryFinder.
1525 QString splitMsg(wrkMsg);
1526 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1527 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1528 QList<QByteArray> splitMsgEnc;
1529 int overrun = initialOverrun;
1532 splitPos = qtbf.toPreviousBoundary();
1534 // splitPos==-1 means the QTBF couldn't find a split point at all and
1535 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1536 // the string. Neither one of these works for us.
1538 // If a split point could be found, split the message there, calculate the
1539 // overrun, and continue with the loop.
1540 splitMsg = splitMsg.left(splitPos);
1541 splitMsgEnc = cmdGenerator(splitMsg);
1542 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1545 // If a split point could not be found (the beginning of the message
1546 // is reached without finding a split point short enough to send) and we
1547 // are still in Word mode, switch to Grapheme mode. We also need to restore
1548 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1549 // the previous attempt to find a split point.
1550 if (qtbf.type() == QTextBoundaryFinder::Word) {
1552 splitPos = splitMsg.size();
1553 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1554 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1555 qtbf = graphemeQtbf;
1558 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1559 // This should never happen, but it should be handled anyway.
1560 qWarning() << "Unexpected failure to split message!";
1566 // Once a message of sendable length has been found, remove it from the wrkMsg and
1567 // add it to the list of messages to be sent.
1568 wrkMsg.remove(0, splitPos);
1569 msgsToSend.append(splitMsgEnc);
1572 // If the entire remaining message is short enough to be sent all at once, remove
1573 // it from the wrkMsg and add it to the list of messages to be sent.
1574 wrkMsg.remove(0, splitPos);
1575 msgsToSend.append(initialSplitMsgEnc);
1577 } while (wrkMsg.size() > 0);