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 // use a random server?
162 if (useRandomServer()) {
163 _lastUsedServerIndex = qrand() % serverList().size();
165 else if (_previousConnectionAttemptFailed) {
166 // cycle to next server if previous connection attempt failed
167 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
168 if (++_lastUsedServerIndex >= serverList().size()) {
169 _lastUsedServerIndex = 0;
172 _previousConnectionAttemptFailed = false;
174 Server server = usedServer();
175 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
176 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
178 if (server.useProxy) {
179 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
180 socket.setProxy(proxy);
183 socket.setProxy(QNetworkProxy::NoProxy);
188 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
189 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
190 QHostInfo::fromName(server.host);
194 CoreIdentity *identity = identityPtr();
196 socket.setLocalCertificate(identity->sslCert());
197 socket.setPrivateKey(identity->sslKey());
199 socket.connectToHostEncrypted(server.host, server.port);
202 socket.connectToHost(server.host, server.port);
205 socket.connectToHost(server.host, server.port);
210 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
212 _quitRequested = requested; // see socketDisconnected();
213 if (!withReconnect) {
214 _autoReconnectTimer.stop();
215 _autoReconnectCount = 0; // prohibiting auto reconnect
217 disablePingTimeout();
224 awayMsg = me_->awayMessage();
225 Core::setAwayMessage(userId(), networkId(), awayMsg);
228 if (reason.isEmpty() && identityPtr())
229 _quitReason = identityPtr()->quitReason();
231 _quitReason = reason;
233 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
234 if (socket.state() == QAbstractSocket::UnconnectedState) {
235 socketDisconnected();
237 if (socket.state() == QAbstractSocket::ConnectedState) {
238 userInputHandler()->issueQuit(_quitReason);
242 if (requested || withReconnect) {
243 // the irc server has 10 seconds to close the socket
244 _socketCloseTimer.start(10000);
250 void CoreNetwork::userInput(BufferInfo buf, QString msg)
252 userInputHandler()->handleUserInput(buf, msg);
256 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
258 if (_tokenBucket > 0) {
262 _msgQueue.prepend(s);
270 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
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] == ':')))
287 putRawLine(msg, prepend);
291 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
293 QListIterator<QList<QByteArray>> i(params);
294 while (i.hasNext()) {
295 QList<QByteArray> msg = i.next();
296 putCmd(cmd, msg, prefix, prependAll);
301 void CoreNetwork::setChannelJoined(const QString &channel)
303 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
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 if (networkInfo().useSasl) {
491 putRawLine(serverEncode(QString("CAP REQ :sasl")));
493 if (!server.password.isEmpty()) {
494 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
497 if (identity->nicks().isEmpty()) {
499 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
502 nick = identity->nicks()[0];
504 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
505 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
509 void CoreNetwork::socketDisconnected()
511 disablePingTimeout();
514 _autoWhoCycleTimer.stop();
515 _autoWhoTimer.stop();
516 _autoWhoQueue.clear();
517 _autoWhoPending.clear();
519 _socketCloseTimer.stop();
521 _tokenBucketTimer.stop();
525 foreach(QString channel, me_->channels())
526 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
530 emit disconnected(networkId());
531 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
532 if (_quitRequested) {
533 _quitRequested = false;
534 setConnectionState(Network::Disconnected);
535 Core::setNetworkConnected(userId(), networkId(), false);
537 else if (_autoReconnectCount != 0) {
538 setConnectionState(Network::Reconnecting);
539 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
540 doAutoReconnect(); // first try is immediate
542 _autoReconnectTimer.start();
547 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
549 Network::ConnectionState state;
550 switch (socketState) {
551 case QAbstractSocket::UnconnectedState:
552 state = Network::Disconnected;
553 socketDisconnected();
555 case QAbstractSocket::HostLookupState:
556 case QAbstractSocket::ConnectingState:
557 state = Network::Connecting;
559 case QAbstractSocket::ConnectedState:
560 state = Network::Initializing;
562 case QAbstractSocket::ClosingState:
563 state = Network::Disconnecting;
566 state = Network::Disconnected;
568 setConnectionState(state);
572 void CoreNetwork::networkInitialized()
574 setConnectionState(Network::Initialized);
576 _quitRequested = false;
578 if (useAutoReconnect()) {
580 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
583 // restore away state
584 QString awayMsg = Core::awayMessage(userId(), networkId());
585 if (!awayMsg.isEmpty())
586 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
592 if (networkConfig()->autoWhoEnabled()) {
593 _autoWhoCycleTimer.start();
594 _autoWhoTimer.start();
595 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
598 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
599 Core::setNetworkConnected(userId(), networkId(), true);
603 void CoreNetwork::sendPerform()
605 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
608 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
609 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
612 // restore old user modes if server default mode is set.
615 if (!me_->userModes().isEmpty()) {
619 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
620 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
625 foreach(QString line, perform()) {
626 if (!line.isEmpty()) userInput(statusBuf, line);
629 // rejoin channels we've been in
630 if (rejoinChannels()) {
631 QStringList channels, keys;
632 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
633 QString key = channelKey(chan);
634 if (!key.isEmpty()) {
635 channels.prepend(chan);
639 channels.append(chan);
642 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
643 if (!joinString.isEmpty())
644 userInputHandler()->handleJoin(statusBuf, joinString);
649 void CoreNetwork::restoreUserModes()
654 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
655 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
657 QString modesDelta = Core::userModes(userId(), networkId());
658 QString currentModes = me_->userModes();
660 QString addModes, removeModes;
661 if (modesDelta.contains('-')) {
662 addModes = modesDelta.section('-', 0, 0);
663 removeModes = modesDelta.section('-', 1);
666 addModes = modesDelta;
669 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
670 if (currentModes.isEmpty())
671 removeModes = QString();
673 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
675 if (addModes.isEmpty() && removeModes.isEmpty())
678 if (!addModes.isEmpty())
679 addModes = '+' + addModes;
680 if (!removeModes.isEmpty())
681 removeModes = '-' + removeModes;
683 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
684 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
688 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
694 for (int i = 0; i < requestedModes.length(); i++) {
695 if (requestedModes[i] == '+') {
699 if (requestedModes[i] == '-') {
704 addModes += requestedModes[i];
707 removeModes += requestedModes[i];
711 QString addModesOld = _requestedUserModes.section('-', 0, 0);
712 QString removeModesOld = _requestedUserModes.section('-', 1);
714 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
715 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
716 addModes += addModesOld;
718 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
719 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
720 removeModes += removeModesOld;
722 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
726 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
728 QString persistentUserModes = Core::userModes(userId(), networkId());
730 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
731 QString requestedRemove = _requestedUserModes.section('-', 1);
733 QString persistentAdd, persistentRemove;
734 if (persistentUserModes.contains('-')) {
735 persistentAdd = persistentUserModes.section('-', 0, 0);
736 persistentRemove = persistentUserModes.section('-', 1);
739 persistentAdd = persistentUserModes;
742 // remove modes we didn't issue
743 if (requestedAdd.isEmpty())
744 addModes = QString();
746 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
748 if (requestedRemove.isEmpty())
749 removeModes = QString();
751 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
754 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
755 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
758 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
759 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
761 // update issued mode list
762 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
763 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
764 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
766 persistentAdd += addModes;
767 persistentRemove += removeModes;
768 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
772 void CoreNetwork::resetPersistentModes()
774 _requestedUserModes = QString('-');
775 Core::setUserModes(userId(), networkId(), QString());
779 void CoreNetwork::setUseAutoReconnect(bool use)
781 Network::setUseAutoReconnect(use);
783 _autoReconnectTimer.stop();
787 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
789 Network::setAutoReconnectInterval(interval);
790 _autoReconnectTimer.setInterval(interval * 1000);
794 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
796 Network::setAutoReconnectRetries(retries);
797 if (_autoReconnectCount != 0) {
798 if (unlimitedReconnectRetries())
799 _autoReconnectCount = -1;
801 _autoReconnectCount = autoReconnectRetries();
806 void CoreNetwork::doAutoReconnect()
808 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
809 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
812 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
813 _autoReconnectCount--; // -2 means we delay the next reconnect
818 void CoreNetwork::sendPing()
820 uint now = QDateTime::currentDateTime().toTime_t();
821 if (_pingCount != 0) {
822 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
823 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
825 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
826 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
827 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
828 // and unable to even handle a ping answer. So we ignore those misses.
829 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
834 // Don't send pings until the network is initialized
836 userInputHandler()->handlePing(BufferInfo(), QString());
841 void CoreNetwork::enablePingTimeout(bool enable)
844 disablePingTimeout();
847 if (networkConfig()->pingTimeoutEnabled())
853 void CoreNetwork::disablePingTimeout()
861 void CoreNetwork::setPingInterval(int interval)
863 _pingTimer.setInterval(interval * 1000);
867 /******** AutoWHO ********/
869 void CoreNetwork::startAutoWhoCycle()
871 if (!_autoWhoQueue.isEmpty()) {
872 _autoWhoCycleTimer.stop();
875 _autoWhoQueue = channels();
879 void CoreNetwork::setAutoWhoDelay(int delay)
881 _autoWhoTimer.setInterval(delay * 1000);
885 void CoreNetwork::setAutoWhoInterval(int interval)
887 _autoWhoCycleTimer.setInterval(interval * 1000);
891 void CoreNetwork::setAutoWhoEnabled(bool enabled)
893 if (enabled && isConnected() && !_autoWhoTimer.isActive())
894 _autoWhoTimer.start();
896 _autoWhoTimer.stop();
897 _autoWhoCycleTimer.stop();
902 void CoreNetwork::sendAutoWho()
904 // Don't send autowho if there are still some pending
905 if (_autoWhoPending.count())
908 while (!_autoWhoQueue.isEmpty()) {
909 QString chan = _autoWhoQueue.takeFirst();
910 IrcChannel *ircchan = ircChannel(chan);
911 if (!ircchan) continue;
912 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
914 _autoWhoPending[chan]++;
915 putRawLine("WHO " + serverEncode(chan));
918 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
919 // Timer was stopped, means a new cycle is due immediately
920 _autoWhoCycleTimer.start();
927 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
930 socket.ignoreSslErrors();
931 // TODO errorhandling
937 void CoreNetwork::fillBucketAndProcessQueue()
939 if (_tokenBucket < _burstSize) {
943 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
944 writeToSocket(_msgQueue.takeFirst());
949 void CoreNetwork::writeToSocket(const QByteArray &data)
952 socket.write("\r\n");
957 Network::Server CoreNetwork::usedServer() const
959 if (_lastUsedServerIndex < serverList().count())
960 return serverList()[_lastUsedServerIndex];
962 if (!serverList().isEmpty())
963 return serverList()[0];
965 return Network::Server();
969 void CoreNetwork::requestConnect() const
971 if (connectionState() != Disconnected) {
972 qWarning() << "Requesting connect while already being connected!";
975 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
979 void CoreNetwork::requestDisconnect() const
981 if (connectionState() == Disconnected) {
982 qWarning() << "Requesting disconnect while not being connected!";
985 userInputHandler()->handleQuit(BufferInfo(), QString());
989 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
991 Network::Server currentServer = usedServer();
992 setNetworkInfo(info);
993 Core::updateNetwork(coreSession()->user(), info);
995 // the order of the servers might have changed,
996 // so we try to find the previously used server
997 _lastUsedServerIndex = 0;
998 for (int i = 0; i < serverList().count(); i++) {
999 Network::Server server = serverList()[i];
1000 if (server.host == currentServer.host && server.port == currentServer.port) {
1001 _lastUsedServerIndex = i;
1008 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1010 QString wrkMsg(message);
1011 QList<QList<QByteArray>> msgsToSend;
1013 // do while (wrkMsg.size() > 0)
1015 // First, check to see if the whole message can be sent at once. The
1016 // cmdGenerator function is passed in by the caller and is used to encode
1017 // and encrypt (if applicable) the message, since different callers might
1018 // want to use different encoding or encode different values.
1019 int splitPos = wrkMsg.size();
1020 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1021 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1023 if (initialOverrun) {
1024 // If the message was too long to be sent, first try splitting it along
1025 // word boundaries with QTextBoundaryFinder.
1026 QString splitMsg(wrkMsg);
1027 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1028 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1029 QList<QByteArray> splitMsgEnc;
1030 int overrun = initialOverrun;
1033 splitPos = qtbf.toPreviousBoundary();
1035 // splitPos==-1 means the QTBF couldn't find a split point at all and
1036 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1037 // the string. Neither one of these works for us.
1039 // If a split point could be found, split the message there, calculate the
1040 // overrun, and continue with the loop.
1041 splitMsg = splitMsg.left(splitPos);
1042 splitMsgEnc = cmdGenerator(splitMsg);
1043 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1046 // If a split point could not be found (the beginning of the message
1047 // is reached without finding a split point short enough to send) and we
1048 // are still in Word mode, switch to Grapheme mode. We also need to restore
1049 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1050 // the previous attempt to find a split point.
1051 if (qtbf.type() == QTextBoundaryFinder::Word) {
1053 splitPos = splitMsg.size();
1054 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1055 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1056 qtbf = graphemeQtbf;
1059 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1060 // This should never happen, but it should be handled anyway.
1061 qWarning() << "Unexpected failure to split message!";
1067 // Once a message of sendable length has been found, remove it from the wrkMsg and
1068 // add it to the list of messages to be sent.
1069 wrkMsg.remove(0, splitPos);
1070 msgsToSend.append(splitMsgEnc);
1073 // If the entire remaining message is short enough to be sent all at once, remove
1074 // it from the wrkMsg and add it to the list of messages to be sent.
1075 wrkMsg.remove(0, splitPos);
1076 msgsToSend.append(initialSplitMsgEnc);
1078 } while (wrkMsg.size() > 0);