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
200 _capNegotiationActive = false;
201 _capInitialNegotiationEnded = false;
203 // use a random server?
204 if (useRandomServer()) {
205 _lastUsedServerIndex = qrand() % serverList().size();
207 else if (_previousConnectionAttemptFailed) {
208 // cycle to next server if previous connection attempt failed
209 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
210 if (++_lastUsedServerIndex >= serverList().size()) {
211 _lastUsedServerIndex = 0;
214 _previousConnectionAttemptFailed = false;
216 Server server = usedServer();
217 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
218 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
220 if (server.useProxy) {
221 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
222 socket.setProxy(proxy);
225 socket.setProxy(QNetworkProxy::NoProxy);
230 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
231 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
232 QHostInfo::fromName(server.host);
236 CoreIdentity *identity = identityPtr();
238 socket.setLocalCertificate(identity->sslCert());
239 socket.setPrivateKey(identity->sslKey());
241 socket.connectToHostEncrypted(server.host, server.port);
244 socket.connectToHost(server.host, server.port);
247 socket.connectToHost(server.host, server.port);
252 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
255 // Disconnecting from the network, should expect a socket close or error
256 _disconnectExpected = true;
257 _quitRequested = requested; // see socketDisconnected();
258 if (!withReconnect) {
259 _autoReconnectTimer.stop();
260 _autoReconnectCount = 0; // prohibiting auto reconnect
262 disablePingTimeout();
269 awayMsg = me_->awayMessage();
270 Core::setAwayMessage(userId(), networkId(), awayMsg);
273 if (reason.isEmpty() && identityPtr())
274 _quitReason = identityPtr()->quitReason();
276 _quitReason = reason;
278 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
279 if (socket.state() == QAbstractSocket::UnconnectedState) {
280 socketDisconnected();
282 if (socket.state() == QAbstractSocket::ConnectedState) {
283 userInputHandler()->issueQuit(_quitReason, forceImmediate);
287 if (requested || withReconnect) {
288 // the irc server has 10 seconds to close the socket
289 _socketCloseTimer.start(10000);
295 void CoreNetwork::userInput(BufferInfo buf, QString msg)
297 userInputHandler()->handleUserInput(buf, msg);
301 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
303 if (_tokenBucket > 0) {
307 _msgQueue.prepend(s);
315 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
319 if (!prefix.isEmpty())
320 msg += ":" + prefix + " ";
321 msg += cmd.toUpper().toLatin1();
323 for (int i = 0; i < params.size(); i++) {
326 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
332 putRawLine(msg, prepend);
336 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
338 QListIterator<QList<QByteArray>> i(params);
339 while (i.hasNext()) {
340 QList<QByteArray> msg = i.next();
341 putCmd(cmd, msg, prefix, prependAll);
346 void CoreNetwork::setChannelJoined(const QString &channel)
348 queueAutoWhoOneshot(channel); // check this new channel first
350 Core::setChannelPersistent(userId(), networkId(), channel, true);
351 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
355 void CoreNetwork::setChannelParted(const QString &channel)
357 removeChannelKey(channel);
358 _autoWhoQueue.removeAll(channel.toLower());
359 _autoWhoPending.remove(channel.toLower());
361 Core::setChannelPersistent(userId(), networkId(), channel, false);
365 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
368 removeChannelKey(channel);
371 _channelKeys[channel.toLower()] = key;
376 void CoreNetwork::removeChannelKey(const QString &channel)
378 _channelKeys.remove(channel.toLower());
383 Cipher *CoreNetwork::cipher(const QString &target)
385 if (target.isEmpty())
388 if (!Cipher::neededFeaturesAvailable())
391 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
393 return channel->cipher();
395 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
397 return user->cipher();
398 } else if (!isChannelName(target)) {
399 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
405 QByteArray CoreNetwork::cipherKey(const QString &target) const
407 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
409 return c->cipher()->key();
411 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
413 return u->cipher()->key();
419 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
421 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
423 c->setEncrypted(c->cipher()->setKey(key));
427 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
428 if (!u && !isChannelName(target))
429 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
432 u->setEncrypted(u->cipher()->setKey(key));
438 bool CoreNetwork::cipherUsesCBC(const QString &target)
440 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
442 return c->cipher()->usesCBC();
443 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
445 return u->cipher()->usesCBC();
449 #endif /* HAVE_QCA2 */
451 bool CoreNetwork::setAutoWhoDone(const QString &channel)
453 QString chan = channel.toLower();
454 if (_autoWhoPending.value(chan, 0) <= 0)
456 if (--_autoWhoPending[chan] <= 0)
457 _autoWhoPending.remove(chan);
462 void CoreNetwork::setMyNick(const QString &mynick)
464 Network::setMyNick(mynick);
465 if (connectionState() == Network::Initializing)
466 networkInitialized();
470 void CoreNetwork::socketHasData()
472 while (socket.canReadLine()) {
473 QByteArray s = socket.readLine();
474 if (s.endsWith("\r\n"))
476 else if (s.endsWith("\n"))
478 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
479 event->setTimestamp(QDateTime::currentDateTimeUtc());
480 emit newEvent(event);
485 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
487 // Ignore socket closed errors if expected
488 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
492 _previousConnectionAttemptFailed = true;
493 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
494 emit connectionError(socket.errorString());
495 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
496 emitConnectionError(socket.errorString());
497 if (socket.state() < QAbstractSocket::ConnectedState) {
498 socketDisconnected();
503 void CoreNetwork::socketInitialized()
505 CoreIdentity *identity = identityPtr();
507 qCritical() << "Identity invalid!";
512 Server server = usedServer();
515 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
516 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
517 if (!server.useSsl || !socket.isEncrypted()) {
518 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
521 if (server.useSsl && !socket.isEncrypted()) {
522 // We'll finish setup once we're encrypted, and called again
526 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
529 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
531 // TokenBucket to avoid sending too much at once
532 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
534 _tokenBucket = _burstSize; // init with a full bucket
535 _tokenBucketTimer.start(_messageDelay);
537 // Request capabilities as per IRCv3.2 specifications
538 // Older servers should ignore this; newer servers won't downgrade to RFC1459
539 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
540 putRawLine(serverEncode(QString("CAP LS 302")));
542 if (!server.password.isEmpty()) {
543 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
546 if (identity->nicks().isEmpty()) {
548 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
551 nick = identity->nicks()[0];
553 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
554 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
558 void CoreNetwork::socketDisconnected()
560 disablePingTimeout();
563 _autoWhoCycleTimer.stop();
564 _autoWhoTimer.stop();
565 _autoWhoQueue.clear();
566 _autoWhoPending.clear();
568 _socketCloseTimer.stop();
570 _tokenBucketTimer.stop();
574 foreach(QString channel, me_->channels())
575 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
579 emit disconnected(networkId());
580 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
581 // Reset disconnect expectations
582 _disconnectExpected = false;
583 if (_quitRequested) {
584 _quitRequested = false;
585 setConnectionState(Network::Disconnected);
586 Core::setNetworkConnected(userId(), networkId(), false);
588 else if (_autoReconnectCount != 0) {
589 setConnectionState(Network::Reconnecting);
590 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
591 doAutoReconnect(); // first try is immediate
593 _autoReconnectTimer.start();
598 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
600 Network::ConnectionState state;
601 switch (socketState) {
602 case QAbstractSocket::UnconnectedState:
603 state = Network::Disconnected;
604 socketDisconnected();
606 case QAbstractSocket::HostLookupState:
607 case QAbstractSocket::ConnectingState:
608 state = Network::Connecting;
610 case QAbstractSocket::ConnectedState:
611 state = Network::Initializing;
613 case QAbstractSocket::ClosingState:
614 state = Network::Disconnecting;
617 state = Network::Disconnected;
619 setConnectionState(state);
623 void CoreNetwork::networkInitialized()
625 setConnectionState(Network::Initialized);
627 _disconnectExpected = false;
628 _quitRequested = false;
630 if (useAutoReconnect()) {
632 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
635 // restore away state
636 QString awayMsg = Core::awayMessage(userId(), networkId());
637 if (!awayMsg.isEmpty())
638 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
644 if (networkConfig()->autoWhoEnabled()) {
645 _autoWhoCycleTimer.start();
646 _autoWhoTimer.start();
647 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
650 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
651 Core::setNetworkConnected(userId(), networkId(), true);
655 void CoreNetwork::sendPerform()
657 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
660 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
661 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
664 // restore old user modes if server default mode is set.
667 if (!me_->userModes().isEmpty()) {
671 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
672 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
677 foreach(QString line, perform()) {
678 if (!line.isEmpty()) userInput(statusBuf, line);
681 // rejoin channels we've been in
682 if (rejoinChannels()) {
683 QStringList channels, keys;
684 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
685 QString key = channelKey(chan);
686 if (!key.isEmpty()) {
687 channels.prepend(chan);
691 channels.append(chan);
694 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
695 if (!joinString.isEmpty())
696 userInputHandler()->handleJoin(statusBuf, joinString);
701 void CoreNetwork::restoreUserModes()
706 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
707 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
709 QString modesDelta = Core::userModes(userId(), networkId());
710 QString currentModes = me_->userModes();
712 QString addModes, removeModes;
713 if (modesDelta.contains('-')) {
714 addModes = modesDelta.section('-', 0, 0);
715 removeModes = modesDelta.section('-', 1);
718 addModes = modesDelta;
721 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
722 if (currentModes.isEmpty())
723 removeModes = QString();
725 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
727 if (addModes.isEmpty() && removeModes.isEmpty())
730 if (!addModes.isEmpty())
731 addModes = '+' + addModes;
732 if (!removeModes.isEmpty())
733 removeModes = '-' + removeModes;
735 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
736 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
740 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
746 for (int i = 0; i < requestedModes.length(); i++) {
747 if (requestedModes[i] == '+') {
751 if (requestedModes[i] == '-') {
756 addModes += requestedModes[i];
759 removeModes += requestedModes[i];
763 QString addModesOld = _requestedUserModes.section('-', 0, 0);
764 QString removeModesOld = _requestedUserModes.section('-', 1);
766 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
767 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
768 addModes += addModesOld;
770 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
771 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
772 removeModes += removeModesOld;
774 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
778 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
780 QString persistentUserModes = Core::userModes(userId(), networkId());
782 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
783 QString requestedRemove = _requestedUserModes.section('-', 1);
785 QString persistentAdd, persistentRemove;
786 if (persistentUserModes.contains('-')) {
787 persistentAdd = persistentUserModes.section('-', 0, 0);
788 persistentRemove = persistentUserModes.section('-', 1);
791 persistentAdd = persistentUserModes;
794 // remove modes we didn't issue
795 if (requestedAdd.isEmpty())
796 addModes = QString();
798 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
800 if (requestedRemove.isEmpty())
801 removeModes = QString();
803 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
806 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
807 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
810 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
811 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
813 // update issued mode list
814 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
815 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
816 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
818 persistentAdd += addModes;
819 persistentRemove += removeModes;
820 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
824 void CoreNetwork::resetPersistentModes()
826 _requestedUserModes = QString('-');
827 Core::setUserModes(userId(), networkId(), QString());
831 void CoreNetwork::setUseAutoReconnect(bool use)
833 Network::setUseAutoReconnect(use);
835 _autoReconnectTimer.stop();
839 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
841 Network::setAutoReconnectInterval(interval);
842 _autoReconnectTimer.setInterval(interval * 1000);
846 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
848 Network::setAutoReconnectRetries(retries);
849 if (_autoReconnectCount != 0) {
850 if (unlimitedReconnectRetries())
851 _autoReconnectCount = -1;
853 _autoReconnectCount = autoReconnectRetries();
858 void CoreNetwork::doAutoReconnect()
860 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
861 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
864 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
865 _autoReconnectCount--; // -2 means we delay the next reconnect
870 void CoreNetwork::sendPing()
872 uint now = QDateTime::currentDateTime().toTime_t();
873 if (_pingCount != 0) {
874 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
875 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
877 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
878 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
879 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
880 // and unable to even handle a ping answer. So we ignore those misses.
881 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
886 // Don't send pings until the network is initialized
888 userInputHandler()->handlePing(BufferInfo(), QString());
893 void CoreNetwork::enablePingTimeout(bool enable)
896 disablePingTimeout();
899 if (networkConfig()->pingTimeoutEnabled())
905 void CoreNetwork::disablePingTimeout()
913 void CoreNetwork::setPingInterval(int interval)
915 _pingTimer.setInterval(interval * 1000);
918 /******** IRCv3 Capability Negotiation ********/
920 void CoreNetwork::serverCapAdded(const QString &capability)
922 // Check if it's a known capability; if so, add it to the list
923 // Handle special cases first
924 if (capability == IrcCap::SASL) {
925 // Only request SASL if it's enabled
926 if (networkInfo().useSasl)
927 queueCap(capability);
928 } else if (IrcCap::knownCaps.contains(capability)) {
929 // Handling for general known capabilities
930 queueCap(capability);
934 void CoreNetwork::serverCapAcknowledged(const QString &capability)
936 // This may be called multiple times in certain situations.
938 // Handle core-side configuration
939 if (capability == IrcCap::AWAY_NOTIFY) {
940 // away-notify enabled, stop the autoWho timers, handle manually
941 setAutoWhoEnabled(false);
944 // Handle capabilities that require further messages sent to the IRC server
945 // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
946 if (capability == IrcCap::SASL) {
947 // If SASL mechanisms specified, limit to what's accepted for authentication
948 // if the current identity has a cert set, use SASL EXTERNAL
951 if (!identityPtr()->sslCert().isNull()) {
952 if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::EXTERNAL)) {
953 // EXTERNAL authentication supported, send request
954 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
956 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
957 tr("SASL EXTERNAL authentication not supported"));
962 if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::PLAIN)) {
963 // PLAIN authentication supported, send request
964 // Only working with PLAIN atm, blowfish later
965 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
967 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
968 tr("SASL PLAIN authentication not supported"));
977 void CoreNetwork::serverCapRemoved(const QString &capability)
979 // This may be called multiple times in certain situations.
981 // Handle special cases here
982 if (capability == IrcCap::AWAY_NOTIFY) {
983 // away-notify disabled, enable autoWho according to configuration
984 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
988 void CoreNetwork::queueCap(const QString &capability)
990 // IRCv3 specs all use lowercase capability names
991 QString _capLowercase = capability.toLower();
992 if (!_capsQueued.contains(_capLowercase)) {
993 _capsQueued.append(_capLowercase);
997 QString CoreNetwork::takeQueuedCap()
999 if (!_capsQueued.empty()) {
1000 return _capsQueued.takeFirst();
1006 void CoreNetwork::beginCapNegotiation()
1008 // Don't begin negotiation if no capabilities are queued to request
1009 if (!capNegotiationInProgress()) {
1010 // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1011 // normal connection.
1012 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1013 endCapNegotiation();
1017 _capNegotiationActive = true;
1018 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1019 tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1020 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1021 tr("Negotiating capabilities (requesting: %1)...").arg(_capsQueued.join(", ")));
1025 void CoreNetwork::sendNextCap()
1027 if (capNegotiationInProgress()) {
1028 // Request the next capability and remove it from the list
1029 // Handle one at a time so one capability failing won't NAK all of 'em
1030 putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCap())));
1032 // No pending desired capabilities, capability negotiation finished
1033 // If SASL requested but not available, print a warning
1034 if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1035 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1036 tr("SASL authentication currently not supported by server"));
1038 if (_capNegotiationActive) {
1039 displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1040 tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1041 _capNegotiationActive = false;
1044 endCapNegotiation();
1048 void CoreNetwork::endCapNegotiation()
1050 // If nick registration is already complete, CAP END is not required
1051 if (!_capInitialNegotiationEnded) {
1052 putRawLine(serverEncode(QString("CAP END")));
1053 _capInitialNegotiationEnded = true;
1057 /******** AutoWHO ********/
1059 void CoreNetwork::startAutoWhoCycle()
1061 if (!_autoWhoQueue.isEmpty()) {
1062 _autoWhoCycleTimer.stop();
1065 _autoWhoQueue = channels();
1068 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1070 // Prepend so these new channels/nicks are the first to be checked
1071 // Don't allow duplicates
1072 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1073 _autoWhoQueue.prepend(channelOrNick.toLower());
1075 if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1076 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
1077 setAutoWhoEnabled(true);
1082 void CoreNetwork::setAutoWhoDelay(int delay)
1084 _autoWhoTimer.setInterval(delay * 1000);
1088 void CoreNetwork::setAutoWhoInterval(int interval)
1090 _autoWhoCycleTimer.setInterval(interval * 1000);
1094 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1096 if (enabled && isConnected() && !_autoWhoTimer.isActive())
1097 _autoWhoTimer.start();
1098 else if (!enabled) {
1099 _autoWhoTimer.stop();
1100 _autoWhoCycleTimer.stop();
1105 void CoreNetwork::sendAutoWho()
1107 // Don't send autowho if there are still some pending
1108 if (_autoWhoPending.count())
1111 while (!_autoWhoQueue.isEmpty()) {
1112 QString chanOrNick = _autoWhoQueue.takeFirst();
1113 // Check if it's a known channel or nick
1114 IrcChannel *ircchan = ircChannel(chanOrNick);
1115 IrcUser *ircuser = ircUser(chanOrNick);
1117 // Apply channel limiting rules
1118 // If using away-notify, don't impose channel size limits in order to capture away
1119 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1120 if (networkConfig()->autoWhoNickLimit() > 0
1121 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1122 && !capEnabled(IrcCap::AWAY_NOTIFY))
1124 _autoWhoPending[chanOrNick.toLower()]++;
1125 } else if (ircuser) {
1126 // Checking a nick, add it to the pending list
1127 _autoWhoPending[ircuser->nick().toLower()]++;
1129 // Not a channel or a nick, skip it
1130 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1133 if (supports("WHOX")) {
1134 // Use WHO extended to poll away users and/or user accounts
1135 // See http://faerion.sourceforge.net/doc/irc/whox.var
1136 // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1137 putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1138 .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1140 putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1145 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1146 && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1147 // Timer was stopped, means a new cycle is due immediately
1148 // Don't run a new cycle if using away-notify; server will notify as appropriate
1149 _autoWhoCycleTimer.start();
1150 startAutoWhoCycle();
1151 } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1152 // Don't run another who cycle if away-notify is enabled
1153 _autoWhoCycleTimer.stop();
1159 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1161 Server server = usedServer();
1162 if (server.sslVerify) {
1163 // Treat the SSL error as a hard error
1164 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1165 "since verification is required");
1166 if (!sslErrors.empty()) {
1167 // Add the error reason if known
1168 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1170 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1172 // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1173 // validity, network trouble, etc.
1174 disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1176 // Treat the SSL error as a warning, continue to connect anyways
1177 QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1178 "since verification is not required");
1179 if (!sslErrors.empty()) {
1180 // Add the error reason if known
1181 sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1183 displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1185 // Proceed with the connection
1186 socket.ignoreSslErrors();
1193 void CoreNetwork::fillBucketAndProcessQueue()
1195 if (_tokenBucket < _burstSize) {
1199 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1200 writeToSocket(_msgQueue.takeFirst());
1205 void CoreNetwork::writeToSocket(const QByteArray &data)
1208 socket.write("\r\n");
1213 Network::Server CoreNetwork::usedServer() const
1215 if (_lastUsedServerIndex < serverList().count())
1216 return serverList()[_lastUsedServerIndex];
1218 if (!serverList().isEmpty())
1219 return serverList()[0];
1221 return Network::Server();
1225 void CoreNetwork::requestConnect() const
1227 if (connectionState() != Disconnected) {
1228 qWarning() << "Requesting connect while already being connected!";
1231 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1235 void CoreNetwork::requestDisconnect() const
1237 if (connectionState() == Disconnected) {
1238 qWarning() << "Requesting disconnect while not being connected!";
1241 userInputHandler()->handleQuit(BufferInfo(), QString());
1245 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1247 Network::Server currentServer = usedServer();
1248 setNetworkInfo(info);
1249 Core::updateNetwork(coreSession()->user(), info);
1251 // the order of the servers might have changed,
1252 // so we try to find the previously used server
1253 _lastUsedServerIndex = 0;
1254 for (int i = 0; i < serverList().count(); i++) {
1255 Network::Server server = serverList()[i];
1256 if (server.host == currentServer.host && server.port == currentServer.port) {
1257 _lastUsedServerIndex = i;
1264 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1266 QString wrkMsg(message);
1267 QList<QList<QByteArray>> msgsToSend;
1269 // do while (wrkMsg.size() > 0)
1271 // First, check to see if the whole message can be sent at once. The
1272 // cmdGenerator function is passed in by the caller and is used to encode
1273 // and encrypt (if applicable) the message, since different callers might
1274 // want to use different encoding or encode different values.
1275 int splitPos = wrkMsg.size();
1276 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1277 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1279 if (initialOverrun) {
1280 // If the message was too long to be sent, first try splitting it along
1281 // word boundaries with QTextBoundaryFinder.
1282 QString splitMsg(wrkMsg);
1283 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1284 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1285 QList<QByteArray> splitMsgEnc;
1286 int overrun = initialOverrun;
1289 splitPos = qtbf.toPreviousBoundary();
1291 // splitPos==-1 means the QTBF couldn't find a split point at all and
1292 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1293 // the string. Neither one of these works for us.
1295 // If a split point could be found, split the message there, calculate the
1296 // overrun, and continue with the loop.
1297 splitMsg = splitMsg.left(splitPos);
1298 splitMsgEnc = cmdGenerator(splitMsg);
1299 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1302 // If a split point could not be found (the beginning of the message
1303 // is reached without finding a split point short enough to send) and we
1304 // are still in Word mode, switch to Grapheme mode. We also need to restore
1305 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1306 // the previous attempt to find a split point.
1307 if (qtbf.type() == QTextBoundaryFinder::Word) {
1309 splitPos = splitMsg.size();
1310 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1311 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1312 qtbf = graphemeQtbf;
1315 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1316 // This should never happen, but it should be handled anyway.
1317 qWarning() << "Unexpected failure to split message!";
1323 // Once a message of sendable length has been found, remove it from the wrkMsg and
1324 // add it to the list of messages to be sent.
1325 wrkMsg.remove(0, splitPos);
1326 msgsToSend.append(splitMsgEnc);
1329 // If the entire remaining message is short enough to be sent all at once, remove
1330 // it from the wrkMsg and add it to the list of messages to be sent.
1331 wrkMsg.remove(0, splitPos);
1332 msgsToSend.append(initialSplitMsgEnc);
1334 } while (wrkMsg.size() > 0);