1 /***************************************************************************
2 * Copyright (C) 2005-2015 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"
32 INIT_SYNCABLE_OBJECT(CoreNetwork)
33 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
34 : Network(networkid, session),
35 _coreSession(session),
36 _userInputHandler(new CoreUserInputHandler(this)),
37 _autoReconnectCount(0),
38 _quitRequested(false),
40 _previousConnectionAttemptFailed(false),
41 _lastUsedServerIndex(0),
46 _requestedUserModes('-')
48 _autoReconnectTimer.setSingleShot(true);
49 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
51 setPingInterval(networkConfig()->pingInterval());
52 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
54 setAutoWhoDelay(networkConfig()->autoWhoDelay());
55 setAutoWhoInterval(networkConfig()->autoWhoInterval());
57 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
58 foreach(QString chan, channels.keys()) {
59 _channelKeys[chan.toLower()] = channels[chan];
62 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
63 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
64 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
65 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
66 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
68 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
69 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
70 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
71 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
73 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
74 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
75 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
76 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
78 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
79 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
81 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
83 if (Quassel::isOptionSet("oidentd")) {
84 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
85 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
90 CoreNetwork::~CoreNetwork()
92 if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
93 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
94 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
95 delete _userInputHandler;
99 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
101 if (!bufferName.isEmpty()) {
102 IrcChannel *channel = ircChannel(bufferName);
104 return channel->decodeString(string);
106 return decodeString(string);
110 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
112 IrcUser *user = ircUser(userNick);
114 return user->decodeString(string);
115 return decodeString(string);
119 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
121 if (!bufferName.isEmpty()) {
122 IrcChannel *channel = ircChannel(bufferName);
124 return channel->encodeString(string);
126 return encodeString(string);
130 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
132 IrcUser *user = ircUser(userNick);
134 return user->encodeString(string);
135 return encodeString(string);
139 void CoreNetwork::connectToIrc(bool reconnecting)
141 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
142 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
143 if (unlimitedReconnectRetries())
144 _autoReconnectCount = -1;
146 _autoReconnectCount = autoReconnectRetries();
148 if (serverList().isEmpty()) {
149 qWarning() << "Server list empty, ignoring connect request!";
152 CoreIdentity *identity = identityPtr();
154 qWarning() << "Invalid identity configures, ignoring connect request!";
158 // cleaning up old quit reason
161 // reset capability negotiation in case server changes during a reconnect
163 _capsPending.clear();
164 _capsSupported.clear();
166 // use a random server?
167 if (useRandomServer()) {
168 _lastUsedServerIndex = qrand() % serverList().size();
170 else if (_previousConnectionAttemptFailed) {
171 // cycle to next server if previous connection attempt failed
172 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
173 if (++_lastUsedServerIndex >= serverList().size()) {
174 _lastUsedServerIndex = 0;
177 _previousConnectionAttemptFailed = false;
179 Server server = usedServer();
180 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
181 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
183 if (server.useProxy) {
184 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
185 socket.setProxy(proxy);
188 socket.setProxy(QNetworkProxy::NoProxy);
193 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
194 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
195 QHostInfo::fromName(server.host);
199 CoreIdentity *identity = identityPtr();
201 socket.setLocalCertificate(identity->sslCert());
202 socket.setPrivateKey(identity->sslKey());
204 socket.connectToHostEncrypted(server.host, server.port);
207 socket.connectToHost(server.host, server.port);
210 socket.connectToHost(server.host, server.port);
215 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
217 _quitRequested = requested; // see socketDisconnected();
218 if (!withReconnect) {
219 _autoReconnectTimer.stop();
220 _autoReconnectCount = 0; // prohibiting auto reconnect
222 disablePingTimeout();
229 awayMsg = me_->awayMessage();
230 Core::setAwayMessage(userId(), networkId(), awayMsg);
233 if (reason.isEmpty() && identityPtr())
234 _quitReason = identityPtr()->quitReason();
236 _quitReason = reason;
238 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
239 if (socket.state() == QAbstractSocket::UnconnectedState) {
240 socketDisconnected();
242 if (socket.state() == QAbstractSocket::ConnectedState) {
243 userInputHandler()->issueQuit(_quitReason);
247 if (requested || withReconnect) {
248 // the irc server has 10 seconds to close the socket
249 _socketCloseTimer.start(10000);
255 void CoreNetwork::userInput(BufferInfo buf, QString msg)
257 userInputHandler()->handleUserInput(buf, msg);
261 void CoreNetwork::putRawLine(QByteArray s)
263 if (_tokenBucket > 0)
270 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix)
274 if (!prefix.isEmpty())
275 msg += ":" + prefix + " ";
276 msg += cmd.toUpper().toLatin1();
278 for (int i = 0; i < params.size(); i++) {
281 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
291 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix)
293 QListIterator<QList<QByteArray>> i(params);
294 while (i.hasNext()) {
295 QList<QByteArray> msg = i.next();
296 putCmd(cmd, msg, prefix);
301 void CoreNetwork::setChannelJoined(const QString &channel)
303 queueAutoWhoOneshot(channel); // check this new channel first
305 Core::setChannelPersistent(userId(), networkId(), channel, true);
306 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
310 void CoreNetwork::setChannelParted(const QString &channel)
312 removeChannelKey(channel);
313 _autoWhoQueue.removeAll(channel.toLower());
314 _autoWhoPending.remove(channel.toLower());
316 Core::setChannelPersistent(userId(), networkId(), channel, false);
320 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
323 removeChannelKey(channel);
326 _channelKeys[channel.toLower()] = key;
331 void CoreNetwork::removeChannelKey(const QString &channel)
333 _channelKeys.remove(channel.toLower());
338 Cipher *CoreNetwork::cipher(const QString &target)
340 if (target.isEmpty())
343 if (!Cipher::neededFeaturesAvailable())
346 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
348 return channel->cipher();
350 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
352 return user->cipher();
353 } else if (!isChannelName(target)) {
354 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
360 QByteArray CoreNetwork::cipherKey(const QString &target) const
362 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
364 return c->cipher()->key();
366 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
368 return u->cipher()->key();
374 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
376 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
378 c->setEncrypted(c->cipher()->setKey(key));
382 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
383 if (!u && !isChannelName(target))
384 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
387 u->setEncrypted(u->cipher()->setKey(key));
393 bool CoreNetwork::cipherUsesCBC(const QString &target)
395 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
397 return c->cipher()->usesCBC();
398 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
400 return u->cipher()->usesCBC();
404 #endif /* HAVE_QCA2 */
406 bool CoreNetwork::setAutoWhoDone(const QString &channel)
408 QString chan = channel.toLower();
409 if (_autoWhoPending.value(chan, 0) <= 0)
411 if (--_autoWhoPending[chan] <= 0)
412 _autoWhoPending.remove(chan);
417 void CoreNetwork::setMyNick(const QString &mynick)
419 Network::setMyNick(mynick);
420 if (connectionState() == Network::Initializing)
421 networkInitialized();
425 void CoreNetwork::socketHasData()
427 while (socket.canReadLine()) {
428 QByteArray s = socket.readLine();
429 if (s.endsWith("\r\n"))
431 else if (s.endsWith("\n"))
433 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
434 event->setTimestamp(QDateTime::currentDateTimeUtc());
435 emit newEvent(event);
440 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
442 if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
445 _previousConnectionAttemptFailed = true;
446 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
447 emit connectionError(socket.errorString());
448 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
449 emitConnectionError(socket.errorString());
450 if (socket.state() < QAbstractSocket::ConnectedState) {
451 socketDisconnected();
456 void CoreNetwork::socketInitialized()
458 CoreIdentity *identity = identityPtr();
460 qCritical() << "Identity invalid!";
465 Server server = usedServer();
468 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
469 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
470 if (!server.useSsl || !socket.isEncrypted()) {
471 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
474 if (server.useSsl && !socket.isEncrypted()) {
475 // We'll finish setup once we're encrypted, and called again
479 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
482 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
484 // TokenBucket to avoid sending too much at once
485 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
487 _tokenBucket = _burstSize; // init with a full bucket
488 _tokenBucketTimer.start(_messageDelay);
490 // Request capabilities as per IRCv3.2 specifications
491 // Older servers should ignore this; newer servers won't downgrade to RFC1459
492 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
493 putRawLine(serverEncode(QString("CAP LS 302")));
495 if (!server.password.isEmpty()) {
496 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
499 if (identity->nicks().isEmpty()) {
501 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
504 nick = identity->nicks()[0];
506 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
507 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
511 void CoreNetwork::socketDisconnected()
513 disablePingTimeout();
516 _autoWhoCycleTimer.stop();
517 _autoWhoTimer.stop();
518 _autoWhoQueue.clear();
519 _autoWhoPending.clear();
521 _socketCloseTimer.stop();
523 _tokenBucketTimer.stop();
527 foreach(QString channel, me_->channels())
528 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
532 emit disconnected(networkId());
533 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
534 if (_quitRequested) {
535 _quitRequested = false;
536 setConnectionState(Network::Disconnected);
537 Core::setNetworkConnected(userId(), networkId(), false);
539 else if (_autoReconnectCount != 0) {
540 setConnectionState(Network::Reconnecting);
541 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
542 doAutoReconnect(); // first try is immediate
544 _autoReconnectTimer.start();
549 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
551 Network::ConnectionState state;
552 switch (socketState) {
553 case QAbstractSocket::UnconnectedState:
554 state = Network::Disconnected;
555 socketDisconnected();
557 case QAbstractSocket::HostLookupState:
558 case QAbstractSocket::ConnectingState:
559 state = Network::Connecting;
561 case QAbstractSocket::ConnectedState:
562 state = Network::Initializing;
564 case QAbstractSocket::ClosingState:
565 state = Network::Disconnecting;
568 state = Network::Disconnected;
570 setConnectionState(state);
574 void CoreNetwork::networkInitialized()
576 setConnectionState(Network::Initialized);
578 _quitRequested = false;
580 if (useAutoReconnect()) {
582 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
585 // restore away state
586 QString awayMsg = Core::awayMessage(userId(), networkId());
587 if (!awayMsg.isEmpty())
588 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
594 if (networkConfig()->autoWhoEnabled()) {
595 _autoWhoCycleTimer.start();
596 _autoWhoTimer.start();
597 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
600 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
601 Core::setNetworkConnected(userId(), networkId(), true);
605 void CoreNetwork::sendPerform()
607 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
610 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
611 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
614 // restore old user modes if server default mode is set.
617 if (!me_->userModes().isEmpty()) {
621 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
622 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
627 foreach(QString line, perform()) {
628 if (!line.isEmpty()) userInput(statusBuf, line);
631 // rejoin channels we've been in
632 if (rejoinChannels()) {
633 QStringList channels, keys;
634 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
635 QString key = channelKey(chan);
636 if (!key.isEmpty()) {
637 channels.prepend(chan);
641 channels.append(chan);
644 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
645 if (!joinString.isEmpty())
646 userInputHandler()->handleJoin(statusBuf, joinString);
651 void CoreNetwork::restoreUserModes()
656 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
657 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
659 QString modesDelta = Core::userModes(userId(), networkId());
660 QString currentModes = me_->userModes();
662 QString addModes, removeModes;
663 if (modesDelta.contains('-')) {
664 addModes = modesDelta.section('-', 0, 0);
665 removeModes = modesDelta.section('-', 1);
668 addModes = modesDelta;
671 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
672 if (currentModes.isEmpty())
673 removeModes = QString();
675 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
677 if (addModes.isEmpty() && removeModes.isEmpty())
680 if (!addModes.isEmpty())
681 addModes = '+' + addModes;
682 if (!removeModes.isEmpty())
683 removeModes = '-' + removeModes;
685 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
686 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
690 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
696 for (int i = 0; i < requestedModes.length(); i++) {
697 if (requestedModes[i] == '+') {
701 if (requestedModes[i] == '-') {
706 addModes += requestedModes[i];
709 removeModes += requestedModes[i];
713 QString addModesOld = _requestedUserModes.section('-', 0, 0);
714 QString removeModesOld = _requestedUserModes.section('-', 1);
716 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
717 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
718 addModes += addModesOld;
720 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
721 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
722 removeModes += removeModesOld;
724 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
728 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
730 QString persistentUserModes = Core::userModes(userId(), networkId());
732 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
733 QString requestedRemove = _requestedUserModes.section('-', 1);
735 QString persistentAdd, persistentRemove;
736 if (persistentUserModes.contains('-')) {
737 persistentAdd = persistentUserModes.section('-', 0, 0);
738 persistentRemove = persistentUserModes.section('-', 1);
741 persistentAdd = persistentUserModes;
744 // remove modes we didn't issue
745 if (requestedAdd.isEmpty())
746 addModes = QString();
748 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
750 if (requestedRemove.isEmpty())
751 removeModes = QString();
753 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
756 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
757 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
760 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
761 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
763 // update issued mode list
764 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
765 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
766 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
768 persistentAdd += addModes;
769 persistentRemove += removeModes;
770 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
774 void CoreNetwork::resetPersistentModes()
776 _requestedUserModes = QString('-');
777 Core::setUserModes(userId(), networkId(), QString());
781 void CoreNetwork::setUseAutoReconnect(bool use)
783 Network::setUseAutoReconnect(use);
785 _autoReconnectTimer.stop();
789 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
791 Network::setAutoReconnectInterval(interval);
792 _autoReconnectTimer.setInterval(interval * 1000);
796 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
798 Network::setAutoReconnectRetries(retries);
799 if (_autoReconnectCount != 0) {
800 if (unlimitedReconnectRetries())
801 _autoReconnectCount = -1;
803 _autoReconnectCount = autoReconnectRetries();
808 void CoreNetwork::doAutoReconnect()
810 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
811 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
814 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
815 _autoReconnectCount--; // -2 means we delay the next reconnect
820 void CoreNetwork::sendPing()
822 uint now = QDateTime::currentDateTime().toTime_t();
823 if (_pingCount != 0) {
824 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
825 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
827 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
828 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
829 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
830 // and unable to even handle a ping answer. So we ignore those misses.
831 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
836 // Don't send pings until the network is initialized
838 userInputHandler()->handlePing(BufferInfo(), QString());
843 void CoreNetwork::enablePingTimeout(bool enable)
846 disablePingTimeout();
849 if (networkConfig()->pingTimeoutEnabled())
855 void CoreNetwork::disablePingTimeout()
863 void CoreNetwork::setPingInterval(int interval)
865 _pingTimer.setInterval(interval * 1000);
868 /******** IRCv3 Capability Negotiation ********/
870 void CoreNetwork::addCap(const QString &capability, const QString &value)
872 // Clear from pending list, add to supported list
873 if (!_capsSupported.contains(capability)) {
875 // Value defined, just use it
876 _capsSupported[capability] = value;
877 } else if (_capsPending.contains(capability)) {
878 // Value not defined, but a pending capability had a value.
879 // E.g. CAP * LS :sasl=PLAIN multi-prefix
880 // Preserve the capability value for later use.
881 _capsSupported[capability] = _capsPending[capability];
883 // No value ever given, assign to blank
884 _capsSupported[capability] = QString();
887 if (_capsPending.contains(capability))
888 _capsPending.remove(capability);
890 // Handle special cases here
891 // TODO Use events if it makes sense
892 if (capability == "away-notify") {
893 // away-notify enabled, stop the automatic timers, handle manually
894 setAutoWhoEnabled(false);
898 void CoreNetwork::removeCap(const QString &capability)
900 // Clear from pending list, remove from supported list
901 if (_capsPending.contains(capability))
902 _capsPending.remove(capability);
903 if (_capsSupported.contains(capability))
904 _capsSupported.remove(capability);
906 // Handle special cases here
907 // TODO Use events if it makes sense
908 if (capability == "away-notify") {
909 // away-notify disabled, enable autowho according to configuration
910 setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
914 QString CoreNetwork::capValue(const QString &capability) const
916 // If a supported capability exists, good; if not, return pending value.
917 // If capability isn't supported after all, the pending entry will be removed.
918 if (_capsSupported.contains(capability))
919 return _capsSupported[capability];
920 else if (_capsPending.contains(capability))
921 return _capsPending[capability];
926 void CoreNetwork::queuePendingCap(const QString &capability, const QString &value)
928 if (!_capsQueued.contains(capability)) {
929 _capsQueued.append(capability);
930 // Some capabilities may have values attached, preserve them as pending
931 _capsPending[capability] = value;
935 QString CoreNetwork::takeQueuedCap()
937 if (!_capsQueued.empty()) {
938 return _capsQueued.takeFirst();
944 /******** AutoWHO ********/
946 void CoreNetwork::startAutoWhoCycle()
948 if (!_autoWhoQueue.isEmpty()) {
949 _autoWhoCycleTimer.stop();
952 _autoWhoQueue = channels();
955 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
957 // Prepend so these new channels/nicks are the first to be checked
958 // Don't allow duplicates
959 if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
960 _autoWhoQueue.prepend(channelOrNick.toLower());
962 if (useCapAwayNotify()) {
963 // When away-notify is active, the timer's stopped. Start a new cycle to who this channel.
964 setAutoWhoEnabled(true);
969 void CoreNetwork::setAutoWhoDelay(int delay)
971 _autoWhoTimer.setInterval(delay * 1000);
975 void CoreNetwork::setAutoWhoInterval(int interval)
977 _autoWhoCycleTimer.setInterval(interval * 1000);
981 void CoreNetwork::setAutoWhoEnabled(bool enabled)
983 if (enabled && isConnected() && !_autoWhoTimer.isActive())
984 _autoWhoTimer.start();
986 _autoWhoTimer.stop();
987 _autoWhoCycleTimer.stop();
992 void CoreNetwork::sendAutoWho()
994 // Don't send autowho if there are still some pending
995 if (_autoWhoPending.count())
998 while (!_autoWhoQueue.isEmpty()) {
999 QString chanOrNick = _autoWhoQueue.takeFirst();
1000 // Check if it's a known channel or nick
1001 IrcChannel *ircchan = ircChannel(chanOrNick);
1002 IrcUser *ircuser = ircUser(chanOrNick);
1004 // Apply channel limiting rules
1005 // If using away-notify, don't impose channel size limits in order to capture away
1006 // state of everyone. Auto-who won't run on a timer so network impact is minimal.
1007 if (networkConfig()->autoWhoNickLimit() > 0
1008 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1009 && !useCapAwayNotify())
1011 _autoWhoPending[chanOrNick.toLower()]++;
1012 } else if (ircuser) {
1013 // Checking a nick, add it to the pending list
1014 _autoWhoPending[ircuser->nick().toLower()]++;
1016 // Not a channel or a nick, skip it
1017 qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1020 // TODO Use WHO extended to poll away users and/or user accounts
1021 // If a server supports it, supports("WHOX") will be true
1022 // See: http://faerion.sourceforge.net/doc/irc/whox.var and HexChat
1023 putRawLine("WHO " + serverEncode(chanOrNick));
1027 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1028 && !useCapAwayNotify()) {
1029 // Timer was stopped, means a new cycle is due immediately
1030 // Don't run a new cycle if using away-notify; server will notify as appropriate
1031 _autoWhoCycleTimer.start();
1032 startAutoWhoCycle();
1033 } else if (useCapAwayNotify() && _autoWhoCycleTimer.isActive()) {
1034 // Don't run another who cycle if away-notify is enabled
1035 _autoWhoCycleTimer.stop();
1041 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1044 socket.ignoreSslErrors();
1045 // TODO errorhandling
1051 void CoreNetwork::fillBucketAndProcessQueue()
1053 if (_tokenBucket < _burstSize) {
1057 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1058 writeToSocket(_msgQueue.takeFirst());
1063 void CoreNetwork::writeToSocket(const QByteArray &data)
1066 socket.write("\r\n");
1071 Network::Server CoreNetwork::usedServer() const
1073 if (_lastUsedServerIndex < serverList().count())
1074 return serverList()[_lastUsedServerIndex];
1076 if (!serverList().isEmpty())
1077 return serverList()[0];
1079 return Network::Server();
1083 void CoreNetwork::requestConnect() const
1085 if (connectionState() != Disconnected) {
1086 qWarning() << "Requesting connect while already being connected!";
1089 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1093 void CoreNetwork::requestDisconnect() const
1095 if (connectionState() == Disconnected) {
1096 qWarning() << "Requesting disconnect while not being connected!";
1099 userInputHandler()->handleQuit(BufferInfo(), QString());
1103 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1105 Network::Server currentServer = usedServer();
1106 setNetworkInfo(info);
1107 Core::updateNetwork(coreSession()->user(), info);
1109 // the order of the servers might have changed,
1110 // so we try to find the previously used server
1111 _lastUsedServerIndex = 0;
1112 for (int i = 0; i < serverList().count(); i++) {
1113 Network::Server server = serverList()[i];
1114 if (server.host == currentServer.host && server.port == currentServer.port) {
1115 _lastUsedServerIndex = i;
1122 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1124 QString wrkMsg(message);
1125 QList<QList<QByteArray>> msgsToSend;
1127 // do while (wrkMsg.size() > 0)
1129 // First, check to see if the whole message can be sent at once. The
1130 // cmdGenerator function is passed in by the caller and is used to encode
1131 // and encrypt (if applicable) the message, since different callers might
1132 // want to use different encoding or encode different values.
1133 int splitPos = wrkMsg.size();
1134 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1135 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1137 if (initialOverrun) {
1138 // If the message was too long to be sent, first try splitting it along
1139 // word boundaries with QTextBoundaryFinder.
1140 QString splitMsg(wrkMsg);
1141 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1142 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1143 QList<QByteArray> splitMsgEnc;
1144 int overrun = initialOverrun;
1147 splitPos = qtbf.toPreviousBoundary();
1149 // splitPos==-1 means the QTBF couldn't find a split point at all and
1150 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1151 // the string. Neither one of these works for us.
1153 // If a split point could be found, split the message there, calculate the
1154 // overrun, and continue with the loop.
1155 splitMsg = splitMsg.left(splitPos);
1156 splitMsgEnc = cmdGenerator(splitMsg);
1157 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1160 // If a split point could not be found (the beginning of the message
1161 // is reached without finding a split point short enough to send) and we
1162 // are still in Word mode, switch to Grapheme mode. We also need to restore
1163 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1164 // the previous attempt to find a split point.
1165 if (qtbf.type() == QTextBoundaryFinder::Word) {
1167 splitPos = splitMsg.size();
1168 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1169 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1170 qtbf = graphemeQtbf;
1173 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1174 // This should never happen, but it should be handled anyway.
1175 qWarning() << "Unexpected failure to split message!";
1181 // Once a message of sendable length has been found, remove it from the wrkMsg and
1182 // add it to the list of messages to be sent.
1183 wrkMsg.remove(0, splitPos);
1184 msgsToSend.append(splitMsgEnc);
1187 // If the entire remaining message is short enough to be sent all at once, remove
1188 // it from the wrkMsg and add it to the list of messages to be sent.
1189 wrkMsg.remove(0, splitPos);
1190 msgsToSend.append(initialSplitMsgEnc);
1192 } while (wrkMsg.size() > 0);