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(fillBucketAndProcessQueue()));
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 // IRCv3 capability handling
88 // These react to CAP messages from the server
89 connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
90 connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
91 connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
93 if (Quassel::isOptionSet("oidentd")) {
94 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
95 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
100 CoreNetwork::~CoreNetwork()
102 // Request a proper disconnect, but don't count as user-requested disconnect
103 if (socketConnected()) {
104 // Only try if the socket's fully connected (not initializing or disconnecting).
105 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
106 // shown even if other messages are queued.
107 disconnectFromIrc(false, QString(), false, true);
108 // Process the putCmd events that trigger the quit. Without this, shutting down the core
109 // results in abrubtly closing the socket rather than sending the QUIT as expected.
110 QCoreApplication::processEvents();
111 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
112 if (!forceDisconnect()) {
113 qWarning() << "Timed out quitting network" << networkName() <<
114 "(user ID " << userId() << ")";
117 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
118 delete _userInputHandler;
122 bool CoreNetwork::forceDisconnect(int msecs)
124 if (socket.state() == QAbstractSocket::UnconnectedState) {
125 // Socket already disconnected.
128 // Request a socket-level disconnect if not already happened
129 socket.disconnectFromHost();
130 // Return the result of waiting for disconnect; true if successful, otherwise false
131 return socket.waitForDisconnected(msecs);
135 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
137 if (!bufferName.isEmpty()) {
138 IrcChannel *channel = ircChannel(bufferName);
140 return channel->decodeString(string);
142 return decodeString(string);
146 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
148 IrcUser *user = ircUser(userNick);
150 return user->decodeString(string);
151 return decodeString(string);
155 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
157 if (!bufferName.isEmpty()) {
158 IrcChannel *channel = ircChannel(bufferName);
160 return channel->encodeString(string);
162 return encodeString(string);
166 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
168 IrcUser *user = ircUser(userNick);
170 return user->encodeString(string);
171 return encodeString(string);
175 void CoreNetwork::connectToIrc(bool reconnecting)
177 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
178 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
179 if (unlimitedReconnectRetries())
180 _autoReconnectCount = -1;
182 _autoReconnectCount = autoReconnectRetries();
184 if (serverList().isEmpty()) {
185 qWarning() << "Server list empty, ignoring connect request!";
188 CoreIdentity *identity = identityPtr();
190 qWarning() << "Invalid identity configures, ignoring connect request!";
194 // cleaning up old quit reason
197 // Reset capability negotiation tracking, also handling server changes during reconnect
198 _capsQueuedIndividual.clear();
199 _capsQueuedBundled.clear();
201 _capNegotiationActive = false;
202 _capInitialNegotiationEnded = false;
204 // use a random server?
205 if (useRandomServer()) {
206 _lastUsedServerIndex = qrand() % serverList().size();
208 else if (_previousConnectionAttemptFailed) {
209 // cycle to next server if previous connection attempt failed
210 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
211 if (++_lastUsedServerIndex >= serverList().size()) {
212 _lastUsedServerIndex = 0;
215 _previousConnectionAttemptFailed = false;
217 Server server = usedServer();
218 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
219 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
221 if (server.useProxy) {
222 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
223 socket.setProxy(proxy);
226 socket.setProxy(QNetworkProxy::NoProxy);
231 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
232 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
233 QHostInfo::fromName(server.host);
237 CoreIdentity *identity = identityPtr();
239 socket.setLocalCertificate(identity->sslCert());
240 socket.setPrivateKey(identity->sslKey());
242 socket.connectToHostEncrypted(server.host, server.port);
245 socket.connectToHost(server.host, server.port);
248 socket.connectToHost(server.host, server.port);
253 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
256 // Disconnecting from the network, should expect a socket close or error
257 _disconnectExpected = true;
258 _quitRequested = requested; // see socketDisconnected();
259 if (!withReconnect) {
260 _autoReconnectTimer.stop();
261 _autoReconnectCount = 0; // prohibiting auto reconnect
263 disablePingTimeout();
270 awayMsg = me_->awayMessage();
271 Core::setAwayMessage(userId(), networkId(), awayMsg);
274 if (reason.isEmpty() && identityPtr())
275 _quitReason = identityPtr()->quitReason();
277 _quitReason = reason;
279 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
280 if (socket.state() == QAbstractSocket::UnconnectedState) {
281 socketDisconnected();
283 if (socket.state() == QAbstractSocket::ConnectedState) {
284 userInputHandler()->issueQuit(_quitReason, forceImmediate);
288 if (requested || withReconnect) {
289 // the irc server has 10 seconds to close the socket
290 _socketCloseTimer.start(10000);
296 void CoreNetwork::userInput(BufferInfo buf, QString msg)
298 userInputHandler()->handleUserInput(buf, msg);
302 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
304 if (_tokenBucket > 0) {
308 _msgQueue.prepend(s);
316 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
320 if (!prefix.isEmpty())
321 msg += ":" + prefix + " ";
322 msg += cmd.toUpper().toLatin1();
324 for (int i = 0; i < params.size(); i++) {
327 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
333 putRawLine(msg, prepend);
337 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
339 QListIterator<QList<QByteArray>> i(params);
340 while (i.hasNext()) {
341 QList<QByteArray> msg = i.next();
342 putCmd(cmd, msg, prefix, prependAll);
347 void CoreNetwork::setChannelJoined(const QString &channel)
349 queueAutoWhoOneshot(channel); // check this new channel first
351 Core::setChannelPersistent(userId(), networkId(), channel, true);
352 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
356 void CoreNetwork::setChannelParted(const QString &channel)
358 removeChannelKey(channel);
359 _autoWhoQueue.removeAll(channel.toLower());
360 _autoWhoPending.remove(channel.toLower());
362 Core::setChannelPersistent(userId(), networkId(), channel, false);
366 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
369 removeChannelKey(channel);
372 _channelKeys[channel.toLower()] = key;
377 void CoreNetwork::removeChannelKey(const QString &channel)
379 _channelKeys.remove(channel.toLower());
384 Cipher *CoreNetwork::cipher(const QString &target)
386 if (target.isEmpty())
389 if (!Cipher::neededFeaturesAvailable())
392 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
394 return channel->cipher();
396 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
398 return user->cipher();
399 } else if (!isChannelName(target)) {
400 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
406 QByteArray CoreNetwork::cipherKey(const QString &target) const
408 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
410 return c->cipher()->key();
412 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
414 return u->cipher()->key();
420 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
422 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
424 c->setEncrypted(c->cipher()->setKey(key));
428 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
429 if (!u && !isChannelName(target))
430 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
433 u->setEncrypted(u->cipher()->setKey(key));
439 bool CoreNetwork::cipherUsesCBC(const QString &target)
441 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
443 return c->cipher()->usesCBC();
444 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
446 return u->cipher()->usesCBC();
450 #endif /* HAVE_QCA2 */
452 bool CoreNetwork::setAutoWhoDone(const QString &channel)
454 QString chan = channel.toLower();
455 if (_autoWhoPending.value(chan, 0) <= 0)
457 if (--_autoWhoPending[chan] <= 0)
458 _autoWhoPending.remove(chan);
463 void CoreNetwork::setMyNick(const QString &mynick)
465 Network::setMyNick(mynick);
466 if (connectionState() == Network::Initializing)
467 networkInitialized();
471 void CoreNetwork::socketHasData()
473 while (socket.canReadLine()) {
474 QByteArray s = socket.readLine();
475 if (s.endsWith("\r\n"))
477 else if (s.endsWith("\n"))
479 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
480 event->setTimestamp(QDateTime::currentDateTimeUtc());
481 emit newEvent(event);
486 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
488 // Ignore socket closed errors if expected
489 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
493 _previousConnectionAttemptFailed = true;
494 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
495 emit connectionError(socket.errorString());
496 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
497 emitConnectionError(socket.errorString());
498 if (socket.state() < QAbstractSocket::ConnectedState) {
499 socketDisconnected();
504 void CoreNetwork::socketInitialized()
506 CoreIdentity *identity = identityPtr();
508 qCritical() << "Identity invalid!";
513 Server server = usedServer();
516 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
517 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
518 if (!server.useSsl || !socket.isEncrypted()) {
519 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
522 if (server.useSsl && !socket.isEncrypted()) {
523 // We'll finish setup once we're encrypted, and called again
527 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
530 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
532 // TokenBucket to avoid sending too much at once
533 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
535 _tokenBucket = _burstSize; // init with a full bucket
536 _tokenBucketTimer.start(_messageDelay);
538 // Request capabilities as per IRCv3.2 specifications
539 // Older servers should ignore this; newer servers won't downgrade to RFC1459
540 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
541 putRawLine(serverEncode(QString("CAP LS 302")));
543 if (!server.password.isEmpty()) {
544 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
547 if (identity->nicks().isEmpty()) {
549 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
552 nick = identity->nicks()[0];
554 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
555 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
559 void CoreNetwork::socketDisconnected()
561 disablePingTimeout();
564 _autoWhoCycleTimer.stop();
565 _autoWhoTimer.stop();
566 _autoWhoQueue.clear();
567 _autoWhoPending.clear();
569 _socketCloseTimer.stop();
571 _tokenBucketTimer.stop();
575 foreach(QString channel, me_->channels())
576 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
580 emit disconnected(networkId());
581 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
582 // Reset disconnect expectations
583 _disconnectExpected = false;
584 if (_quitRequested) {
585 _quitRequested = false;
586 setConnectionState(Network::Disconnected);
587 Core::setNetworkConnected(userId(), networkId(), false);
589 else if (_autoReconnectCount != 0) {
590 setConnectionState(Network::Reconnecting);
591 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
592 doAutoReconnect(); // first try is immediate
594 _autoReconnectTimer.start();
599 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
601 Network::ConnectionState state;
602 switch (socketState) {
603 case QAbstractSocket::UnconnectedState:
604 state = Network::Disconnected;
605 socketDisconnected();
607 case QAbstractSocket::HostLookupState:
608 case QAbstractSocket::ConnectingState:
609 state = Network::Connecting;
611 case QAbstractSocket::ConnectedState:
612 state = Network::Initializing;
614 case QAbstractSocket::ClosingState:
615 state = Network::Disconnecting;
618 state = Network::Disconnected;
620 setConnectionState(state);
624 void CoreNetwork::networkInitialized()
626 setConnectionState(Network::Initialized);
628 _disconnectExpected = false;
629 _quitRequested = false;
631 if (useAutoReconnect()) {
633 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
636 // restore away state
637 QString awayMsg = Core::awayMessage(userId(), networkId());
638 if (!awayMsg.isEmpty())
639 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
645 if (networkConfig()->autoWhoEnabled()) {
646 _autoWhoCycleTimer.start();
647 _autoWhoTimer.start();
648 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
651 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
652 Core::setNetworkConnected(userId(), networkId(), true);
656 void CoreNetwork::sendPerform()
658 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
661 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
662 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
665 // restore old user modes if server default mode is set.
668 if (!me_->userModes().isEmpty()) {
672 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
673 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
678 foreach(QString line, perform()) {
679 if (!line.isEmpty()) userInput(statusBuf, line);
682 // rejoin channels we've been in
683 if (rejoinChannels()) {
684 QStringList channels, keys;
685 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
686 QString key = channelKey(chan);
687 if (!key.isEmpty()) {
688 channels.prepend(chan);
692 channels.append(chan);
695 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
696 if (!joinString.isEmpty())
697 userInputHandler()->handleJoin(statusBuf, joinString);
702 void CoreNetwork::restoreUserModes()
707 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
708 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
710 QString modesDelta = Core::userModes(userId(), networkId());
711 QString currentModes = me_->userModes();
713 QString addModes, removeModes;
714 if (modesDelta.contains('-')) {
715 addModes = modesDelta.section('-', 0, 0);
716 removeModes = modesDelta.section('-', 1);
719 addModes = modesDelta;
722 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
723 if (currentModes.isEmpty())
724 removeModes = QString();
726 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
728 if (addModes.isEmpty() && removeModes.isEmpty())
731 if (!addModes.isEmpty())
732 addModes = '+' + addModes;
733 if (!removeModes.isEmpty())
734 removeModes = '-' + removeModes;
736 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
737 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
741 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
747 for (int i = 0; i < requestedModes.length(); i++) {
748 if (requestedModes[i] == '+') {
752 if (requestedModes[i] == '-') {
757 addModes += requestedModes[i];
760 removeModes += requestedModes[i];
764 QString addModesOld = _requestedUserModes.section('-', 0, 0);
765 QString removeModesOld = _requestedUserModes.section('-', 1);
767 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
768 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
769 addModes += addModesOld;
771 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
772 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
773 removeModes += removeModesOld;
775 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
779 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
781 QString persistentUserModes = Core::userModes(userId(), networkId());
783 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
784 QString requestedRemove = _requestedUserModes.section('-', 1);
786 QString persistentAdd, persistentRemove;
787 if (persistentUserModes.contains('-')) {
788 persistentAdd = persistentUserModes.section('-', 0, 0);
789 persistentRemove = persistentUserModes.section('-', 1);
792 persistentAdd = persistentUserModes;
795 // remove modes we didn't issue
796 if (requestedAdd.isEmpty())
797 addModes = QString();
799 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
801 if (requestedRemove.isEmpty())
802 removeModes = QString();
804 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
807 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
808 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
811 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
812 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
814 // update issued mode list
815 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
816 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
817 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
819 persistentAdd += addModes;
820 persistentRemove += removeModes;
821 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
825 void CoreNetwork::resetPersistentModes()
827 _requestedUserModes = QString('-');
828 Core::setUserModes(userId(), networkId(), QString());
832 void CoreNetwork::setUseAutoReconnect(bool use)
834 Network::setUseAutoReconnect(use);
836 _autoReconnectTimer.stop();
840 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
842 Network::setAutoReconnectInterval(interval);
843 _autoReconnectTimer.setInterval(interval * 1000);
847 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
849 Network::setAutoReconnectRetries(retries);
850 if (_autoReconnectCount != 0) {
851 if (unlimitedReconnectRetries())
852 _autoReconnectCount = -1;
854 _autoReconnectCount = autoReconnectRetries();
859 void CoreNetwork::doAutoReconnect()
861 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
862 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
865 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
866 _autoReconnectCount--; // -2 means we delay the next reconnect
871 void CoreNetwork::sendPing()
873 uint now = QDateTime::currentDateTime().toTime_t();
874 if (_pingCount != 0) {
875 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
876 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
878 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
879 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
880 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
881 // and unable to even handle a ping answer. So we ignore those misses.
882 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
887 // Don't send pings until the network is initialized
889 userInputHandler()->handlePing(BufferInfo(), QString());
894 void CoreNetwork::enablePingTimeout(bool enable)
897 disablePingTimeout();
900 if (networkConfig()->pingTimeoutEnabled())
906 void CoreNetwork::disablePingTimeout()
914 void CoreNetwork::setPingInterval(int interval)
916 _pingTimer.setInterval(interval * 1000);
919 /******** IRCv3 Capability Negotiation ********/
921 void CoreNetwork::serverCapAdded(const QString &capability)
923 // Check if it's a known capability; if so, add it to the list
924 // Handle special cases first
925 if (capability == IrcCap::SASL) {
926 // Only request SASL if it's enabled
927 if (networkInfo().useSasl)
928 queueCap(capability);
929 } else if (IrcCap::knownCaps.contains(capability)) {
930 // Handling for general known capabilities
931 queueCap(capability);
935 void CoreNetwork::serverCapAcknowledged(const QString &capability)
937 // This may be called multiple times in certain situations.
939 // Handle core-side configuration
940 if (capability == IrcCap::AWAY_NOTIFY) {
941 // away-notify enabled, stop the autoWho timers, handle manually
942 setAutoWhoEnabled(false);
945 // Handle capabilities that require further messages sent to the IRC server
946 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
947 if (capability == IrcCap::SASL) {
948 // If SASL mechanisms specified, limit to what's accepted for authentication
949 // if the current identity has a cert set, use SASL EXTERNAL
952 if (!identityPtr()->sslCert().isNull()) {
953 if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::EXTERNAL)) {
954 // EXTERNAL authentication supported, send request
955 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
957 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
958 tr("SASL EXTERNAL authentication not supported"));
963 if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::PLAIN)) {
964 // PLAIN authentication supported, send request
965 // Only working with PLAIN atm, blowfish later
966 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
968 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
969 tr("SASL PLAIN authentication not supported"));
978 void CoreNetwork::serverCapRemoved(const QString &capability)
980 // This may be called multiple times in certain situations.
982 // Handle special cases here
983 if (capability == IrcCap::AWAY_NOTIFY) {
984 // away-notify disabled, enable autoWho according to configuration
985 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
989 void CoreNetwork::queueCap(const QString &capability)
991 // IRCv3 specs all use lowercase capability names
992 QString _capLowercase = capability.toLower();
994 if(capsRequiringConfiguration.contains(_capLowercase)) {
995 // The capability requires additional configuration before being acknowledged (e.g. SASL),
996 // so we should negotiate it separately from all other capabilities. Otherwise new
997 // capabilities will be requested while still configuring the previous one.
998 if (!_capsQueuedIndividual.contains(_capLowercase)) {
999 _capsQueuedIndividual.append(_capLowercase);
1002 // The capability doesn't need any special configuration, so it should be safe to try
1003 // bundling together with others. "Should" being the imperative word, as IRC servers can do
1005 if (!_capsQueuedBundled.contains(_capLowercase)) {
1006 _capsQueuedBundled.append(_capLowercase);
1011 QString CoreNetwork::takeQueuedCaps()
1013 // Clear the record of the most recently negotiated capability bundle. Does nothing if the list
1015 _capsQueuedLastBundle.clear();
1017 // First, negotiate all the standalone capabilities that require additional configuration.
1018 if (!_capsQueuedIndividual.empty()) {
1019 // We have an individual capability available. Take the first and pass it back.
1020 return _capsQueuedIndividual.takeFirst();
1021 } else if (!_capsQueuedBundled.empty()) {
1022 // We have capabilities available that can be grouped. Try to fit in as many as within the
1024 // See CoreNetwork::maxCapRequestLength
1026 // Response must have at least one capability regardless of max length for anything to
1028 QString capBundle = _capsQueuedBundled.takeFirst();
1029 QString nextCap("");
1030 while (!_capsQueuedBundled.empty()) {
1031 // As long as capabilities remain, get the next...
1032 nextCap = _capsQueuedBundled.first();
1033 if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1034 // [capability + 1 for a space + this new capability] fit within length limits
1035 // Add it to formatted list
1036 capBundle.append(" " + nextCap);
1037 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1038 _capsQueuedLastBundle.append(nextCap);
1039 // Then remove it from the queue
1040 _capsQueuedBundled.removeFirst();
1042 // We've reached the length limit for a single capability request, stop adding more
1046 // Return this space-separated set of capabilities, removing any extra spaces
1047 return capBundle.trimmed();
1049 // No capabilities left to negotiate, return an empty string.
1054 void CoreNetwork::retryCapsIndividually()
1056 // The most recent set of capabilities got denied by the IRC server. As we don't know what got
1057 // denied, try each capability individually.
1058 if (_capsQueuedLastBundle.empty()) {
1059 // No most recently tried capability set, just return.
1061 // Note: there's little point in retrying individually requested caps during negotiation.
1062 // We know the individual capability was the one that failed, and it's not likely it'll
1063 // suddenly start working within a few seconds. 'cap-notify' provides a better system for
1064 // handling capability removal and addition.
1067 // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1068 // over efficiency. If this becomes an issue, implement a binary splicing system instead,
1069 // keeping track of which halves of the group fail, dividing the set each time.
1071 // Add most recently tried capability set to individual list, re-requesting them one at a time
1072 _capsQueuedIndividual.append(_capsQueuedLastBundle);
1073 // Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
1074 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1075 tr("Could not negotiate some capabilities, retrying individually (%1)...")
1076 .arg(_capsQueuedLastBundle.join(", ")));
1077 // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1078 // need to remove them here.
1079 // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1081 _capsQueuedLastBundle.clear();
1084 void CoreNetwork::beginCapNegotiation()
1086 // Don't begin negotiation if no capabilities are queued to request
1087 if (!capNegotiationInProgress()) {
1088 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1089 // normal connection.
1090 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1091 endCapNegotiation();
1095 _capNegotiationActive = true;
1096 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1097 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1099 // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1100 // comma separator between the two if needed.
1101 QString queuedCapsDisplay =
1102 (!_capsQueuedIndividual.empty() ? _capsQueuedIndividual.join(", ") + ", " : "")
1103 + _capsQueuedBundled.join(", ");
1104 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1105 tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1110 void CoreNetwork::sendNextCap()
1112 if (capNegotiationInProgress()) {
1113 // Request the next set of capabilities and remove them from the list
1114 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1116 // No pending desired capabilities, capability negotiation finished
1117 // If SASL requested but not available, print a warning
1118 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1119 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1120 tr("SASL authentication currently not supported by server"));
1122 if (_capNegotiationActive) {
1123 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1124 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1125 _capNegotiationActive = false;
1128 endCapNegotiation();
1132 void CoreNetwork::endCapNegotiation()
1134 // If nick registration is already complete, CAP END is not required
1135 if (!_capInitialNegotiationEnded) {
1136 putRawLine(serverEncode(QString("CAP END")));
1137 _capInitialNegotiationEnded = true;
1141 /******** AutoWHO ********/
1143 void CoreNetwork::startAutoWhoCycle()
1145 if (!_autoWhoQueue.isEmpty()) {
1146 _autoWhoCycleTimer.stop();
1149 _autoWhoQueue = channels();
1152 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1154 // Prepend so these new channels/nicks are the first to be checked
1155 // Don't allow duplicates
1156 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1157 _autoWhoQueue.prepend(channelOrNick.toLower());
1159 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1160 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1161 setAutoWhoEnabled(true);
1166 void CoreNetwork::setAutoWhoDelay(int delay)
1168 _autoWhoTimer.setInterval(delay * 1000);
1172 void CoreNetwork::setAutoWhoInterval(int interval)
1174 _autoWhoCycleTimer.setInterval(interval * 1000);
1178 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1180 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1181 _autoWhoTimer.start();
1182 else if (!enabled) {
1183 _autoWhoTimer.stop();
1184 _autoWhoCycleTimer.stop();
1189 void CoreNetwork::sendAutoWho()
1191 // Don't send autowho if there are still some pending
1192 if (_autoWhoPending.count())
1195 while (!_autoWhoQueue.isEmpty()) {
1196 QString chanOrNick = _autoWhoQueue.takeFirst();
1197 // Check if it's a known channel or nick
1198 IrcChannel *ircchan = ircChannel(chanOrNick);
1199 IrcUser *ircuser = ircUser(chanOrNick);
1201 // Apply channel limiting rules
1202 // If using away-notify, don't impose channel size limits in order to capture away
1203 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1204 if (networkConfig()->autoWhoNickLimit() > 0
1205 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1206 && !capEnabled(IrcCap::AWAY_NOTIFY))
1208 _autoWhoPending[chanOrNick.toLower()]++;
1209 } else if (ircuser) {
1210 // Checking a nick, add it to the pending list
1211 _autoWhoPending[ircuser->nick().toLower()]++;
1213 // Not a channel or a nick, skip it
1214 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1217 if (supports("WHOX")) {
1218 // Use WHO extended to poll away users and/or user accounts
1219 // See http://faerion.sourceforge.net/doc/irc/whox.var
1220 // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1221 putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1222 .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1224 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1229 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1230 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1231 // Timer was stopped, means a new cycle is due immediately
1232 // Don't run a new cycle if using away-notify; server will notify as appropriate
1233 _autoWhoCycleTimer.start();
1234 startAutoWhoCycle();
1235 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1236 // Don't run another who cycle if away-notify is enabled
1237 _autoWhoCycleTimer.stop();
1243 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1245 Server server = usedServer();
1246 if (server.sslVerify) {
1247 // Treat the SSL error as a hard error
1248 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1249 "since verification is required");
1250 if (!sslErrors.empty()) {
1251 // Add the error reason if known
1252 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1254 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1256 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1257 // validity, network trouble, etc.
1258 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1260 // Treat the SSL error as a warning, continue to connect anyways
1261 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1262 "since verification is not required");
1263 if (!sslErrors.empty()) {
1264 // Add the error reason if known
1265 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1267 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1269 // Proceed with the connection
1270 socket.ignoreSslErrors();
1277 void CoreNetwork::fillBucketAndProcessQueue()
1279 if (_tokenBucket < _burstSize) {
1283 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1284 writeToSocket(_msgQueue.takeFirst());
1289 void CoreNetwork::writeToSocket(const QByteArray &data)
1292 socket.write("\r\n");
1297 Network::Server CoreNetwork::usedServer() const
1299 if (_lastUsedServerIndex < serverList().count())
1300 return serverList()[_lastUsedServerIndex];
1302 if (!serverList().isEmpty())
1303 return serverList()[0];
1305 return Network::Server();
1309 void CoreNetwork::requestConnect() const
1311 if (connectionState() != Disconnected) {
1312 qWarning() << "Requesting connect while already being connected!";
1315 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1319 void CoreNetwork::requestDisconnect() const
1321 if (connectionState() == Disconnected) {
1322 qWarning() << "Requesting disconnect while not being connected!";
1325 userInputHandler()->handleQuit(BufferInfo(), QString());
1329 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1331 Network::Server currentServer = usedServer();
1332 setNetworkInfo(info);
1333 Core::updateNetwork(coreSession()->user(), info);
1335 // the order of the servers might have changed,
1336 // so we try to find the previously used server
1337 _lastUsedServerIndex = 0;
1338 for (int i = 0; i < serverList().count(); i++) {
1339 Network::Server server = serverList()[i];
1340 if (server.host == currentServer.host && server.port == currentServer.port) {
1341 _lastUsedServerIndex = i;
1348 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1350 QString wrkMsg(message);
1351 QList<QList<QByteArray>> msgsToSend;
1353 // do while (wrkMsg.size() > 0)
1355 // First, check to see if the whole message can be sent at once. The
1356 // cmdGenerator function is passed in by the caller and is used to encode
1357 // and encrypt (if applicable) the message, since different callers might
1358 // want to use different encoding or encode different values.
1359 int splitPos = wrkMsg.size();
1360 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1361 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1363 if (initialOverrun) {
1364 // If the message was too long to be sent, first try splitting it along
1365 // word boundaries with QTextBoundaryFinder.
1366 QString splitMsg(wrkMsg);
1367 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1368 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1369 QList<QByteArray> splitMsgEnc;
1370 int overrun = initialOverrun;
1373 splitPos = qtbf.toPreviousBoundary();
1375 // splitPos==-1 means the QTBF couldn't find a split point at all and
1376 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1377 // the string. Neither one of these works for us.
1379 // If a split point could be found, split the message there, calculate the
1380 // overrun, and continue with the loop.
1381 splitMsg = splitMsg.left(splitPos);
1382 splitMsgEnc = cmdGenerator(splitMsg);
1383 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1386 // If a split point could not be found (the beginning of the message
1387 // is reached without finding a split point short enough to send) and we
1388 // are still in Word mode, switch to Grapheme mode. We also need to restore
1389 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1390 // the previous attempt to find a split point.
1391 if (qtbf.type() == QTextBoundaryFinder::Word) {
1393 splitPos = splitMsg.size();
1394 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1395 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1396 qtbf = graphemeQtbf;
1399 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1400 // This should never happen, but it should be handled anyway.
1401 qWarning() << "Unexpected failure to split message!";
1407 // Once a message of sendable length has been found, remove it from the wrkMsg and
1408 // add it to the list of messages to be sent.
1409 wrkMsg.remove(0, splitPos);
1410 msgsToSend.append(splitMsgEnc);
1413 // If the entire remaining message is short enough to be sent all at once, remove
1414 // it from the wrkMsg and add it to the list of messages to be sent.
1415 wrkMsg.remove(0, splitPos);
1416 msgsToSend.append(initialSplitMsgEnc);
1418 } while (wrkMsg.size() > 0);