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 if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
103 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
104 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
105 delete _userInputHandler;
109 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
111 if (!bufferName.isEmpty()) {
112 IrcChannel *channel = ircChannel(bufferName);
114 return channel->decodeString(string);
116 return decodeString(string);
120 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
122 IrcUser *user = ircUser(userNick);
124 return user->decodeString(string);
125 return decodeString(string);
129 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
131 if (!bufferName.isEmpty()) {
132 IrcChannel *channel = ircChannel(bufferName);
134 return channel->encodeString(string);
136 return encodeString(string);
140 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
142 IrcUser *user = ircUser(userNick);
144 return user->encodeString(string);
145 return encodeString(string);
149 void CoreNetwork::connectToIrc(bool reconnecting)
151 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
152 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
153 if (unlimitedReconnectRetries())
154 _autoReconnectCount = -1;
156 _autoReconnectCount = autoReconnectRetries();
158 if (serverList().isEmpty()) {
159 qWarning() << "Server list empty, ignoring connect request!";
162 CoreIdentity *identity = identityPtr();
164 qWarning() << "Invalid identity configures, ignoring connect request!";
168 // cleaning up old quit reason
171 // Reset capability negotiation tracking, also handling server changes during reconnect
174 _capNegotiationActive = false;
175 _capInitialNegotiationEnded = false;
177 // use a random server?
178 if (useRandomServer()) {
179 _lastUsedServerIndex = qrand() % serverList().size();
181 else if (_previousConnectionAttemptFailed) {
182 // cycle to next server if previous connection attempt failed
183 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
184 if (++_lastUsedServerIndex >= serverList().size()) {
185 _lastUsedServerIndex = 0;
188 _previousConnectionAttemptFailed = false;
190 Server server = usedServer();
191 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
192 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
194 if (server.useProxy) {
195 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
196 socket.setProxy(proxy);
199 socket.setProxy(QNetworkProxy::NoProxy);
204 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
205 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
206 QHostInfo::fromName(server.host);
210 CoreIdentity *identity = identityPtr();
212 socket.setLocalCertificate(identity->sslCert());
213 socket.setPrivateKey(identity->sslKey());
215 socket.connectToHostEncrypted(server.host, server.port);
218 socket.connectToHost(server.host, server.port);
221 socket.connectToHost(server.host, server.port);
226 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
229 // Disconnecting from the network, should expect a socket close or error
230 _disconnectExpected = true;
231 _quitRequested = requested; // see socketDisconnected();
232 if (!withReconnect) {
233 _autoReconnectTimer.stop();
234 _autoReconnectCount = 0; // prohibiting auto reconnect
236 disablePingTimeout();
243 awayMsg = me_->awayMessage();
244 Core::setAwayMessage(userId(), networkId(), awayMsg);
247 if (reason.isEmpty() && identityPtr())
248 _quitReason = identityPtr()->quitReason();
250 _quitReason = reason;
252 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
253 if (socket.state() == QAbstractSocket::UnconnectedState) {
254 socketDisconnected();
256 if (socket.state() == QAbstractSocket::ConnectedState) {
257 userInputHandler()->issueQuit(_quitReason, forceImmediate);
261 if (requested || withReconnect) {
262 // the irc server has 10 seconds to close the socket
263 _socketCloseTimer.start(10000);
269 void CoreNetwork::userInput(BufferInfo buf, QString msg)
271 userInputHandler()->handleUserInput(buf, msg);
275 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
277 if (_tokenBucket > 0) {
281 _msgQueue.prepend(s);
289 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
293 if (!prefix.isEmpty())
294 msg += ":" + prefix + " ";
295 msg += cmd.toUpper().toLatin1();
297 for (int i = 0; i < params.size(); i++) {
300 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
306 putRawLine(msg, prepend);
310 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
312 QListIterator<QList<QByteArray>> i(params);
313 while (i.hasNext()) {
314 QList<QByteArray> msg = i.next();
315 putCmd(cmd, msg, prefix, prependAll);
320 void CoreNetwork::setChannelJoined(const QString &channel)
322 queueAutoWhoOneshot(channel); // check this new channel first
324 Core::setChannelPersistent(userId(), networkId(), channel, true);
325 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
329 void CoreNetwork::setChannelParted(const QString &channel)
331 removeChannelKey(channel);
332 _autoWhoQueue.removeAll(channel.toLower());
333 _autoWhoPending.remove(channel.toLower());
335 Core::setChannelPersistent(userId(), networkId(), channel, false);
339 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
342 removeChannelKey(channel);
345 _channelKeys[channel.toLower()] = key;
350 void CoreNetwork::removeChannelKey(const QString &channel)
352 _channelKeys.remove(channel.toLower());
357 Cipher *CoreNetwork::cipher(const QString &target)
359 if (target.isEmpty())
362 if (!Cipher::neededFeaturesAvailable())
365 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
367 return channel->cipher();
369 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
371 return user->cipher();
372 } else if (!isChannelName(target)) {
373 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
379 QByteArray CoreNetwork::cipherKey(const QString &target) const
381 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
383 return c->cipher()->key();
385 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
387 return u->cipher()->key();
393 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
395 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
397 c->setEncrypted(c->cipher()->setKey(key));
401 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
402 if (!u && !isChannelName(target))
403 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
406 u->setEncrypted(u->cipher()->setKey(key));
412 bool CoreNetwork::cipherUsesCBC(const QString &target)
414 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
416 return c->cipher()->usesCBC();
417 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
419 return u->cipher()->usesCBC();
423 #endif /* HAVE_QCA2 */
425 bool CoreNetwork::setAutoWhoDone(const QString &channel)
427 QString chan = channel.toLower();
428 if (_autoWhoPending.value(chan, 0) <= 0)
430 if (--_autoWhoPending[chan] <= 0)
431 _autoWhoPending.remove(chan);
436 void CoreNetwork::setMyNick(const QString &mynick)
438 Network::setMyNick(mynick);
439 if (connectionState() == Network::Initializing)
440 networkInitialized();
444 void CoreNetwork::socketHasData()
446 while (socket.canReadLine()) {
447 QByteArray s = socket.readLine();
448 if (s.endsWith("\r\n"))
450 else if (s.endsWith("\n"))
452 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
453 event->setTimestamp(QDateTime::currentDateTimeUtc());
454 emit newEvent(event);
459 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
461 // Ignore socket closed errors if expected
462 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
466 _previousConnectionAttemptFailed = true;
467 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
468 emit connectionError(socket.errorString());
469 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
470 emitConnectionError(socket.errorString());
471 if (socket.state() < QAbstractSocket::ConnectedState) {
472 socketDisconnected();
477 void CoreNetwork::socketInitialized()
479 CoreIdentity *identity = identityPtr();
481 qCritical() << "Identity invalid!";
486 Server server = usedServer();
489 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
490 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
491 if (!server.useSsl || !socket.isEncrypted()) {
492 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
495 if (server.useSsl && !socket.isEncrypted()) {
496 // We'll finish setup once we're encrypted, and called again
500 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
503 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
505 // TokenBucket to avoid sending too much at once
506 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
508 _tokenBucket = _burstSize; // init with a full bucket
509 _tokenBucketTimer.start(_messageDelay);
511 // Request capabilities as per IRCv3.2 specifications
512 // Older servers should ignore this; newer servers won't downgrade to RFC1459
513 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
514 putRawLine(serverEncode(QString("CAP LS 302")));
516 if (!server.password.isEmpty()) {
517 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
520 if (identity->nicks().isEmpty()) {
522 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
525 nick = identity->nicks()[0];
527 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
528 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
532 void CoreNetwork::socketDisconnected()
534 disablePingTimeout();
537 _autoWhoCycleTimer.stop();
538 _autoWhoTimer.stop();
539 _autoWhoQueue.clear();
540 _autoWhoPending.clear();
542 _socketCloseTimer.stop();
544 _tokenBucketTimer.stop();
548 foreach(QString channel, me_->channels())
549 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
553 emit disconnected(networkId());
554 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
555 // Reset disconnect expectations
556 _disconnectExpected = false;
557 if (_quitRequested) {
558 _quitRequested = false;
559 setConnectionState(Network::Disconnected);
560 Core::setNetworkConnected(userId(), networkId(), false);
562 else if (_autoReconnectCount != 0) {
563 setConnectionState(Network::Reconnecting);
564 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
565 doAutoReconnect(); // first try is immediate
567 _autoReconnectTimer.start();
572 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
574 Network::ConnectionState state;
575 switch (socketState) {
576 case QAbstractSocket::UnconnectedState:
577 state = Network::Disconnected;
578 socketDisconnected();
580 case QAbstractSocket::HostLookupState:
581 case QAbstractSocket::ConnectingState:
582 state = Network::Connecting;
584 case QAbstractSocket::ConnectedState:
585 state = Network::Initializing;
587 case QAbstractSocket::ClosingState:
588 state = Network::Disconnecting;
591 state = Network::Disconnected;
593 setConnectionState(state);
597 void CoreNetwork::networkInitialized()
599 setConnectionState(Network::Initialized);
601 _disconnectExpected = false;
602 _quitRequested = false;
604 if (useAutoReconnect()) {
606 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
609 // restore away state
610 QString awayMsg = Core::awayMessage(userId(), networkId());
611 if (!awayMsg.isEmpty())
612 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
618 if (networkConfig()->autoWhoEnabled()) {
619 _autoWhoCycleTimer.start();
620 _autoWhoTimer.start();
621 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
624 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
625 Core::setNetworkConnected(userId(), networkId(), true);
629 void CoreNetwork::sendPerform()
631 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
634 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
635 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
638 // restore old user modes if server default mode is set.
641 if (!me_->userModes().isEmpty()) {
645 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
646 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
651 foreach(QString line, perform()) {
652 if (!line.isEmpty()) userInput(statusBuf, line);
655 // rejoin channels we've been in
656 if (rejoinChannels()) {
657 QStringList channels, keys;
658 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
659 QString key = channelKey(chan);
660 if (!key.isEmpty()) {
661 channels.prepend(chan);
665 channels.append(chan);
668 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
669 if (!joinString.isEmpty())
670 userInputHandler()->handleJoin(statusBuf, joinString);
675 void CoreNetwork::restoreUserModes()
680 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
681 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
683 QString modesDelta = Core::userModes(userId(), networkId());
684 QString currentModes = me_->userModes();
686 QString addModes, removeModes;
687 if (modesDelta.contains('-')) {
688 addModes = modesDelta.section('-', 0, 0);
689 removeModes = modesDelta.section('-', 1);
692 addModes = modesDelta;
695 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
696 if (currentModes.isEmpty())
697 removeModes = QString();
699 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
701 if (addModes.isEmpty() && removeModes.isEmpty())
704 if (!addModes.isEmpty())
705 addModes = '+' + addModes;
706 if (!removeModes.isEmpty())
707 removeModes = '-' + removeModes;
709 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
710 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
714 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
720 for (int i = 0; i < requestedModes.length(); i++) {
721 if (requestedModes[i] == '+') {
725 if (requestedModes[i] == '-') {
730 addModes += requestedModes[i];
733 removeModes += requestedModes[i];
737 QString addModesOld = _requestedUserModes.section('-', 0, 0);
738 QString removeModesOld = _requestedUserModes.section('-', 1);
740 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
741 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
742 addModes += addModesOld;
744 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
745 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
746 removeModes += removeModesOld;
748 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
752 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
754 QString persistentUserModes = Core::userModes(userId(), networkId());
756 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
757 QString requestedRemove = _requestedUserModes.section('-', 1);
759 QString persistentAdd, persistentRemove;
760 if (persistentUserModes.contains('-')) {
761 persistentAdd = persistentUserModes.section('-', 0, 0);
762 persistentRemove = persistentUserModes.section('-', 1);
765 persistentAdd = persistentUserModes;
768 // remove modes we didn't issue
769 if (requestedAdd.isEmpty())
770 addModes = QString();
772 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
774 if (requestedRemove.isEmpty())
775 removeModes = QString();
777 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
780 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
781 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
784 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
785 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
787 // update issued mode list
788 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
789 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
790 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
792 persistentAdd += addModes;
793 persistentRemove += removeModes;
794 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
798 void CoreNetwork::resetPersistentModes()
800 _requestedUserModes = QString('-');
801 Core::setUserModes(userId(), networkId(), QString());
805 void CoreNetwork::setUseAutoReconnect(bool use)
807 Network::setUseAutoReconnect(use);
809 _autoReconnectTimer.stop();
813 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
815 Network::setAutoReconnectInterval(interval);
816 _autoReconnectTimer.setInterval(interval * 1000);
820 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
822 Network::setAutoReconnectRetries(retries);
823 if (_autoReconnectCount != 0) {
824 if (unlimitedReconnectRetries())
825 _autoReconnectCount = -1;
827 _autoReconnectCount = autoReconnectRetries();
832 void CoreNetwork::doAutoReconnect()
834 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
835 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
838 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
839 _autoReconnectCount--; // -2 means we delay the next reconnect
844 void CoreNetwork::sendPing()
846 uint now = QDateTime::currentDateTime().toTime_t();
847 if (_pingCount != 0) {
848 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
849 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
851 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
852 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
853 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
854 // and unable to even handle a ping answer. So we ignore those misses.
855 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
860 // Don't send pings until the network is initialized
862 userInputHandler()->handlePing(BufferInfo(), QString());
867 void CoreNetwork::enablePingTimeout(bool enable)
870 disablePingTimeout();
873 if (networkConfig()->pingTimeoutEnabled())
879 void CoreNetwork::disablePingTimeout()
887 void CoreNetwork::setPingInterval(int interval)
889 _pingTimer.setInterval(interval * 1000);
892 /******** IRCv3 Capability Negotiation ********/
894 void CoreNetwork::serverCapAdded(const QString &capability)
896 // Check if it's a known capability; if so, add it to the list
897 // Handle special cases first
898 if (capability == IrcCap::SASL) {
899 // Only request SASL if it's enabled
900 if (networkInfo().useSasl)
901 queueCap(capability);
902 } else if (IrcCap::knownCaps.contains(capability)) {
903 // Handling for general known capabilities
904 queueCap(capability);
908 void CoreNetwork::serverCapAcknowledged(const QString &capability)
910 // This may be called multiple times in certain situations.
912 // Handle core-side configuration
913 if (capability == IrcCap::AWAY_NOTIFY) {
914 // away-notify enabled, stop the autoWho timers, handle manually
915 setAutoWhoEnabled(false);
918 // Handle capabilities that require further messages sent to the IRC server
919 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
920 if (capability == IrcCap::SASL) {
921 // If SASL mechanisms specified, limit to what's accepted for authentication
922 // if the current identity has a cert set, use SASL EXTERNAL
925 if (!identityPtr()->sslCert().isNull()) {
926 if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::EXTERNAL)) {
927 // EXTERNAL authentication supported, send request
928 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
930 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
931 tr("SASL EXTERNAL authentication not supported"));
936 if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::PLAIN)) {
937 // PLAIN authentication supported, send request
938 // Only working with PLAIN atm, blowfish later
939 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
941 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
942 tr("SASL PLAIN authentication not supported"));
951 void CoreNetwork::serverCapRemoved(const QString &capability)
953 // This may be called multiple times in certain situations.
955 // Handle special cases here
956 if (capability == IrcCap::AWAY_NOTIFY) {
957 // away-notify disabled, enable autoWho according to configuration
958 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
962 void CoreNetwork::queueCap(const QString &capability)
964 // IRCv3 specs all use lowercase capability names
965 QString _capLowercase = capability.toLower();
966 if (!_capsQueued.contains(_capLowercase)) {
967 _capsQueued.append(_capLowercase);
971 QString CoreNetwork::takeQueuedCap()
973 if (!_capsQueued.empty()) {
974 return _capsQueued.takeFirst();
980 void CoreNetwork::beginCapNegotiation()
982 // Don't begin negotiation if no capabilities are queued to request
983 if (!capNegotiationInProgress())
986 _capNegotiationActive = true;
987 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
988 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
989 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
990 tr("Negotiating capabilities (requesting: %1)...").arg(_capsQueued.join(", ")));
994 void CoreNetwork::sendNextCap()
996 if (capNegotiationInProgress()) {
997 // Request the next capability and remove it from the list
998 // Handle one at a time so one capability failing won't NAK all of 'em
999 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCap())));
1001 // No pending desired capabilities, capability negotiation finished
1002 // If SASL requested but not available, print a warning
1003 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1004 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1005 tr("SASL authentication currently not supported by server"));
1007 if (_capNegotiationActive) {
1008 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1009 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1010 _capNegotiationActive = false;
1013 // If nick registration is already complete, CAP END is not required
1014 if (!_capInitialNegotiationEnded) {
1015 putRawLine(serverEncode(QString("CAP END")));
1016 _capInitialNegotiationEnded = true;
1021 /******** AutoWHO ********/
1023 void CoreNetwork::startAutoWhoCycle()
1025 if (!_autoWhoQueue.isEmpty()) {
1026 _autoWhoCycleTimer.stop();
1029 _autoWhoQueue = channels();
1032 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1034 // Prepend so these new channels/nicks are the first to be checked
1035 // Don't allow duplicates
1036 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1037 _autoWhoQueue.prepend(channelOrNick.toLower());
1039 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1040 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1041 setAutoWhoEnabled(true);
1046 void CoreNetwork::setAutoWhoDelay(int delay)
1048 _autoWhoTimer.setInterval(delay * 1000);
1052 void CoreNetwork::setAutoWhoInterval(int interval)
1054 _autoWhoCycleTimer.setInterval(interval * 1000);
1058 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1060 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1061 _autoWhoTimer.start();
1062 else if (!enabled) {
1063 _autoWhoTimer.stop();
1064 _autoWhoCycleTimer.stop();
1069 void CoreNetwork::sendAutoWho()
1071 // Don't send autowho if there are still some pending
1072 if (_autoWhoPending.count())
1075 while (!_autoWhoQueue.isEmpty()) {
1076 QString chanOrNick = _autoWhoQueue.takeFirst();
1077 // Check if it's a known channel or nick
1078 IrcChannel *ircchan = ircChannel(chanOrNick);
1079 IrcUser *ircuser = ircUser(chanOrNick);
1081 // Apply channel limiting rules
1082 // If using away-notify, don't impose channel size limits in order to capture away
1083 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1084 if (networkConfig()->autoWhoNickLimit() > 0
1085 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1086 && !capEnabled(IrcCap::AWAY_NOTIFY))
1088 _autoWhoPending[chanOrNick.toLower()]++;
1089 } else if (ircuser) {
1090 // Checking a nick, add it to the pending list
1091 _autoWhoPending[ircuser->nick().toLower()]++;
1093 // Not a channel or a nick, skip it
1094 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1097 if (supports("WHOX")) {
1098 // Use WHO extended to poll away users and/or user accounts
1099 // See http://faerion.sourceforge.net/doc/irc/whox.var
1100 // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1101 putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1102 .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1104 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1109 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1110 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1111 // Timer was stopped, means a new cycle is due immediately
1112 // Don't run a new cycle if using away-notify; server will notify as appropriate
1113 _autoWhoCycleTimer.start();
1114 startAutoWhoCycle();
1115 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1116 // Don't run another who cycle if away-notify is enabled
1117 _autoWhoCycleTimer.stop();
1123 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1125 Server server = usedServer();
1126 if (server.sslVerify) {
1127 // Treat the SSL error as a hard error
1128 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1129 "since verification is required");
1130 if (!sslErrors.empty()) {
1131 // Add the error reason if known
1132 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1134 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1136 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1137 // validity, network trouble, etc.
1138 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1140 // Treat the SSL error as a warning, continue to connect anyways
1141 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1142 "since verification is not required");
1143 if (!sslErrors.empty()) {
1144 // Add the error reason if known
1145 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1147 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1149 // Proceed with the connection
1150 socket.ignoreSslErrors();
1157 void CoreNetwork::fillBucketAndProcessQueue()
1159 if (_tokenBucket < _burstSize) {
1163 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1164 writeToSocket(_msgQueue.takeFirst());
1169 void CoreNetwork::writeToSocket(const QByteArray &data)
1172 socket.write("\r\n");
1177 Network::Server CoreNetwork::usedServer() const
1179 if (_lastUsedServerIndex < serverList().count())
1180 return serverList()[_lastUsedServerIndex];
1182 if (!serverList().isEmpty())
1183 return serverList()[0];
1185 return Network::Server();
1189 void CoreNetwork::requestConnect() const
1191 if (connectionState() != Disconnected) {
1192 qWarning() << "Requesting connect while already being connected!";
1195 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1199 void CoreNetwork::requestDisconnect() const
1201 if (connectionState() == Disconnected) {
1202 qWarning() << "Requesting disconnect while not being connected!";
1205 userInputHandler()->handleQuit(BufferInfo(), QString());
1209 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1211 Network::Server currentServer = usedServer();
1212 setNetworkInfo(info);
1213 Core::updateNetwork(coreSession()->user(), info);
1215 // the order of the servers might have changed,
1216 // so we try to find the previously used server
1217 _lastUsedServerIndex = 0;
1218 for (int i = 0; i < serverList().count(); i++) {
1219 Network::Server server = serverList()[i];
1220 if (server.host == currentServer.host && server.port == currentServer.port) {
1221 _lastUsedServerIndex = i;
1228 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1230 QString wrkMsg(message);
1231 QList<QList<QByteArray>> msgsToSend;
1233 // do while (wrkMsg.size() > 0)
1235 // First, check to see if the whole message can be sent at once. The
1236 // cmdGenerator function is passed in by the caller and is used to encode
1237 // and encrypt (if applicable) the message, since different callers might
1238 // want to use different encoding or encode different values.
1239 int splitPos = wrkMsg.size();
1240 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1241 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1243 if (initialOverrun) {
1244 // If the message was too long to be sent, first try splitting it along
1245 // word boundaries with QTextBoundaryFinder.
1246 QString splitMsg(wrkMsg);
1247 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1248 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1249 QList<QByteArray> splitMsgEnc;
1250 int overrun = initialOverrun;
1253 splitPos = qtbf.toPreviousBoundary();
1255 // splitPos==-1 means the QTBF couldn't find a split point at all and
1256 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1257 // the string. Neither one of these works for us.
1259 // If a split point could be found, split the message there, calculate the
1260 // overrun, and continue with the loop.
1261 splitMsg = splitMsg.left(splitPos);
1262 splitMsgEnc = cmdGenerator(splitMsg);
1263 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1266 // If a split point could not be found (the beginning of the message
1267 // is reached without finding a split point short enough to send) and we
1268 // are still in Word mode, switch to Grapheme mode. We also need to restore
1269 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1270 // the previous attempt to find a split point.
1271 if (qtbf.type() == QTextBoundaryFinder::Word) {
1273 splitPos = splitMsg.size();
1274 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1275 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1276 qtbf = graphemeQtbf;
1279 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1280 // This should never happen, but it should be handled anyway.
1281 qWarning() << "Unexpected failure to split message!";
1287 // Once a message of sendable length has been found, remove it from the wrkMsg and
1288 // add it to the list of messages to be sent.
1289 wrkMsg.remove(0, splitPos);
1290 msgsToSend.append(splitMsgEnc);
1293 // If the entire remaining message is short enough to be sent all at once, remove
1294 // it from the wrkMsg and add it to the list of messages to be sent.
1295 wrkMsg.remove(0, splitPos);
1296 msgsToSend.append(initialSplitMsgEnc);
1298 } while (wrkMsg.size() > 0);