1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
67 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
68 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
69 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
70 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
72 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
73 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
74 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
75 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(checkTokenBucket()));
77 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
78 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
79 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
80 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
82 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
83 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
85 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
87 // Custom rate limiting
88 // These react to the user changing settings in the client
89 connect(this, SIGNAL(useCustomMessageRateSet(bool)), SLOT(updateRateLimiting()));
90 connect(this, SIGNAL(messageRateBurstSizeSet(quint32)), SLOT(updateRateLimiting()));
91 connect(this, SIGNAL(messageRateDelaySet(quint32)), SLOT(updateRateLimiting()));
92 connect(this, SIGNAL(unlimitedMessageRateSet(bool)), SLOT(updateRateLimiting()));
94 // IRCv3 capability handling
95 // These react to CAP messages from the server
96 connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
97 connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
98 connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
100 if (Quassel::isOptionSet("oidentd")) {
101 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
102 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
107 CoreNetwork::~CoreNetwork()
109 // Request a proper disconnect, but don't count as user-requested disconnect
110 if (socketConnected()) {
111 // Only try if the socket's fully connected (not initializing or disconnecting).
112 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
113 // shown even if other messages are queued.
114 disconnectFromIrc(false, QString(), false, true);
115 // Process the putCmd events that trigger the quit. Without this, shutting down the core
116 // results in abrubtly closing the socket rather than sending the QUIT as expected.
117 QCoreApplication::processEvents();
118 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
119 if (!forceDisconnect()) {
120 qWarning() << "Timed out quitting network" << networkName() <<
121 "(user ID " << userId() << ")";
124 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
125 delete _userInputHandler;
129 bool CoreNetwork::forceDisconnect(int msecs)
131 if (socket.state() == QAbstractSocket::UnconnectedState) {
132 // Socket already disconnected.
135 // Request a socket-level disconnect if not already happened
136 socket.disconnectFromHost();
137 // Return the result of waiting for disconnect; true if successful, otherwise false
138 return socket.waitForDisconnected(msecs);
142 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
144 if (!bufferName.isEmpty()) {
145 IrcChannel *channel = ircChannel(bufferName);
147 return channel->decodeString(string);
149 return decodeString(string);
153 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
155 IrcUser *user = ircUser(userNick);
157 return user->decodeString(string);
158 return decodeString(string);
162 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
164 if (!bufferName.isEmpty()) {
165 IrcChannel *channel = ircChannel(bufferName);
167 return channel->encodeString(string);
169 return encodeString(string);
173 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
175 IrcUser *user = ircUser(userNick);
177 return user->encodeString(string);
178 return encodeString(string);
182 void CoreNetwork::connectToIrc(bool reconnecting)
184 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
185 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
186 if (unlimitedReconnectRetries())
187 _autoReconnectCount = -1;
189 _autoReconnectCount = autoReconnectRetries();
191 if (serverList().isEmpty()) {
192 qWarning() << "Server list empty, ignoring connect request!";
195 CoreIdentity *identity = identityPtr();
197 qWarning() << "Invalid identity configures, ignoring connect request!";
201 // cleaning up old quit reason
204 // Reset capability negotiation tracking, also handling server changes during reconnect
205 _capsQueuedIndividual.clear();
206 _capsQueuedBundled.clear();
208 _capNegotiationActive = false;
209 _capInitialNegotiationEnded = false;
211 // use a random server?
212 if (useRandomServer()) {
213 _lastUsedServerIndex = qrand() % serverList().size();
215 else if (_previousConnectionAttemptFailed) {
216 // cycle to next server if previous connection attempt failed
217 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
218 if (++_lastUsedServerIndex >= serverList().size()) {
219 _lastUsedServerIndex = 0;
222 _previousConnectionAttemptFailed = false;
224 Server server = usedServer();
225 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
226 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
228 if (server.useProxy) {
229 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
230 socket.setProxy(proxy);
233 socket.setProxy(QNetworkProxy::NoProxy);
238 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
239 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
240 QHostInfo::fromName(server.host);
244 CoreIdentity *identity = identityPtr();
246 socket.setLocalCertificate(identity->sslCert());
247 socket.setPrivateKey(identity->sslKey());
249 socket.connectToHostEncrypted(server.host, server.port);
252 socket.connectToHost(server.host, server.port);
255 socket.connectToHost(server.host, server.port);
260 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
263 // Disconnecting from the network, should expect a socket close or error
264 _disconnectExpected = true;
265 _quitRequested = requested; // see socketDisconnected();
266 if (!withReconnect) {
267 _autoReconnectTimer.stop();
268 _autoReconnectCount = 0; // prohibiting auto reconnect
270 disablePingTimeout();
277 awayMsg = me_->awayMessage();
278 Core::setAwayMessage(userId(), networkId(), awayMsg);
281 if (reason.isEmpty() && identityPtr())
282 _quitReason = identityPtr()->quitReason();
284 _quitReason = reason;
286 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
287 if (socket.state() == QAbstractSocket::UnconnectedState) {
288 socketDisconnected();
290 if (socket.state() == QAbstractSocket::ConnectedState) {
291 userInputHandler()->issueQuit(_quitReason, forceImmediate);
295 if (requested || withReconnect) {
296 // the irc server has 10 seconds to close the socket
297 _socketCloseTimer.start(10000);
303 void CoreNetwork::userInput(BufferInfo buf, QString msg)
305 userInputHandler()->handleUserInput(buf, msg);
309 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
311 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.size() == 0)) {
312 // If there's tokens remaining, ...
313 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
314 // Send the message now.
317 // Otherwise, queue the message for later
319 // Jump to the start, skipping other messages
320 _msgQueue.prepend(s);
322 // Add to back, waiting in order
329 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
333 if (!prefix.isEmpty())
334 msg += ":" + prefix + " ";
335 msg += cmd.toUpper().toLatin1();
337 for (int i = 0; i < params.size(); i++) {
340 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
346 putRawLine(msg, prepend);
350 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
352 QListIterator<QList<QByteArray>> i(params);
353 while (i.hasNext()) {
354 QList<QByteArray> msg = i.next();
355 putCmd(cmd, msg, prefix, prependAll);
360 void CoreNetwork::setChannelJoined(const QString &channel)
362 queueAutoWhoOneshot(channel); // check this new channel first
364 Core::setChannelPersistent(userId(), networkId(), channel, true);
365 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
369 void CoreNetwork::setChannelParted(const QString &channel)
371 removeChannelKey(channel);
372 _autoWhoQueue.removeAll(channel.toLower());
373 _autoWhoPending.remove(channel.toLower());
375 Core::setChannelPersistent(userId(), networkId(), channel, false);
379 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
382 removeChannelKey(channel);
385 _channelKeys[channel.toLower()] = key;
390 void CoreNetwork::removeChannelKey(const QString &channel)
392 _channelKeys.remove(channel.toLower());
397 Cipher *CoreNetwork::cipher(const QString &target)
399 if (target.isEmpty())
402 if (!Cipher::neededFeaturesAvailable())
405 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
407 return channel->cipher();
409 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
411 return user->cipher();
412 } else if (!isChannelName(target)) {
413 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
419 QByteArray CoreNetwork::cipherKey(const QString &target) const
421 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
423 return c->cipher()->key();
425 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
427 return u->cipher()->key();
433 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
435 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
437 c->setEncrypted(c->cipher()->setKey(key));
441 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
442 if (!u && !isChannelName(target))
443 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
446 u->setEncrypted(u->cipher()->setKey(key));
452 bool CoreNetwork::cipherUsesCBC(const QString &target)
454 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
456 return c->cipher()->usesCBC();
457 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
459 return u->cipher()->usesCBC();
463 #endif /* HAVE_QCA2 */
465 bool CoreNetwork::setAutoWhoDone(const QString &channel)
467 QString chan = channel.toLower();
468 if (_autoWhoPending.value(chan, 0) <= 0)
470 if (--_autoWhoPending[chan] <= 0)
471 _autoWhoPending.remove(chan);
476 void CoreNetwork::setMyNick(const QString &mynick)
478 Network::setMyNick(mynick);
479 if (connectionState() == Network::Initializing)
480 networkInitialized();
484 void CoreNetwork::socketHasData()
486 while (socket.canReadLine()) {
487 QByteArray s = socket.readLine();
488 if (s.endsWith("\r\n"))
490 else if (s.endsWith("\n"))
492 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
493 event->setTimestamp(QDateTime::currentDateTimeUtc());
494 emit newEvent(event);
499 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
501 // Ignore socket closed errors if expected
502 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
506 _previousConnectionAttemptFailed = true;
507 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
508 emit connectionError(socket.errorString());
509 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
510 emitConnectionError(socket.errorString());
511 if (socket.state() < QAbstractSocket::ConnectedState) {
512 socketDisconnected();
517 void CoreNetwork::socketInitialized()
519 CoreIdentity *identity = identityPtr();
521 qCritical() << "Identity invalid!";
526 Server server = usedServer();
529 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
530 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
531 if (!server.useSsl || !socket.isEncrypted()) {
532 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
535 if (server.useSsl && !socket.isEncrypted()) {
536 // We'll finish setup once we're encrypted, and called again
540 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
543 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
545 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
546 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
547 // force flag to apply user preferences. When making changes, ensure that this still happens!
548 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
549 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
551 updateRateLimiting(true);
552 // Fill up the token bucket as we're connecting from scratch
555 // Request capabilities as per IRCv3.2 specifications
556 // Older servers should ignore this; newer servers won't downgrade to RFC1459
557 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
558 putRawLine(serverEncode(QString("CAP LS 302")));
560 if (!server.password.isEmpty()) {
561 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
564 if (identity->nicks().isEmpty()) {
566 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
569 nick = identity->nicks()[0];
571 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
572 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
576 void CoreNetwork::socketDisconnected()
578 disablePingTimeout();
581 _autoWhoCycleTimer.stop();
582 _autoWhoTimer.stop();
583 _autoWhoQueue.clear();
584 _autoWhoPending.clear();
586 _socketCloseTimer.stop();
588 _tokenBucketTimer.stop();
592 foreach(QString channel, me_->channels())
593 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
597 emit disconnected(networkId());
598 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
599 // Reset disconnect expectations
600 _disconnectExpected = false;
601 if (_quitRequested) {
602 _quitRequested = false;
603 setConnectionState(Network::Disconnected);
604 Core::setNetworkConnected(userId(), networkId(), false);
606 else if (_autoReconnectCount != 0) {
607 setConnectionState(Network::Reconnecting);
608 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
609 doAutoReconnect(); // first try is immediate
611 _autoReconnectTimer.start();
616 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
618 Network::ConnectionState state;
619 switch (socketState) {
620 case QAbstractSocket::UnconnectedState:
621 state = Network::Disconnected;
622 socketDisconnected();
624 case QAbstractSocket::HostLookupState:
625 case QAbstractSocket::ConnectingState:
626 state = Network::Connecting;
628 case QAbstractSocket::ConnectedState:
629 state = Network::Initializing;
631 case QAbstractSocket::ClosingState:
632 state = Network::Disconnecting;
635 state = Network::Disconnected;
637 setConnectionState(state);
641 void CoreNetwork::networkInitialized()
643 setConnectionState(Network::Initialized);
645 _disconnectExpected = false;
646 _quitRequested = false;
648 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
649 // flag used for initial registration and capability negotiation.
650 updateRateLimiting();
652 if (useAutoReconnect()) {
654 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
657 // restore away state
658 QString awayMsg = Core::awayMessage(userId(), networkId());
659 if (!awayMsg.isEmpty()) {
660 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
661 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
662 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
669 if (networkConfig()->autoWhoEnabled()) {
670 _autoWhoCycleTimer.start();
671 _autoWhoTimer.start();
672 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
675 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
676 Core::setNetworkConnected(userId(), networkId(), true);
680 void CoreNetwork::sendPerform()
682 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
685 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
686 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
689 // restore old user modes if server default mode is set.
692 if (!me_->userModes().isEmpty()) {
696 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
697 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
702 foreach(QString line, perform()) {
703 if (!line.isEmpty()) userInput(statusBuf, line);
706 // rejoin channels we've been in
707 if (rejoinChannels()) {
708 QStringList channels, keys;
709 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
710 QString key = channelKey(chan);
711 if (!key.isEmpty()) {
712 channels.prepend(chan);
716 channels.append(chan);
719 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
720 if (!joinString.isEmpty())
721 userInputHandler()->handleJoin(statusBuf, joinString);
726 void CoreNetwork::restoreUserModes()
731 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
732 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
734 QString modesDelta = Core::userModes(userId(), networkId());
735 QString currentModes = me_->userModes();
737 QString addModes, removeModes;
738 if (modesDelta.contains('-')) {
739 addModes = modesDelta.section('-', 0, 0);
740 removeModes = modesDelta.section('-', 1);
743 addModes = modesDelta;
746 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
747 if (currentModes.isEmpty())
748 removeModes = QString();
750 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
752 if (addModes.isEmpty() && removeModes.isEmpty())
755 if (!addModes.isEmpty())
756 addModes = '+' + addModes;
757 if (!removeModes.isEmpty())
758 removeModes = '-' + removeModes;
760 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
761 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
765 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
771 for (int i = 0; i < requestedModes.length(); i++) {
772 if (requestedModes[i] == '+') {
776 if (requestedModes[i] == '-') {
781 addModes += requestedModes[i];
784 removeModes += requestedModes[i];
788 QString addModesOld = _requestedUserModes.section('-', 0, 0);
789 QString removeModesOld = _requestedUserModes.section('-', 1);
791 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
792 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
793 addModes += addModesOld;
795 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
796 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
797 removeModes += removeModesOld;
799 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
803 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
805 QString persistentUserModes = Core::userModes(userId(), networkId());
807 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
808 QString requestedRemove = _requestedUserModes.section('-', 1);
810 QString persistentAdd, persistentRemove;
811 if (persistentUserModes.contains('-')) {
812 persistentAdd = persistentUserModes.section('-', 0, 0);
813 persistentRemove = persistentUserModes.section('-', 1);
816 persistentAdd = persistentUserModes;
819 // remove modes we didn't issue
820 if (requestedAdd.isEmpty())
821 addModes = QString();
823 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
825 if (requestedRemove.isEmpty())
826 removeModes = QString();
828 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
831 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
832 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
835 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
836 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
838 // update issued mode list
839 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
840 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
841 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
843 persistentAdd += addModes;
844 persistentRemove += removeModes;
845 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
849 void CoreNetwork::resetPersistentModes()
851 _requestedUserModes = QString('-');
852 Core::setUserModes(userId(), networkId(), QString());
856 void CoreNetwork::setUseAutoReconnect(bool use)
858 Network::setUseAutoReconnect(use);
860 _autoReconnectTimer.stop();
864 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
866 Network::setAutoReconnectInterval(interval);
867 _autoReconnectTimer.setInterval(interval * 1000);
871 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
873 Network::setAutoReconnectRetries(retries);
874 if (_autoReconnectCount != 0) {
875 if (unlimitedReconnectRetries())
876 _autoReconnectCount = -1;
878 _autoReconnectCount = autoReconnectRetries();
883 void CoreNetwork::doAutoReconnect()
885 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
886 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
889 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
890 _autoReconnectCount--; // -2 means we delay the next reconnect
895 void CoreNetwork::sendPing()
897 uint now = QDateTime::currentDateTime().toTime_t();
898 if (_pingCount != 0) {
899 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
900 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
902 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
903 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
904 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
905 // and unable to even handle a ping answer. So we ignore those misses.
906 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
911 // Don't send pings until the network is initialized
913 userInputHandler()->handlePing(BufferInfo(), QString());
918 void CoreNetwork::enablePingTimeout(bool enable)
921 disablePingTimeout();
924 if (networkConfig()->pingTimeoutEnabled())
930 void CoreNetwork::disablePingTimeout()
938 void CoreNetwork::setPingInterval(int interval)
940 _pingTimer.setInterval(interval * 1000);
944 /******** Custom Rate Limiting ********/
946 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
948 // Verify and apply custom rate limiting options, always resetting the delay and burst size
949 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
950 // this may be called while connected to a server.
952 if (useCustomMessageRate() || forceUnlimited) {
953 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
955 _messageDelay = messageRateDelay();
957 _burstSize = messageRateBurstSize();
958 if (_burstSize < 1) {
959 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
961 // Can't go slower than one message at a time
965 if (_tokenBucket > _burstSize) {
966 // Don't let the token bucket exceed the maximum
967 _tokenBucket = _burstSize;
968 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
969 // changing the rate-limit settings while connected to a server will incorrectly reset
973 // Toggle the timer according to whether or not rate limiting is enabled
974 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
975 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
976 // Override user preferences if called with force unlimited, only used during connect.
977 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
978 if (_skipMessageRates) {
979 // If the message queue already contains messages, they need sent before disabling the
980 // timer. Set the timer to a rapid pace and let it disable itself.
981 if (_msgQueue.size() > 0) {
982 qDebug() << "Outgoing message queue contains messages while disabling rate "
983 "limiting. Sending remaining queued messages...";
984 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
985 // so nothing should cause this to block.. in theory. However, don't directly call
986 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
988 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
989 // Hesitant to change it without a wide variety of situations to verify behavior.
990 _tokenBucketTimer.start(100);
992 // No rate limiting, disable the timer
993 _tokenBucketTimer.stop();
996 // Rate limiting enabled, enable the timer
997 _tokenBucketTimer.start(_messageDelay);
1000 // Custom message rates disabled. Go for the default.
1002 _skipMessageRates = false; // Enable rate-limiting by default
1003 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1004 _burstSize = 5; // 5 messages at once
1005 if (_tokenBucket > _burstSize) {
1006 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1008 _tokenBucket = _burstSize;
1009 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1010 // changing the rate-limit settings while connected to a server will incorrectly reset
1011 // the token bucket.
1013 // Rate limiting enabled, enable the timer
1014 _tokenBucketTimer.start(_messageDelay);
1018 void CoreNetwork::resetTokenBucket()
1020 // Fill up the token bucket to the maximum
1021 _tokenBucket = _burstSize;
1025 /******** IRCv3 Capability Negotiation ********/
1027 void CoreNetwork::serverCapAdded(const QString &capability)
1029 // Check if it's a known capability; if so, add it to the list
1030 // Handle special cases first
1031 if (capability == IrcCap::SASL) {
1032 // Only request SASL if it's enabled
1033 if (networkInfo().useSasl)
1034 queueCap(capability);
1035 } else if (IrcCap::knownCaps.contains(capability)) {
1036 // Handling for general known capabilities
1037 queueCap(capability);
1041 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1043 // This may be called multiple times in certain situations.
1045 // Handle core-side configuration
1046 if (capability == IrcCap::AWAY_NOTIFY) {
1047 // away-notify enabled, stop the autoWho timers, handle manually
1048 setAutoWhoEnabled(false);
1051 // Handle capabilities that require further messages sent to the IRC server
1052 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1053 if (capability == IrcCap::SASL) {
1054 // If SASL mechanisms specified, limit to what's accepted for authentication
1055 // if the current identity has a cert set, use SASL EXTERNAL
1058 if (!identityPtr()->sslCert().isNull()) {
1059 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1060 // EXTERNAL authentication supported, send request
1061 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1063 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1064 tr("SASL EXTERNAL authentication not supported"));
1069 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1070 // PLAIN authentication supported, send request
1071 // Only working with PLAIN atm, blowfish later
1072 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1074 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1075 tr("SASL PLAIN authentication not supported"));
1084 void CoreNetwork::serverCapRemoved(const QString &capability)
1086 // This may be called multiple times in certain situations.
1088 // Handle special cases here
1089 if (capability == IrcCap::AWAY_NOTIFY) {
1090 // away-notify disabled, enable autoWho according to configuration
1091 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1095 void CoreNetwork::queueCap(const QString &capability)
1097 // IRCv3 specs all use lowercase capability names
1098 QString _capLowercase = capability.toLower();
1100 if(capsRequiringConfiguration.contains(_capLowercase)) {
1101 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1102 // so we should negotiate it separately from all other capabilities. Otherwise new
1103 // capabilities will be requested while still configuring the previous one.
1104 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1105 _capsQueuedIndividual.append(_capLowercase);
1108 // The capability doesn't need any special configuration, so it should be safe to try
1109 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1111 if (!_capsQueuedBundled.contains(_capLowercase)) {
1112 _capsQueuedBundled.append(_capLowercase);
1117 QString CoreNetwork::takeQueuedCaps()
1119 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1121 _capsQueuedLastBundle.clear();
1123 // First, negotiate all the standalone capabilities that require additional configuration.
1124 if (!_capsQueuedIndividual.empty()) {
1125 // We have an individual capability available. Take the first and pass it back.
1126 return _capsQueuedIndividual.takeFirst();
1127 } else if (!_capsQueuedBundled.empty()) {
1128 // We have capabilities available that can be grouped. Try to fit in as many as within the
1130 // See CoreNetwork::maxCapRequestLength
1132 // Response must have at least one capability regardless of max length for anything to
1134 QString capBundle = _capsQueuedBundled.takeFirst();
1135 QString nextCap("");
1136 while (!_capsQueuedBundled.empty()) {
1137 // As long as capabilities remain, get the next...
1138 nextCap = _capsQueuedBundled.first();
1139 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1140 // [capability + 1 for a space + this new capability] fit within length limits
1141 // Add it to formatted list
1142 capBundle.append(" " + nextCap);
1143 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1144 _capsQueuedLastBundle.append(nextCap);
1145 // Then remove it from the queue
1146 _capsQueuedBundled.removeFirst();
1148 // We've reached the length limit for a single capability request, stop adding more
1152 // Return this space-separated set of capabilities, removing any extra spaces
1153 return capBundle.trimmed();
1155 // No capabilities left to negotiate, return an empty string.
1160 void CoreNetwork::retryCapsIndividually()
1162 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1163 // denied, try each capability individually.
1164 if (_capsQueuedLastBundle.empty()) {
1165 // No most recently tried capability set, just return.
1167 // Note: there's little point in retrying individually requested caps during negotiation.
1168 // We know the individual capability was the one that failed, and it's not likely it'll
1169 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1170 // handling capability removal and addition.
1173 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1174 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1175 // keeping track of which halves of the group fail, dividing the set each time.
1177 // Add most recently tried capability set to individual list, re-requesting them one at a time
1178 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1179 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1180 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1181 tr("Could not negotiate some capabilities, retrying individually (%1)...")
1182 .arg(_capsQueuedLastBundle.join(", ")));
1183 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1184 // need to remove them here.
1185 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1187 _capsQueuedLastBundle.clear();
1190 void CoreNetwork::beginCapNegotiation()
1192 // Don't begin negotiation if no capabilities are queued to request
1193 if (!capNegotiationInProgress()) {
1194 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1195 // normal connection.
1196 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1197 endCapNegotiation();
1201 _capNegotiationActive = true;
1202 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1203 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1205 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1206 // comma separator between the two if needed.
1207 QString queuedCapsDisplay =
1208 (!_capsQueuedIndividual.empty() ? _capsQueuedIndividual.join(", ") + ", " : "")
1209 + _capsQueuedBundled.join(", ");
1210 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1211 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1216 void CoreNetwork::sendNextCap()
1218 if (capNegotiationInProgress()) {
1219 // Request the next set of capabilities and remove them from the list
1220 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1222 // No pending desired capabilities, capability negotiation finished
1223 // If SASL requested but not available, print a warning
1224 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1225 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1226 tr("SASL authentication currently not supported by server"));
1228 if (_capNegotiationActive) {
1229 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1230 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1231 _capNegotiationActive = false;
1234 endCapNegotiation();
1238 void CoreNetwork::endCapNegotiation()
1240 // If nick registration is already complete, CAP END is not required
1241 if (!_capInitialNegotiationEnded) {
1242 putRawLine(serverEncode(QString("CAP END")));
1243 _capInitialNegotiationEnded = true;
1247 /******** AutoWHO ********/
1249 void CoreNetwork::startAutoWhoCycle()
1251 if (!_autoWhoQueue.isEmpty()) {
1252 _autoWhoCycleTimer.stop();
1255 _autoWhoQueue = channels();
1258 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1260 // Prepend so these new channels/nicks are the first to be checked
1261 // Don't allow duplicates
1262 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1263 _autoWhoQueue.prepend(channelOrNick.toLower());
1265 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1266 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1267 setAutoWhoEnabled(true);
1272 void CoreNetwork::setAutoWhoDelay(int delay)
1274 _autoWhoTimer.setInterval(delay * 1000);
1278 void CoreNetwork::setAutoWhoInterval(int interval)
1280 _autoWhoCycleTimer.setInterval(interval * 1000);
1284 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1286 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1287 _autoWhoTimer.start();
1288 else if (!enabled) {
1289 _autoWhoTimer.stop();
1290 _autoWhoCycleTimer.stop();
1295 void CoreNetwork::sendAutoWho()
1297 // Don't send autowho if there are still some pending
1298 if (_autoWhoPending.count())
1301 while (!_autoWhoQueue.isEmpty()) {
1302 QString chanOrNick = _autoWhoQueue.takeFirst();
1303 // Check if it's a known channel or nick
1304 IrcChannel *ircchan = ircChannel(chanOrNick);
1305 IrcUser *ircuser = ircUser(chanOrNick);
1307 // Apply channel limiting rules
1308 // If using away-notify, don't impose channel size limits in order to capture away
1309 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1310 if (networkConfig()->autoWhoNickLimit() > 0
1311 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1312 && !capEnabled(IrcCap::AWAY_NOTIFY))
1314 _autoWhoPending[chanOrNick.toLower()]++;
1315 } else if (ircuser) {
1316 // Checking a nick, add it to the pending list
1317 _autoWhoPending[ircuser->nick().toLower()]++;
1319 // Not a channel or a nick, skip it
1320 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1323 if (supports("WHOX")) {
1324 // Use WHO extended to poll away users and/or user accounts
1325 // See http://faerion.sourceforge.net/doc/irc/whox.var
1326 // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1327 putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1328 .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1330 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1335 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1336 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1337 // Timer was stopped, means a new cycle is due immediately
1338 // Don't run a new cycle if using away-notify; server will notify as appropriate
1339 _autoWhoCycleTimer.start();
1340 startAutoWhoCycle();
1341 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1342 // Don't run another who cycle if away-notify is enabled
1343 _autoWhoCycleTimer.stop();
1349 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1351 Server server = usedServer();
1352 if (server.sslVerify) {
1353 // Treat the SSL error as a hard error
1354 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1355 "since verification is required");
1356 if (!sslErrors.empty()) {
1357 // Add the error reason if known
1358 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1360 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1362 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1363 // validity, network trouble, etc.
1364 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1366 // Treat the SSL error as a warning, continue to connect anyways
1367 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1368 "since verification is not required");
1369 if (!sslErrors.empty()) {
1370 // Add the error reason if known
1371 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1373 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1375 // Proceed with the connection
1376 socket.ignoreSslErrors();
1383 void CoreNetwork::checkTokenBucket()
1385 if (_skipMessageRates) {
1386 if (_msgQueue.size() == 0) {
1387 // Message queue emptied; stop the timer and bail out
1388 _tokenBucketTimer.stop();
1391 // Otherwise, we're emptying the queue, continue on as normal
1394 // Process whatever messages are pending
1395 fillBucketAndProcessQueue();
1399 void CoreNetwork::fillBucketAndProcessQueue()
1401 // If there's less tokens than burst size, refill the token bucket by 1
1402 if (_tokenBucket < _burstSize) {
1406 // As long as there's tokens available and messages remaining, sending messages from the queue
1407 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1408 writeToSocket(_msgQueue.takeFirst());
1413 void CoreNetwork::writeToSocket(const QByteArray &data)
1416 socket.write("\r\n");
1417 if (!_skipMessageRates) {
1418 // Only subtract from the token bucket if message rate limiting is enabled
1424 Network::Server CoreNetwork::usedServer() const
1426 if (_lastUsedServerIndex < serverList().count())
1427 return serverList()[_lastUsedServerIndex];
1429 if (!serverList().isEmpty())
1430 return serverList()[0];
1432 return Network::Server();
1436 void CoreNetwork::requestConnect() const
1438 if (connectionState() != Disconnected) {
1439 qWarning() << "Requesting connect while already being connected!";
1442 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1446 void CoreNetwork::requestDisconnect() const
1448 if (connectionState() == Disconnected) {
1449 qWarning() << "Requesting disconnect while not being connected!";
1452 userInputHandler()->handleQuit(BufferInfo(), QString());
1456 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1458 Network::Server currentServer = usedServer();
1459 setNetworkInfo(info);
1460 Core::updateNetwork(coreSession()->user(), info);
1462 // the order of the servers might have changed,
1463 // so we try to find the previously used server
1464 _lastUsedServerIndex = 0;
1465 for (int i = 0; i < serverList().count(); i++) {
1466 Network::Server server = serverList()[i];
1467 if (server.host == currentServer.host && server.port == currentServer.port) {
1468 _lastUsedServerIndex = i;
1475 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1477 QString wrkMsg(message);
1478 QList<QList<QByteArray>> msgsToSend;
1480 // do while (wrkMsg.size() > 0)
1482 // First, check to see if the whole message can be sent at once. The
1483 // cmdGenerator function is passed in by the caller and is used to encode
1484 // and encrypt (if applicable) the message, since different callers might
1485 // want to use different encoding or encode different values.
1486 int splitPos = wrkMsg.size();
1487 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1488 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1490 if (initialOverrun) {
1491 // If the message was too long to be sent, first try splitting it along
1492 // word boundaries with QTextBoundaryFinder.
1493 QString splitMsg(wrkMsg);
1494 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1495 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1496 QList<QByteArray> splitMsgEnc;
1497 int overrun = initialOverrun;
1500 splitPos = qtbf.toPreviousBoundary();
1502 // splitPos==-1 means the QTBF couldn't find a split point at all and
1503 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1504 // the string. Neither one of these works for us.
1506 // If a split point could be found, split the message there, calculate the
1507 // overrun, and continue with the loop.
1508 splitMsg = splitMsg.left(splitPos);
1509 splitMsgEnc = cmdGenerator(splitMsg);
1510 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1513 // If a split point could not be found (the beginning of the message
1514 // is reached without finding a split point short enough to send) and we
1515 // are still in Word mode, switch to Grapheme mode. We also need to restore
1516 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1517 // the previous attempt to find a split point.
1518 if (qtbf.type() == QTextBoundaryFinder::Word) {
1520 splitPos = splitMsg.size();
1521 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1522 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1523 qtbf = graphemeQtbf;
1526 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1527 // This should never happen, but it should be handled anyway.
1528 qWarning() << "Unexpected failure to split message!";
1534 // Once a message of sendable length has been found, remove it from the wrkMsg and
1535 // add it to the list of messages to be sent.
1536 wrkMsg.remove(0, splitPos);
1537 msgsToSend.append(splitMsgEnc);
1540 // If the entire remaining message is short enough to be sent all at once, remove
1541 // it from the wrkMsg and add it to the list of messages to be sent.
1542 wrkMsg.remove(0, splitPos);
1543 msgsToSend.append(initialSplitMsgEnc);
1545 } while (wrkMsg.size() > 0);