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),
43 _previousConnectionAttemptFailed(false),
44 _lastUsedServerIndex(0),
49 _requestedUserModes('-')
51 _autoReconnectTimer.setSingleShot(true);
52 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
54 setPingInterval(networkConfig()->pingInterval());
55 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
57 setAutoWhoDelay(networkConfig()->autoWhoDelay());
58 setAutoWhoInterval(networkConfig()->autoWhoInterval());
60 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
61 foreach(QString chan, channels.keys()) {
62 _channelKeys[chan.toLower()] = channels[chan];
65 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
66 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
67 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
68 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
69 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
71 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
72 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
73 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
74 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
76 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
77 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
78 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
79 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
81 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
82 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
84 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
86 // IRCv3 capability handling
87 // These react to CAP messages from the server
88 connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
89 connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
90 connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
92 if (Quassel::isOptionSet("oidentd")) {
93 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
94 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
99 CoreNetwork::~CoreNetwork()
101 if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
102 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
103 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
104 delete _userInputHandler;
108 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
110 if (!bufferName.isEmpty()) {
111 IrcChannel *channel = ircChannel(bufferName);
113 return channel->decodeString(string);
115 return decodeString(string);
119 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
121 IrcUser *user = ircUser(userNick);
123 return user->decodeString(string);
124 return decodeString(string);
128 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
130 if (!bufferName.isEmpty()) {
131 IrcChannel *channel = ircChannel(bufferName);
133 return channel->encodeString(string);
135 return encodeString(string);
139 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
141 IrcUser *user = ircUser(userNick);
143 return user->encodeString(string);
144 return encodeString(string);
148 void CoreNetwork::connectToIrc(bool reconnecting)
150 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
151 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
152 if (unlimitedReconnectRetries())
153 _autoReconnectCount = -1;
155 _autoReconnectCount = autoReconnectRetries();
157 if (serverList().isEmpty()) {
158 qWarning() << "Server list empty, ignoring connect request!";
161 CoreIdentity *identity = identityPtr();
163 qWarning() << "Invalid identity configures, ignoring connect request!";
167 // cleaning up old quit reason
170 // Reset capability negotiation tracking, also handling server changes during reconnect
173 _capNegotiationActive = false;
174 _capInitialNegotiationEnded = false;
176 // use a random server?
177 if (useRandomServer()) {
178 _lastUsedServerIndex = qrand() % serverList().size();
180 else if (_previousConnectionAttemptFailed) {
181 // cycle to next server if previous connection attempt failed
182 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
183 if (++_lastUsedServerIndex >= serverList().size()) {
184 _lastUsedServerIndex = 0;
187 _previousConnectionAttemptFailed = false;
189 Server server = usedServer();
190 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
191 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
193 if (server.useProxy) {
194 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
195 socket.setProxy(proxy);
198 socket.setProxy(QNetworkProxy::NoProxy);
203 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
204 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
205 QHostInfo::fromName(server.host);
209 CoreIdentity *identity = identityPtr();
211 socket.setLocalCertificate(identity->sslCert());
212 socket.setPrivateKey(identity->sslKey());
214 socket.connectToHostEncrypted(server.host, server.port);
217 socket.connectToHost(server.host, server.port);
220 socket.connectToHost(server.host, server.port);
225 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
228 _quitRequested = requested; // see socketDisconnected();
229 if (!withReconnect) {
230 _autoReconnectTimer.stop();
231 _autoReconnectCount = 0; // prohibiting auto reconnect
233 disablePingTimeout();
240 awayMsg = me_->awayMessage();
241 Core::setAwayMessage(userId(), networkId(), awayMsg);
244 if (reason.isEmpty() && identityPtr())
245 _quitReason = identityPtr()->quitReason();
247 _quitReason = reason;
249 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
250 if (socket.state() == QAbstractSocket::UnconnectedState) {
251 socketDisconnected();
253 if (socket.state() == QAbstractSocket::ConnectedState) {
254 userInputHandler()->issueQuit(_quitReason, forceImmediate);
258 if (requested || withReconnect) {
259 // the irc server has 10 seconds to close the socket
260 _socketCloseTimer.start(10000);
266 void CoreNetwork::userInput(BufferInfo buf, QString msg)
268 userInputHandler()->handleUserInput(buf, msg);
272 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
274 if (_tokenBucket > 0) {
278 _msgQueue.prepend(s);
286 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
290 if (!prefix.isEmpty())
291 msg += ":" + prefix + " ";
292 msg += cmd.toUpper().toLatin1();
294 for (int i = 0; i < params.size(); i++) {
297 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
303 putRawLine(msg, prepend);
307 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
309 QListIterator<QList<QByteArray>> i(params);
310 while (i.hasNext()) {
311 QList<QByteArray> msg = i.next();
312 putCmd(cmd, msg, prefix, prependAll);
317 void CoreNetwork::setChannelJoined(const QString &channel)
319 queueAutoWhoOneshot(channel); // check this new channel first
321 Core::setChannelPersistent(userId(), networkId(), channel, true);
322 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
326 void CoreNetwork::setChannelParted(const QString &channel)
328 removeChannelKey(channel);
329 _autoWhoQueue.removeAll(channel.toLower());
330 _autoWhoPending.remove(channel.toLower());
332 Core::setChannelPersistent(userId(), networkId(), channel, false);
336 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
339 removeChannelKey(channel);
342 _channelKeys[channel.toLower()] = key;
347 void CoreNetwork::removeChannelKey(const QString &channel)
349 _channelKeys.remove(channel.toLower());
354 Cipher *CoreNetwork::cipher(const QString &target)
356 if (target.isEmpty())
359 if (!Cipher::neededFeaturesAvailable())
362 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
364 return channel->cipher();
366 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
368 return user->cipher();
369 } else if (!isChannelName(target)) {
370 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
376 QByteArray CoreNetwork::cipherKey(const QString &target) const
378 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
380 return c->cipher()->key();
382 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
384 return u->cipher()->key();
390 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
392 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
394 c->setEncrypted(c->cipher()->setKey(key));
398 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
399 if (!u && !isChannelName(target))
400 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
403 u->setEncrypted(u->cipher()->setKey(key));
409 bool CoreNetwork::cipherUsesCBC(const QString &target)
411 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
413 return c->cipher()->usesCBC();
414 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
416 return u->cipher()->usesCBC();
420 #endif /* HAVE_QCA2 */
422 bool CoreNetwork::setAutoWhoDone(const QString &channel)
424 QString chan = channel.toLower();
425 if (_autoWhoPending.value(chan, 0) <= 0)
427 if (--_autoWhoPending[chan] <= 0)
428 _autoWhoPending.remove(chan);
433 void CoreNetwork::setMyNick(const QString &mynick)
435 Network::setMyNick(mynick);
436 if (connectionState() == Network::Initializing)
437 networkInitialized();
441 void CoreNetwork::socketHasData()
443 while (socket.canReadLine()) {
444 QByteArray s = socket.readLine();
445 if (s.endsWith("\r\n"))
447 else if (s.endsWith("\n"))
449 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
450 event->setTimestamp(QDateTime::currentDateTimeUtc());
451 emit newEvent(event);
456 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
458 if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
461 _previousConnectionAttemptFailed = true;
462 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
463 emit connectionError(socket.errorString());
464 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
465 emitConnectionError(socket.errorString());
466 if (socket.state() < QAbstractSocket::ConnectedState) {
467 socketDisconnected();
472 void CoreNetwork::socketInitialized()
474 CoreIdentity *identity = identityPtr();
476 qCritical() << "Identity invalid!";
481 Server server = usedServer();
484 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
485 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
486 if (!server.useSsl || !socket.isEncrypted()) {
487 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
490 if (server.useSsl && !socket.isEncrypted()) {
491 // We'll finish setup once we're encrypted, and called again
495 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
498 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
500 // TokenBucket to avoid sending too much at once
501 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
503 _tokenBucket = _burstSize; // init with a full bucket
504 _tokenBucketTimer.start(_messageDelay);
506 // Request capabilities as per IRCv3.2 specifications
507 // Older servers should ignore this; newer servers won't downgrade to RFC1459
508 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
509 putRawLine(serverEncode(QString("CAP LS 302")));
511 if (!server.password.isEmpty()) {
512 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
515 if (identity->nicks().isEmpty()) {
517 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
520 nick = identity->nicks()[0];
522 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
523 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
527 void CoreNetwork::socketDisconnected()
529 disablePingTimeout();
532 _autoWhoCycleTimer.stop();
533 _autoWhoTimer.stop();
534 _autoWhoQueue.clear();
535 _autoWhoPending.clear();
537 _socketCloseTimer.stop();
539 _tokenBucketTimer.stop();
543 foreach(QString channel, me_->channels())
544 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
548 emit disconnected(networkId());
549 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
550 if (_quitRequested) {
551 _quitRequested = false;
552 setConnectionState(Network::Disconnected);
553 Core::setNetworkConnected(userId(), networkId(), false);
555 else if (_autoReconnectCount != 0) {
556 setConnectionState(Network::Reconnecting);
557 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
558 doAutoReconnect(); // first try is immediate
560 _autoReconnectTimer.start();
565 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
567 Network::ConnectionState state;
568 switch (socketState) {
569 case QAbstractSocket::UnconnectedState:
570 state = Network::Disconnected;
571 socketDisconnected();
573 case QAbstractSocket::HostLookupState:
574 case QAbstractSocket::ConnectingState:
575 state = Network::Connecting;
577 case QAbstractSocket::ConnectedState:
578 state = Network::Initializing;
580 case QAbstractSocket::ClosingState:
581 state = Network::Disconnecting;
584 state = Network::Disconnected;
586 setConnectionState(state);
590 void CoreNetwork::networkInitialized()
592 setConnectionState(Network::Initialized);
594 _quitRequested = false;
596 if (useAutoReconnect()) {
598 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
601 // restore away state
602 QString awayMsg = Core::awayMessage(userId(), networkId());
603 if (!awayMsg.isEmpty())
604 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
610 if (networkConfig()->autoWhoEnabled()) {
611 _autoWhoCycleTimer.start();
612 _autoWhoTimer.start();
613 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
616 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
617 Core::setNetworkConnected(userId(), networkId(), true);
621 void CoreNetwork::sendPerform()
623 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
626 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
627 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
630 // restore old user modes if server default mode is set.
633 if (!me_->userModes().isEmpty()) {
637 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
638 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
643 foreach(QString line, perform()) {
644 if (!line.isEmpty()) userInput(statusBuf, line);
647 // rejoin channels we've been in
648 if (rejoinChannels()) {
649 QStringList channels, keys;
650 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
651 QString key = channelKey(chan);
652 if (!key.isEmpty()) {
653 channels.prepend(chan);
657 channels.append(chan);
660 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
661 if (!joinString.isEmpty())
662 userInputHandler()->handleJoin(statusBuf, joinString);
667 void CoreNetwork::restoreUserModes()
672 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
673 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
675 QString modesDelta = Core::userModes(userId(), networkId());
676 QString currentModes = me_->userModes();
678 QString addModes, removeModes;
679 if (modesDelta.contains('-')) {
680 addModes = modesDelta.section('-', 0, 0);
681 removeModes = modesDelta.section('-', 1);
684 addModes = modesDelta;
687 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
688 if (currentModes.isEmpty())
689 removeModes = QString();
691 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
693 if (addModes.isEmpty() && removeModes.isEmpty())
696 if (!addModes.isEmpty())
697 addModes = '+' + addModes;
698 if (!removeModes.isEmpty())
699 removeModes = '-' + removeModes;
701 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
702 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
706 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
712 for (int i = 0; i < requestedModes.length(); i++) {
713 if (requestedModes[i] == '+') {
717 if (requestedModes[i] == '-') {
722 addModes += requestedModes[i];
725 removeModes += requestedModes[i];
729 QString addModesOld = _requestedUserModes.section('-', 0, 0);
730 QString removeModesOld = _requestedUserModes.section('-', 1);
732 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
733 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
734 addModes += addModesOld;
736 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
737 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
738 removeModes += removeModesOld;
740 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
744 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
746 QString persistentUserModes = Core::userModes(userId(), networkId());
748 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
749 QString requestedRemove = _requestedUserModes.section('-', 1);
751 QString persistentAdd, persistentRemove;
752 if (persistentUserModes.contains('-')) {
753 persistentAdd = persistentUserModes.section('-', 0, 0);
754 persistentRemove = persistentUserModes.section('-', 1);
757 persistentAdd = persistentUserModes;
760 // remove modes we didn't issue
761 if (requestedAdd.isEmpty())
762 addModes = QString();
764 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
766 if (requestedRemove.isEmpty())
767 removeModes = QString();
769 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
772 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
773 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
776 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
777 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
779 // update issued mode list
780 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
781 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
782 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
784 persistentAdd += addModes;
785 persistentRemove += removeModes;
786 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
790 void CoreNetwork::resetPersistentModes()
792 _requestedUserModes = QString('-');
793 Core::setUserModes(userId(), networkId(), QString());
797 void CoreNetwork::setUseAutoReconnect(bool use)
799 Network::setUseAutoReconnect(use);
801 _autoReconnectTimer.stop();
805 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
807 Network::setAutoReconnectInterval(interval);
808 _autoReconnectTimer.setInterval(interval * 1000);
812 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
814 Network::setAutoReconnectRetries(retries);
815 if (_autoReconnectCount != 0) {
816 if (unlimitedReconnectRetries())
817 _autoReconnectCount = -1;
819 _autoReconnectCount = autoReconnectRetries();
824 void CoreNetwork::doAutoReconnect()
826 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
827 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
830 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
831 _autoReconnectCount--; // -2 means we delay the next reconnect
836 void CoreNetwork::sendPing()
838 uint now = QDateTime::currentDateTime().toTime_t();
839 if (_pingCount != 0) {
840 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
841 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
843 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
844 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
845 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
846 // and unable to even handle a ping answer. So we ignore those misses.
847 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
852 // Don't send pings until the network is initialized
854 userInputHandler()->handlePing(BufferInfo(), QString());
859 void CoreNetwork::enablePingTimeout(bool enable)
862 disablePingTimeout();
865 if (networkConfig()->pingTimeoutEnabled())
871 void CoreNetwork::disablePingTimeout()
879 void CoreNetwork::setPingInterval(int interval)
881 _pingTimer.setInterval(interval * 1000);
884 /******** IRCv3 Capability Negotiation ********/
886 void CoreNetwork::serverCapAdded(const QString &capability)
888 // Check if it's a known capability; if so, add it to the list
889 // Handle special cases first
890 if (capability == IrcCap::SASL) {
891 // Only request SASL if it's enabled
892 if (networkInfo().useSasl)
893 queueCap(capability);
894 } else if (IrcCap::knownCaps.contains(capability)) {
895 // Handling for general known capabilities
896 queueCap(capability);
900 void CoreNetwork::serverCapAcknowledged(const QString &capability)
902 // This may be called multiple times in certain situations.
904 // Handle core-side configuration
905 if (capability == IrcCap::AWAY_NOTIFY) {
906 // away-notify enabled, stop the autoWho timers, handle manually
907 setAutoWhoEnabled(false);
910 // Handle capabilities that require further messages sent to the IRC server
911 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
912 if (capability == IrcCap::SASL) {
913 // If SASL mechanisms specified, limit to what's accepted for authentication
914 // if the current identity has a cert set, use SASL EXTERNAL
917 if (!identityPtr()->sslCert().isNull()) {
918 if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::EXTERNAL)) {
919 // EXTERNAL authentication supported, send request
920 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
922 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
923 tr("SASL EXTERNAL authentication not supported"));
928 if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::PLAIN)) {
929 // PLAIN authentication supported, send request
930 // Only working with PLAIN atm, blowfish later
931 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
933 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
934 tr("SASL PLAIN authentication not supported"));
943 void CoreNetwork::serverCapRemoved(const QString &capability)
945 // This may be called multiple times in certain situations.
947 // Handle special cases here
948 if (capability == IrcCap::AWAY_NOTIFY) {
949 // away-notify disabled, enable autoWho according to configuration
950 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
954 void CoreNetwork::queueCap(const QString &capability)
956 // IRCv3 specs all use lowercase capability names
957 QString _capLowercase = capability.toLower();
958 if (!_capsQueued.contains(_capLowercase)) {
959 _capsQueued.append(_capLowercase);
963 QString CoreNetwork::takeQueuedCap()
965 if (!_capsQueued.empty()) {
966 return _capsQueued.takeFirst();
972 void CoreNetwork::beginCapNegotiation()
974 // Don't begin negotiation if no capabilities are queued to request
975 if (!capNegotiationInProgress())
978 _capNegotiationActive = true;
979 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
980 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
981 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
982 tr("Negotiating capabilities (requesting: %1)...").arg(_capsQueued.join(", ")));
986 void CoreNetwork::sendNextCap()
988 if (capNegotiationInProgress()) {
989 // Request the next capability and remove it from the list
990 // Handle one at a time so one capability failing won't NAK all of 'em
991 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCap())));
993 // No pending desired capabilities, capability negotiation finished
994 // If SASL requested but not available, print a warning
995 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
996 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
997 tr("SASL authentication currently not supported by server"));
999 if (_capNegotiationActive) {
1000 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1001 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1002 _capNegotiationActive = false;
1005 // If nick registration is already complete, CAP END is not required
1006 if (!_capInitialNegotiationEnded) {
1007 putRawLine(serverEncode(QString("CAP END")));
1008 _capInitialNegotiationEnded = true;
1013 /******** AutoWHO ********/
1015 void CoreNetwork::startAutoWhoCycle()
1017 if (!_autoWhoQueue.isEmpty()) {
1018 _autoWhoCycleTimer.stop();
1021 _autoWhoQueue = channels();
1024 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1026 // Prepend so these new channels/nicks are the first to be checked
1027 // Don't allow duplicates
1028 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1029 _autoWhoQueue.prepend(channelOrNick.toLower());
1031 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1032 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1033 setAutoWhoEnabled(true);
1038 void CoreNetwork::setAutoWhoDelay(int delay)
1040 _autoWhoTimer.setInterval(delay * 1000);
1044 void CoreNetwork::setAutoWhoInterval(int interval)
1046 _autoWhoCycleTimer.setInterval(interval * 1000);
1050 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1052 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1053 _autoWhoTimer.start();
1054 else if (!enabled) {
1055 _autoWhoTimer.stop();
1056 _autoWhoCycleTimer.stop();
1061 void CoreNetwork::sendAutoWho()
1063 // Don't send autowho if there are still some pending
1064 if (_autoWhoPending.count())
1067 while (!_autoWhoQueue.isEmpty()) {
1068 QString chanOrNick = _autoWhoQueue.takeFirst();
1069 // Check if it's a known channel or nick
1070 IrcChannel *ircchan = ircChannel(chanOrNick);
1071 IrcUser *ircuser = ircUser(chanOrNick);
1073 // Apply channel limiting rules
1074 // If using away-notify, don't impose channel size limits in order to capture away
1075 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1076 if (networkConfig()->autoWhoNickLimit() > 0
1077 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1078 && !capEnabled(IrcCap::AWAY_NOTIFY))
1080 _autoWhoPending[chanOrNick.toLower()]++;
1081 } else if (ircuser) {
1082 // Checking a nick, add it to the pending list
1083 _autoWhoPending[ircuser->nick().toLower()]++;
1085 // Not a channel or a nick, skip it
1086 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1089 if (supports("WHOX")) {
1090 // Use WHO extended to poll away users and/or user accounts
1091 // See http://faerion.sourceforge.net/doc/irc/whox.var
1092 // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1093 putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1094 .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1096 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1101 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1102 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1103 // Timer was stopped, means a new cycle is due immediately
1104 // Don't run a new cycle if using away-notify; server will notify as appropriate
1105 _autoWhoCycleTimer.start();
1106 startAutoWhoCycle();
1107 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1108 // Don't run another who cycle if away-notify is enabled
1109 _autoWhoCycleTimer.stop();
1115 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1117 Server server = usedServer();
1118 if (server.sslVerify) {
1119 // Treat the SSL error as a hard error
1120 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1121 "since verification is required");
1122 if (!sslErrors.empty()) {
1123 // Add the error reason if known
1124 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1126 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1128 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1129 // validity, network trouble, etc.
1130 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1132 // Treat the SSL error as a warning, continue to connect anyways
1133 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1134 "since verification is not required");
1135 if (!sslErrors.empty()) {
1136 // Add the error reason if known
1137 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1139 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1141 // Proceed with the connection
1142 socket.ignoreSslErrors();
1149 void CoreNetwork::fillBucketAndProcessQueue()
1151 if (_tokenBucket < _burstSize) {
1155 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1156 writeToSocket(_msgQueue.takeFirst());
1161 void CoreNetwork::writeToSocket(const QByteArray &data)
1164 socket.write("\r\n");
1169 Network::Server CoreNetwork::usedServer() const
1171 if (_lastUsedServerIndex < serverList().count())
1172 return serverList()[_lastUsedServerIndex];
1174 if (!serverList().isEmpty())
1175 return serverList()[0];
1177 return Network::Server();
1181 void CoreNetwork::requestConnect() const
1183 if (connectionState() != Disconnected) {
1184 qWarning() << "Requesting connect while already being connected!";
1187 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1191 void CoreNetwork::requestDisconnect() const
1193 if (connectionState() == Disconnected) {
1194 qWarning() << "Requesting disconnect while not being connected!";
1197 userInputHandler()->handleQuit(BufferInfo(), QString());
1201 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1203 Network::Server currentServer = usedServer();
1204 setNetworkInfo(info);
1205 Core::updateNetwork(coreSession()->user(), info);
1207 // the order of the servers might have changed,
1208 // so we try to find the previously used server
1209 _lastUsedServerIndex = 0;
1210 for (int i = 0; i < serverList().count(); i++) {
1211 Network::Server server = serverList()[i];
1212 if (server.host == currentServer.host && server.port == currentServer.port) {
1213 _lastUsedServerIndex = i;
1220 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1222 QString wrkMsg(message);
1223 QList<QList<QByteArray>> msgsToSend;
1225 // do while (wrkMsg.size() > 0)
1227 // First, check to see if the whole message can be sent at once. The
1228 // cmdGenerator function is passed in by the caller and is used to encode
1229 // and encrypt (if applicable) the message, since different callers might
1230 // want to use different encoding or encode different values.
1231 int splitPos = wrkMsg.size();
1232 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1233 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1235 if (initialOverrun) {
1236 // If the message was too long to be sent, first try splitting it along
1237 // word boundaries with QTextBoundaryFinder.
1238 QString splitMsg(wrkMsg);
1239 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1240 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1241 QList<QByteArray> splitMsgEnc;
1242 int overrun = initialOverrun;
1245 splitPos = qtbf.toPreviousBoundary();
1247 // splitPos==-1 means the QTBF couldn't find a split point at all and
1248 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1249 // the string. Neither one of these works for us.
1251 // If a split point could be found, split the message there, calculate the
1252 // overrun, and continue with the loop.
1253 splitMsg = splitMsg.left(splitPos);
1254 splitMsgEnc = cmdGenerator(splitMsg);
1255 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1258 // If a split point could not be found (the beginning of the message
1259 // is reached without finding a split point short enough to send) and we
1260 // are still in Word mode, switch to Grapheme mode. We also need to restore
1261 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1262 // the previous attempt to find a split point.
1263 if (qtbf.type() == QTextBoundaryFinder::Word) {
1265 splitPos = splitMsg.size();
1266 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1267 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1268 qtbf = graphemeQtbf;
1271 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1272 // This should never happen, but it should be handled anyway.
1273 qWarning() << "Unexpected failure to split message!";
1279 // Once a message of sendable length has been found, remove it from the wrkMsg and
1280 // add it to the list of messages to be sent.
1281 wrkMsg.remove(0, splitPos);
1282 msgsToSend.append(splitMsgEnc);
1285 // If the entire remaining message is short enough to be sent all at once, remove
1286 // it from the wrkMsg and add it to the list of messages to be sent.
1287 wrkMsg.remove(0, splitPos);
1288 msgsToSend.append(initialSplitMsgEnc);
1290 } while (wrkMsg.size() > 0);