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)));
112 CoreNetwork::~CoreNetwork()
114 // Request a proper disconnect, but don't count as user-requested disconnect
115 if (socketConnected()) {
116 // Only try if the socket's fully connected (not initializing or disconnecting).
117 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
118 // shown even if other messages are queued.
119 disconnectFromIrc(false, QString(), false, true);
120 // Process the putCmd events that trigger the quit. Without this, shutting down the core
121 // results in abrubtly closing the socket rather than sending the QUIT as expected.
122 QCoreApplication::processEvents();
123 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
124 if (!forceDisconnect()) {
125 qWarning() << "Timed out quitting network" << networkName() <<
126 "(user ID " << userId() << ")";
129 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
130 delete _userInputHandler;
134 bool CoreNetwork::forceDisconnect(int msecs)
136 if (socket.state() == QAbstractSocket::UnconnectedState) {
137 // Socket already disconnected.
140 // Request a socket-level disconnect if not already happened
141 socket.disconnectFromHost();
142 // Return the result of waiting for disconnect; true if successful, otherwise false
143 return socket.waitForDisconnected(msecs);
147 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
149 if (!bufferName.isEmpty()) {
150 IrcChannel *channel = ircChannel(bufferName);
152 return channel->decodeString(string);
154 return decodeString(string);
158 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
160 IrcUser *user = ircUser(userNick);
162 return user->decodeString(string);
163 return decodeString(string);
167 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
169 if (!bufferName.isEmpty()) {
170 IrcChannel *channel = ircChannel(bufferName);
172 return channel->encodeString(string);
174 return encodeString(string);
178 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
180 IrcUser *user = ircUser(userNick);
182 return user->encodeString(string);
183 return encodeString(string);
187 void CoreNetwork::connectToIrc(bool reconnecting)
189 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
190 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
191 if (unlimitedReconnectRetries())
192 _autoReconnectCount = -1;
194 _autoReconnectCount = autoReconnectRetries();
196 if (serverList().isEmpty()) {
197 qWarning() << "Server list empty, ignoring connect request!";
200 CoreIdentity *identity = identityPtr();
202 qWarning() << "Invalid identity configures, ignoring connect request!";
206 // cleaning up old quit reason
209 // Reset capability negotiation tracking, also handling server changes during reconnect
210 _capsQueuedIndividual.clear();
211 _capsQueuedBundled.clear();
213 _capNegotiationActive = false;
214 _capInitialNegotiationEnded = false;
216 // use a random server?
217 if (useRandomServer()) {
218 _lastUsedServerIndex = qrand() % serverList().size();
220 else if (_previousConnectionAttemptFailed) {
221 // cycle to next server if previous connection attempt failed
222 _previousConnectionAttemptFailed = false;
223 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
224 if (++_lastUsedServerIndex >= serverList().size()) {
225 _lastUsedServerIndex = 0;
229 // Start out with the top server in the list
230 _lastUsedServerIndex = 0;
233 Server server = usedServer();
234 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
235 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
237 if (server.useProxy) {
238 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
239 socket.setProxy(proxy);
242 socket.setProxy(QNetworkProxy::NoProxy);
247 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
248 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
249 if (! server.useProxy) {
250 //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
251 //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
252 QHostInfo::fromName(server.host);
256 CoreIdentity *identity = identityPtr();
258 socket.setLocalCertificate(identity->sslCert());
259 socket.setPrivateKey(identity->sslKey());
261 socket.connectToHostEncrypted(server.host, server.port);
264 socket.connectToHost(server.host, server.port);
267 socket.connectToHost(server.host, server.port);
272 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
275 // Disconnecting from the network, should expect a socket close or error
276 _disconnectExpected = true;
277 _quitRequested = requested; // see socketDisconnected();
278 if (!withReconnect) {
279 _autoReconnectTimer.stop();
280 _autoReconnectCount = 0; // prohibiting auto reconnect
282 disablePingTimeout();
289 awayMsg = me_->awayMessage();
290 Core::setAwayMessage(userId(), networkId(), awayMsg);
293 if (reason.isEmpty() && identityPtr())
294 _quitReason = identityPtr()->quitReason();
296 _quitReason = reason;
298 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
299 if (socket.state() == QAbstractSocket::UnconnectedState) {
300 socketDisconnected();
302 if (socket.state() == QAbstractSocket::ConnectedState) {
303 userInputHandler()->issueQuit(_quitReason, forceImmediate);
307 if (requested || withReconnect) {
308 // the irc server has 10 seconds to close the socket
309 _socketCloseTimer.start(10000);
315 void CoreNetwork::userInput(BufferInfo buf, QString msg)
317 userInputHandler()->handleUserInput(buf, msg);
321 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
323 if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.size() == 0)) {
324 // If there's tokens remaining, ...
325 // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
326 // Send the message now.
329 // Otherwise, queue the message for later
331 // Jump to the start, skipping other messages
332 _msgQueue.prepend(s);
334 // Add to back, waiting in order
341 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
345 if (!prefix.isEmpty())
346 msg += ":" + prefix + " ";
347 msg += cmd.toUpper().toLatin1();
349 for (int i = 0; i < params.size(); i++) {
352 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
358 putRawLine(msg, prepend);
362 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
364 QListIterator<QList<QByteArray>> i(params);
365 while (i.hasNext()) {
366 QList<QByteArray> msg = i.next();
367 putCmd(cmd, msg, prefix, prependAll);
372 void CoreNetwork::setChannelJoined(const QString &channel)
374 queueAutoWhoOneshot(channel); // check this new channel first
376 Core::setChannelPersistent(userId(), networkId(), channel, true);
377 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
381 void CoreNetwork::setChannelParted(const QString &channel)
383 removeChannelKey(channel);
384 _autoWhoQueue.removeAll(channel.toLower());
385 _autoWhoPending.remove(channel.toLower());
387 Core::setChannelPersistent(userId(), networkId(), channel, false);
391 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
394 removeChannelKey(channel);
397 _channelKeys[channel.toLower()] = key;
402 void CoreNetwork::removeChannelKey(const QString &channel)
404 _channelKeys.remove(channel.toLower());
409 Cipher *CoreNetwork::cipher(const QString &target)
411 if (target.isEmpty())
414 if (!Cipher::neededFeaturesAvailable())
417 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
419 return channel->cipher();
421 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
423 return user->cipher();
424 } else if (!isChannelName(target)) {
425 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
431 QByteArray CoreNetwork::cipherKey(const QString &target) const
433 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
435 return c->cipher()->key();
437 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
439 return u->cipher()->key();
445 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
447 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
449 c->setEncrypted(c->cipher()->setKey(key));
450 coreSession()->setBufferCipher(networkId(), target, key);
454 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
455 if (!u && !isChannelName(target))
456 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
459 u->setEncrypted(u->cipher()->setKey(key));
460 coreSession()->setBufferCipher(networkId(), target, key);
466 bool CoreNetwork::cipherUsesCBC(const QString &target)
468 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
470 return c->cipher()->usesCBC();
471 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
473 return u->cipher()->usesCBC();
477 #endif /* HAVE_QCA2 */
479 bool CoreNetwork::setAutoWhoDone(const QString &channel)
481 QString chan = channel.toLower();
482 if (_autoWhoPending.value(chan, 0) <= 0)
484 if (--_autoWhoPending[chan] <= 0)
485 _autoWhoPending.remove(chan);
490 void CoreNetwork::setMyNick(const QString &mynick)
492 Network::setMyNick(mynick);
493 if (connectionState() == Network::Initializing)
494 networkInitialized();
498 void CoreNetwork::socketHasData()
500 while (socket.canReadLine()) {
501 QByteArray s = socket.readLine();
502 if (s.endsWith("\r\n"))
504 else if (s.endsWith("\n"))
506 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
507 event->setTimestamp(QDateTime::currentDateTimeUtc());
508 emit newEvent(event);
513 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
515 // Ignore socket closed errors if expected
516 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
520 _previousConnectionAttemptFailed = true;
521 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
522 emit connectionError(socket.errorString());
523 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
524 emitConnectionError(socket.errorString());
525 if (socket.state() < QAbstractSocket::ConnectedState) {
526 socketDisconnected();
531 void CoreNetwork::socketInitialized()
533 CoreIdentity *identity = identityPtr();
535 qCritical() << "Identity invalid!";
540 Server server = usedServer();
543 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
544 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
545 if (!server.useSsl || !socket.isEncrypted()) {
546 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
549 if (server.useSsl && !socket.isEncrypted()) {
550 // We'll finish setup once we're encrypted, and called again
554 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
557 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
559 // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
560 // capability negotiation. networkInitialized() will call updateRateLimiting() without the
561 // force flag to apply user preferences. When making changes, ensure that this still happens!
562 // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
563 // server receive queue and cause a kill. "Shouldn't" being the operative word; the real world
565 updateRateLimiting(true);
566 // Fill up the token bucket as we're connecting from scratch
569 // Request capabilities as per IRCv3.2 specifications
570 // Older servers should ignore this; newer servers won't downgrade to RFC1459
571 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
572 putRawLine(serverEncode(QString("CAP LS 302")));
574 if (!server.password.isEmpty()) {
575 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
578 if (identity->nicks().isEmpty()) {
580 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
583 nick = identity->nicks()[0];
585 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
586 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
590 void CoreNetwork::socketDisconnected()
592 disablePingTimeout();
595 _autoWhoCycleTimer.stop();
596 _autoWhoTimer.stop();
597 _autoWhoQueue.clear();
598 _autoWhoPending.clear();
600 _socketCloseTimer.stop();
602 _tokenBucketTimer.stop();
606 foreach(QString channel, me_->channels())
607 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
611 emit disconnected(networkId());
612 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
613 // Reset disconnect expectations
614 _disconnectExpected = false;
615 if (_quitRequested) {
616 _quitRequested = false;
617 setConnectionState(Network::Disconnected);
618 Core::setNetworkConnected(userId(), networkId(), false);
620 else if (_autoReconnectCount != 0) {
621 setConnectionState(Network::Reconnecting);
622 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
623 doAutoReconnect(); // first try is immediate
625 _autoReconnectTimer.start();
630 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
632 Network::ConnectionState state;
633 switch (socketState) {
634 case QAbstractSocket::UnconnectedState:
635 state = Network::Disconnected;
636 socketDisconnected();
638 case QAbstractSocket::HostLookupState:
639 case QAbstractSocket::ConnectingState:
640 state = Network::Connecting;
642 case QAbstractSocket::ConnectedState:
643 state = Network::Initializing;
645 case QAbstractSocket::ClosingState:
646 state = Network::Disconnecting;
649 state = Network::Disconnected;
651 setConnectionState(state);
655 void CoreNetwork::networkInitialized()
657 setConnectionState(Network::Initialized);
659 _disconnectExpected = false;
660 _quitRequested = false;
662 // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
663 // flag used for initial registration and capability negotiation.
664 updateRateLimiting();
666 if (useAutoReconnect()) {
668 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
671 // restore away state
672 QString awayMsg = Core::awayMessage(userId(), networkId());
673 if (!awayMsg.isEmpty()) {
674 // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
675 // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
676 userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
683 if (networkConfig()->autoWhoEnabled()) {
684 _autoWhoCycleTimer.start();
685 _autoWhoTimer.start();
686 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
689 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
690 Core::setNetworkConnected(userId(), networkId(), true);
694 void CoreNetwork::sendPerform()
696 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
699 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
700 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
703 // restore old user modes if server default mode is set.
706 if (!me_->userModes().isEmpty()) {
710 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
711 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
716 foreach(QString line, perform()) {
717 if (!line.isEmpty()) userInput(statusBuf, line);
720 // rejoin channels we've been in
721 if (rejoinChannels()) {
722 QStringList channels, keys;
723 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
724 QString key = channelKey(chan);
725 if (!key.isEmpty()) {
726 channels.prepend(chan);
730 channels.append(chan);
733 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
734 if (!joinString.isEmpty())
735 userInputHandler()->handleJoin(statusBuf, joinString);
740 void CoreNetwork::restoreUserModes()
745 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
746 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
748 QString modesDelta = Core::userModes(userId(), networkId());
749 QString currentModes = me_->userModes();
751 QString addModes, removeModes;
752 if (modesDelta.contains('-')) {
753 addModes = modesDelta.section('-', 0, 0);
754 removeModes = modesDelta.section('-', 1);
757 addModes = modesDelta;
760 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
761 if (currentModes.isEmpty())
762 removeModes = QString();
764 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
766 if (addModes.isEmpty() && removeModes.isEmpty())
769 if (!addModes.isEmpty())
770 addModes = '+' + addModes;
771 if (!removeModes.isEmpty())
772 removeModes = '-' + removeModes;
774 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
775 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
779 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
785 for (int i = 0; i < requestedModes.length(); i++) {
786 if (requestedModes[i] == '+') {
790 if (requestedModes[i] == '-') {
795 addModes += requestedModes[i];
798 removeModes += requestedModes[i];
802 QString addModesOld = _requestedUserModes.section('-', 0, 0);
803 QString removeModesOld = _requestedUserModes.section('-', 1);
805 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
806 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
807 addModes += addModesOld;
809 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
810 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
811 removeModes += removeModesOld;
813 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
817 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
819 QString persistentUserModes = Core::userModes(userId(), networkId());
821 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
822 QString requestedRemove = _requestedUserModes.section('-', 1);
824 QString persistentAdd, persistentRemove;
825 if (persistentUserModes.contains('-')) {
826 persistentAdd = persistentUserModes.section('-', 0, 0);
827 persistentRemove = persistentUserModes.section('-', 1);
830 persistentAdd = persistentUserModes;
833 // remove modes we didn't issue
834 if (requestedAdd.isEmpty())
835 addModes = QString();
837 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
839 if (requestedRemove.isEmpty())
840 removeModes = QString();
842 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
845 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
846 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
849 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
850 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
852 // update issued mode list
853 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
854 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
855 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
857 persistentAdd += addModes;
858 persistentRemove += removeModes;
859 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
863 void CoreNetwork::resetPersistentModes()
865 _requestedUserModes = QString('-');
866 Core::setUserModes(userId(), networkId(), QString());
870 void CoreNetwork::setUseAutoReconnect(bool use)
872 Network::setUseAutoReconnect(use);
874 _autoReconnectTimer.stop();
878 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
880 Network::setAutoReconnectInterval(interval);
881 _autoReconnectTimer.setInterval(interval * 1000);
885 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
887 Network::setAutoReconnectRetries(retries);
888 if (_autoReconnectCount != 0) {
889 if (unlimitedReconnectRetries())
890 _autoReconnectCount = -1;
892 _autoReconnectCount = autoReconnectRetries();
897 void CoreNetwork::doAutoReconnect()
899 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
900 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
903 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
904 _autoReconnectCount--; // -2 means we delay the next reconnect
909 void CoreNetwork::sendPing()
911 uint now = QDateTime::currentDateTime().toTime_t();
912 if (_pingCount != 0) {
913 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
914 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
916 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
917 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
918 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
919 // and unable to even handle a ping answer. So we ignore those misses.
920 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
925 // Don't send pings until the network is initialized
927 userInputHandler()->handlePing(BufferInfo(), QString());
932 void CoreNetwork::enablePingTimeout(bool enable)
935 disablePingTimeout();
938 if (networkConfig()->pingTimeoutEnabled())
944 void CoreNetwork::disablePingTimeout()
952 void CoreNetwork::setPingInterval(int interval)
954 _pingTimer.setInterval(interval * 1000);
958 /******** Custom Rate Limiting ********/
960 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
962 // Verify and apply custom rate limiting options, always resetting the delay and burst size
963 // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
964 // this may be called while connected to a server.
966 if (useCustomMessageRate() || forceUnlimited) {
967 // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
969 _messageDelay = messageRateDelay();
971 _burstSize = messageRateBurstSize();
972 if (_burstSize < 1) {
973 qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
975 // Can't go slower than one message at a time
979 if (_tokenBucket > _burstSize) {
980 // Don't let the token bucket exceed the maximum
981 _tokenBucket = _burstSize;
982 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
983 // changing the rate-limit settings while connected to a server will incorrectly reset
987 // Toggle the timer according to whether or not rate limiting is enabled
988 // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
989 // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
990 // Override user preferences if called with force unlimited, only used during connect.
991 _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
992 if (_skipMessageRates) {
993 // If the message queue already contains messages, they need sent before disabling the
994 // timer. Set the timer to a rapid pace and let it disable itself.
995 if (_msgQueue.size() > 0) {
996 qDebug() << "Outgoing message queue contains messages while disabling rate "
997 "limiting. Sending remaining queued messages...";
998 // Promptly run the timer again to clear the messages. Rate limiting is disabled,
999 // so nothing should cause this to block.. in theory. However, don't directly call
1000 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1002 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1003 // Hesitant to change it without a wide variety of situations to verify behavior.
1004 _tokenBucketTimer.start(100);
1006 // No rate limiting, disable the timer
1007 _tokenBucketTimer.stop();
1010 // Rate limiting enabled, enable the timer
1011 _tokenBucketTimer.start(_messageDelay);
1014 // Custom message rates disabled. Go for the default.
1016 _skipMessageRates = false; // Enable rate-limiting by default
1017 _messageDelay = 2200; // This seems to be a safe value (2.2 seconds delay)
1018 _burstSize = 5; // 5 messages at once
1019 if (_tokenBucket > _burstSize) {
1020 // TokenBucket to avoid sending too much at once. Don't let the token bucket exceed the
1022 _tokenBucket = _burstSize;
1023 // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
1024 // changing the rate-limit settings while connected to a server will incorrectly reset
1025 // the token bucket.
1027 // Rate limiting enabled, enable the timer
1028 _tokenBucketTimer.start(_messageDelay);
1032 void CoreNetwork::resetTokenBucket()
1034 // Fill up the token bucket to the maximum
1035 _tokenBucket = _burstSize;
1039 /******** IRCv3 Capability Negotiation ********/
1041 void CoreNetwork::serverCapAdded(const QString &capability)
1043 // Check if it's a known capability; if so, add it to the list
1044 // Handle special cases first
1045 if (capability == IrcCap::SASL) {
1046 // Only request SASL if it's enabled
1047 if (networkInfo().useSasl)
1048 queueCap(capability);
1049 } else if (IrcCap::knownCaps.contains(capability)) {
1050 // Handling for general known capabilities
1051 queueCap(capability);
1055 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1057 // This may be called multiple times in certain situations.
1059 // Handle core-side configuration
1060 if (capability == IrcCap::AWAY_NOTIFY) {
1061 // away-notify enabled, stop the autoWho timers, handle manually
1062 setAutoWhoEnabled(false);
1065 // Handle capabilities that require further messages sent to the IRC server
1066 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1067 if (capability == IrcCap::SASL) {
1068 // If SASL mechanisms specified, limit to what's accepted for authentication
1069 // if the current identity has a cert set, use SASL EXTERNAL
1072 if (!identityPtr()->sslCert().isNull()) {
1073 if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1074 // EXTERNAL authentication supported, send request
1075 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1077 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1078 tr("SASL EXTERNAL authentication not supported"));
1083 if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1084 // PLAIN authentication supported, send request
1085 // Only working with PLAIN atm, blowfish later
1086 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1088 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1089 tr("SASL PLAIN authentication not supported"));
1098 void CoreNetwork::serverCapRemoved(const QString &capability)
1100 // This may be called multiple times in certain situations.
1102 // Handle special cases here
1103 if (capability == IrcCap::AWAY_NOTIFY) {
1104 // away-notify disabled, enable autoWho according to configuration
1105 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1109 void CoreNetwork::queueCap(const QString &capability)
1111 // IRCv3 specs all use lowercase capability names
1112 QString _capLowercase = capability.toLower();
1114 if(capsRequiringConfiguration.contains(_capLowercase)) {
1115 // The capability requires additional configuration before being acknowledged (e.g. SASL),
1116 // so we should negotiate it separately from all other capabilities. Otherwise new
1117 // capabilities will be requested while still configuring the previous one.
1118 if (!_capsQueuedIndividual.contains(_capLowercase)) {
1119 _capsQueuedIndividual.append(_capLowercase);
1122 // The capability doesn't need any special configuration, so it should be safe to try
1123 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1125 if (!_capsQueuedBundled.contains(_capLowercase)) {
1126 _capsQueuedBundled.append(_capLowercase);
1131 QString CoreNetwork::takeQueuedCaps()
1133 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1135 _capsQueuedLastBundle.clear();
1137 // First, negotiate all the standalone capabilities that require additional configuration.
1138 if (!_capsQueuedIndividual.empty()) {
1139 // We have an individual capability available. Take the first and pass it back.
1140 return _capsQueuedIndividual.takeFirst();
1141 } else if (!_capsQueuedBundled.empty()) {
1142 // We have capabilities available that can be grouped. Try to fit in as many as within the
1144 // See CoreNetwork::maxCapRequestLength
1146 // Response must have at least one capability regardless of max length for anything to
1148 QString capBundle = _capsQueuedBundled.takeFirst();
1149 QString nextCap("");
1150 while (!_capsQueuedBundled.empty()) {
1151 // As long as capabilities remain, get the next...
1152 nextCap = _capsQueuedBundled.first();
1153 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1154 // [capability + 1 for a space + this new capability] fit within length limits
1155 // Add it to formatted list
1156 capBundle.append(" " + nextCap);
1157 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1158 _capsQueuedLastBundle.append(nextCap);
1159 // Then remove it from the queue
1160 _capsQueuedBundled.removeFirst();
1162 // We've reached the length limit for a single capability request, stop adding more
1166 // Return this space-separated set of capabilities, removing any extra spaces
1167 return capBundle.trimmed();
1169 // No capabilities left to negotiate, return an empty string.
1174 void CoreNetwork::retryCapsIndividually()
1176 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1177 // denied, try each capability individually.
1178 if (_capsQueuedLastBundle.empty()) {
1179 // No most recently tried capability set, just return.
1181 // Note: there's little point in retrying individually requested caps during negotiation.
1182 // We know the individual capability was the one that failed, and it's not likely it'll
1183 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1184 // handling capability removal and addition.
1187 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1188 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1189 // keeping track of which halves of the group fail, dividing the set each time.
1191 // Add most recently tried capability set to individual list, re-requesting them one at a time
1192 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1193 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1194 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1195 tr("Could not negotiate some capabilities, retrying individually (%1)...")
1196 .arg(_capsQueuedLastBundle.join(", ")));
1197 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1198 // need to remove them here.
1199 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1201 _capsQueuedLastBundle.clear();
1204 void CoreNetwork::beginCapNegotiation()
1206 // Don't begin negotiation if no capabilities are queued to request
1207 if (!capNegotiationInProgress()) {
1208 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1209 // normal connection.
1210 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1211 endCapNegotiation();
1215 _capNegotiationActive = true;
1216 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1217 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1219 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1220 // comma separator between the two if needed (both individual and bundled caps exist).
1221 QString queuedCapsDisplay =
1222 _capsQueuedIndividual.join(", ")
1223 + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1224 + _capsQueuedBundled.join(", ");
1225 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1226 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1231 void CoreNetwork::sendNextCap()
1233 if (capNegotiationInProgress()) {
1234 // Request the next set of capabilities and remove them from the list
1235 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1237 // No pending desired capabilities, capability negotiation finished
1238 // If SASL requested but not available, print a warning
1239 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1240 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1241 tr("SASL authentication currently not supported by server"));
1243 if (_capNegotiationActive) {
1244 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1245 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1246 _capNegotiationActive = false;
1249 endCapNegotiation();
1253 void CoreNetwork::endCapNegotiation()
1255 // If nick registration is already complete, CAP END is not required
1256 if (!_capInitialNegotiationEnded) {
1257 putRawLine(serverEncode(QString("CAP END")));
1258 _capInitialNegotiationEnded = true;
1262 /******** AutoWHO ********/
1264 void CoreNetwork::startAutoWhoCycle()
1266 if (!_autoWhoQueue.isEmpty()) {
1267 _autoWhoCycleTimer.stop();
1270 _autoWhoQueue = channels();
1273 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1275 // Prepend so these new channels/nicks are the first to be checked
1276 // Don't allow duplicates
1277 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1278 _autoWhoQueue.prepend(channelOrNick.toLower());
1280 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1281 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1282 setAutoWhoEnabled(true);
1287 void CoreNetwork::setAutoWhoDelay(int delay)
1289 _autoWhoTimer.setInterval(delay * 1000);
1293 void CoreNetwork::setAutoWhoInterval(int interval)
1295 _autoWhoCycleTimer.setInterval(interval * 1000);
1299 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1301 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1302 _autoWhoTimer.start();
1303 else if (!enabled) {
1304 _autoWhoTimer.stop();
1305 _autoWhoCycleTimer.stop();
1310 void CoreNetwork::sendAutoWho()
1312 // Don't send autowho if there are still some pending
1313 if (_autoWhoPending.count())
1316 while (!_autoWhoQueue.isEmpty()) {
1317 QString chanOrNick = _autoWhoQueue.takeFirst();
1318 // Check if it's a known channel or nick
1319 IrcChannel *ircchan = ircChannel(chanOrNick);
1320 IrcUser *ircuser = ircUser(chanOrNick);
1322 // Apply channel limiting rules
1323 // If using away-notify, don't impose channel size limits in order to capture away
1324 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1325 if (networkConfig()->autoWhoNickLimit() > 0
1326 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1327 && !capEnabled(IrcCap::AWAY_NOTIFY))
1329 _autoWhoPending[chanOrNick.toLower()]++;
1330 } else if (ircuser) {
1331 // Checking a nick, add it to the pending list
1332 _autoWhoPending[ircuser->nick().toLower()]++;
1334 // Not a channel or a nick, skip it
1335 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1338 if (supports("WHOX")) {
1339 // Use WHO extended to poll away users and/or user accounts
1340 // See http://faerion.sourceforge.net/doc/irc/whox.var
1341 // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1342 putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1343 .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1345 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1350 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1351 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1352 // Timer was stopped, means a new cycle is due immediately
1353 // Don't run a new cycle if using away-notify; server will notify as appropriate
1354 _autoWhoCycleTimer.start();
1355 startAutoWhoCycle();
1356 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1357 // Don't run another who cycle if away-notify is enabled
1358 _autoWhoCycleTimer.stop();
1364 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1366 Server server = usedServer();
1367 if (server.sslVerify) {
1368 // Treat the SSL error as a hard error
1369 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1370 "since verification is required");
1371 if (!sslErrors.empty()) {
1372 // Add the error reason if known
1373 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1375 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1377 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1378 // validity, network trouble, etc.
1379 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1381 // Treat the SSL error as a warning, continue to connect anyways
1382 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1383 "since verification is not required");
1384 if (!sslErrors.empty()) {
1385 // Add the error reason if known
1386 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1388 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1390 // Proceed with the connection
1391 socket.ignoreSslErrors();
1398 void CoreNetwork::checkTokenBucket()
1400 if (_skipMessageRates) {
1401 if (_msgQueue.size() == 0) {
1402 // Message queue emptied; stop the timer and bail out
1403 _tokenBucketTimer.stop();
1406 // Otherwise, we're emptying the queue, continue on as normal
1409 // Process whatever messages are pending
1410 fillBucketAndProcessQueue();
1414 void CoreNetwork::fillBucketAndProcessQueue()
1416 // If there's less tokens than burst size, refill the token bucket by 1
1417 if (_tokenBucket < _burstSize) {
1421 // As long as there's tokens available and messages remaining, sending messages from the queue
1422 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1423 writeToSocket(_msgQueue.takeFirst());
1428 void CoreNetwork::writeToSocket(const QByteArray &data)
1431 socket.write("\r\n");
1432 if (!_skipMessageRates) {
1433 // Only subtract from the token bucket if message rate limiting is enabled
1439 Network::Server CoreNetwork::usedServer() const
1441 if (_lastUsedServerIndex < serverList().count())
1442 return serverList()[_lastUsedServerIndex];
1444 if (!serverList().isEmpty())
1445 return serverList()[0];
1447 return Network::Server();
1451 void CoreNetwork::requestConnect() const
1453 if (connectionState() != Disconnected) {
1454 qWarning() << "Requesting connect while already being connected!";
1457 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1461 void CoreNetwork::requestDisconnect() const
1463 if (connectionState() == Disconnected) {
1464 qWarning() << "Requesting disconnect while not being connected!";
1467 userInputHandler()->handleQuit(BufferInfo(), QString());
1471 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1473 Network::Server currentServer = usedServer();
1474 setNetworkInfo(info);
1475 Core::updateNetwork(coreSession()->user(), info);
1477 // the order of the servers might have changed,
1478 // so we try to find the previously used server
1479 _lastUsedServerIndex = 0;
1480 for (int i = 0; i < serverList().count(); i++) {
1481 Network::Server server = serverList()[i];
1482 if (server.host == currentServer.host && server.port == currentServer.port) {
1483 _lastUsedServerIndex = i;
1490 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1492 QString wrkMsg(message);
1493 QList<QList<QByteArray>> msgsToSend;
1495 // do while (wrkMsg.size() > 0)
1497 // First, check to see if the whole message can be sent at once. The
1498 // cmdGenerator function is passed in by the caller and is used to encode
1499 // and encrypt (if applicable) the message, since different callers might
1500 // want to use different encoding or encode different values.
1501 int splitPos = wrkMsg.size();
1502 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1503 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1505 if (initialOverrun) {
1506 // If the message was too long to be sent, first try splitting it along
1507 // word boundaries with QTextBoundaryFinder.
1508 QString splitMsg(wrkMsg);
1509 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1510 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1511 QList<QByteArray> splitMsgEnc;
1512 int overrun = initialOverrun;
1515 splitPos = qtbf.toPreviousBoundary();
1517 // splitPos==-1 means the QTBF couldn't find a split point at all and
1518 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1519 // the string. Neither one of these works for us.
1521 // If a split point could be found, split the message there, calculate the
1522 // overrun, and continue with the loop.
1523 splitMsg = splitMsg.left(splitPos);
1524 splitMsgEnc = cmdGenerator(splitMsg);
1525 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1528 // If a split point could not be found (the beginning of the message
1529 // is reached without finding a split point short enough to send) and we
1530 // are still in Word mode, switch to Grapheme mode. We also need to restore
1531 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1532 // the previous attempt to find a split point.
1533 if (qtbf.type() == QTextBoundaryFinder::Word) {
1535 splitPos = splitMsg.size();
1536 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1537 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1538 qtbf = graphemeQtbf;
1541 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1542 // This should never happen, but it should be handled anyway.
1543 qWarning() << "Unexpected failure to split message!";
1549 // Once a message of sendable length has been found, remove it from the wrkMsg and
1550 // add it to the list of messages to be sent.
1551 wrkMsg.remove(0, splitPos);
1552 msgsToSend.append(splitMsgEnc);
1555 // If the entire remaining message is short enough to be sent all at once, remove
1556 // it from the wrkMsg and add it to the list of messages to be sent.
1557 wrkMsg.remove(0, splitPos);
1558 msgsToSend.append(initialSplitMsgEnc);
1560 } while (wrkMsg.size() > 0);