1 /***************************************************************************
2 * Copyright (C) 2005-2013 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 ***************************************************************************/
21 #include "corenetwork.h"
24 #include "coreidentity.h"
25 #include "corenetworkconfig.h"
26 #include "coresession.h"
27 #include "coreuserinputhandler.h"
28 #include "networkevent.h"
30 INIT_SYNCABLE_OBJECT(CoreNetwork)
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32 : Network(networkid, session),
33 _coreSession(session),
34 _userInputHandler(new CoreUserInputHandler(this)),
35 _autoReconnectCount(0),
36 _quitRequested(false),
38 _previousConnectionAttemptFailed(false),
39 _lastUsedServerIndex(0),
44 _requestedUserModes('-')
46 _autoReconnectTimer.setSingleShot(true);
47 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
49 setPingInterval(networkConfig()->pingInterval());
50 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
52 setAutoWhoDelay(networkConfig()->autoWhoDelay());
53 setAutoWhoInterval(networkConfig()->autoWhoInterval());
55 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
56 foreach(QString chan, channels.keys()) {
57 _channelKeys[chan.toLower()] = channels[chan];
60 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
61 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
62 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
63 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
64 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
66 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
67 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
68 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
69 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
71 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
72 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
73 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
74 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
75 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
77 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
78 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
80 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
82 if (Quassel::isOptionSet("oidentd")) {
83 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
84 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
89 CoreNetwork::~CoreNetwork()
91 if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
92 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
93 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
94 delete _userInputHandler;
98 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
100 if (!bufferName.isEmpty()) {
101 IrcChannel *channel = ircChannel(bufferName);
103 return channel->decodeString(string);
105 return decodeString(string);
109 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
111 IrcUser *user = ircUser(userNick);
113 return user->decodeString(string);
114 return decodeString(string);
118 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
120 if (!bufferName.isEmpty()) {
121 IrcChannel *channel = ircChannel(bufferName);
123 return channel->encodeString(string);
125 return encodeString(string);
129 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
131 IrcUser *user = ircUser(userNick);
133 return user->encodeString(string);
134 return encodeString(string);
138 void CoreNetwork::connectToIrc(bool reconnecting)
140 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
141 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
142 if (unlimitedReconnectRetries())
143 _autoReconnectCount = -1;
145 _autoReconnectCount = autoReconnectRetries();
147 if (serverList().isEmpty()) {
148 qWarning() << "Server list empty, ignoring connect request!";
151 CoreIdentity *identity = identityPtr();
153 qWarning() << "Invalid identity configures, ignoring connect request!";
157 // cleaning up old quit reason
160 // use a random server?
161 if (useRandomServer()) {
162 _lastUsedServerIndex = qrand() % serverList().size();
164 else if (_previousConnectionAttemptFailed) {
165 // cycle to next server if previous connection attempt failed
166 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
167 if (++_lastUsedServerIndex >= serverList().size()) {
168 _lastUsedServerIndex = 0;
171 _previousConnectionAttemptFailed = false;
173 Server server = usedServer();
174 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
175 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
177 if (server.useProxy) {
178 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
179 socket.setProxy(proxy);
182 socket.setProxy(QNetworkProxy::NoProxy);
188 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
190 CoreIdentity *identity = identityPtr();
192 socket.setLocalCertificate(identity->sslCert());
193 socket.setPrivateKey(identity->sslKey());
195 socket.connectToHostEncrypted(server.host, server.port);
198 socket.connectToHost(server.host, server.port);
201 socket.connectToHost(server.host, server.port);
206 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
208 _quitRequested = requested; // see socketDisconnected();
209 if (!withReconnect) {
210 _autoReconnectTimer.stop();
211 _autoReconnectCount = 0; // prohibiting auto reconnect
213 disablePingTimeout();
220 awayMsg = me_->awayMessage();
221 Core::setAwayMessage(userId(), networkId(), awayMsg);
224 if (reason.isEmpty() && identityPtr())
225 _quitReason = identityPtr()->quitReason();
227 _quitReason = reason;
229 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
230 switch (socket.state()) {
231 case QAbstractSocket::ConnectedState:
232 userInputHandler()->issueQuit(_quitReason);
233 if (requested || withReconnect) {
234 // the irc server has 10 seconds to close the socket
235 _socketCloseTimer.start(10000);
240 socketDisconnected();
245 void CoreNetwork::userInput(BufferInfo buf, QString msg)
247 userInputHandler()->handleUserInput(buf, msg);
251 void CoreNetwork::putRawLine(QByteArray s)
253 if (_tokenBucket > 0)
260 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix)
264 if (!prefix.isEmpty())
265 msg += ":" + prefix + " ";
266 msg += cmd.toUpper().toAscii();
268 for (int i = 0; i < params.size() - 1; i++) {
269 msg += " " + params[i];
271 if (!params.isEmpty())
272 msg += " :" + params.last();
278 void CoreNetwork::setChannelJoined(const QString &channel)
280 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
282 Core::setChannelPersistent(userId(), networkId(), channel, true);
283 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
287 void CoreNetwork::setChannelParted(const QString &channel)
289 removeChannelKey(channel);
290 _autoWhoQueue.removeAll(channel.toLower());
291 _autoWhoPending.remove(channel.toLower());
293 Core::setChannelPersistent(userId(), networkId(), channel, false);
297 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
300 removeChannelKey(channel);
303 _channelKeys[channel.toLower()] = key;
308 void CoreNetwork::removeChannelKey(const QString &channel)
310 _channelKeys.remove(channel.toLower());
315 Cipher *CoreNetwork::cipher(const QString &target)
317 if (target.isEmpty())
320 if (!Cipher::neededFeaturesAvailable())
323 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
325 return channel->cipher();
327 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
329 return user->cipher();
330 } else if (!isChannelName(target)) {
331 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
337 QByteArray CoreNetwork::cipherKey(const QString &target) const
339 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
341 return c->cipher()->key();
343 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
345 return u->cipher()->key();
351 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
353 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
355 c->setEncrypted(c->cipher()->setKey(key));
359 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
360 if (!u && !isChannelName(target))
361 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
364 u->setEncrypted(u->cipher()->setKey(key));
370 bool CoreNetwork::cipherUsesCBC(const QString &target)
372 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
374 return c->cipher()->usesCBC();
375 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
377 return u->cipher()->usesCBC();
381 #endif /* HAVE_QCA2 */
383 bool CoreNetwork::setAutoWhoDone(const QString &channel)
385 QString chan = channel.toLower();
386 if (_autoWhoPending.value(chan, 0) <= 0)
388 if (--_autoWhoPending[chan] <= 0)
389 _autoWhoPending.remove(chan);
394 void CoreNetwork::setMyNick(const QString &mynick)
396 Network::setMyNick(mynick);
397 if (connectionState() == Network::Initializing)
398 networkInitialized();
402 void CoreNetwork::socketHasData()
404 while (socket.canReadLine()) {
405 QByteArray s = socket.readLine();
407 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
408 #if QT_VERSION >= 0x040700
409 event->setTimestamp(QDateTime::currentDateTimeUtc());
411 event->setTimestamp(QDateTime::currentDateTime().toUTC());
413 emit newEvent(event);
418 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
420 if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
423 _previousConnectionAttemptFailed = true;
424 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
425 emit connectionError(socket.errorString());
426 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
427 emitConnectionError(socket.errorString());
428 if (socket.state() < QAbstractSocket::ConnectedState) {
429 socketDisconnected();
434 void CoreNetwork::socketInitialized()
436 Server server = usedServer();
438 if (server.useSsl && !socket.isEncrypted())
442 CoreIdentity *identity = identityPtr();
444 qCritical() << "Identity invalid!";
449 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
451 // TokenBucket to avoid sending too much at once
452 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
454 _tokenBucket = _burstSize; // init with a full bucket
455 _tokenBucketTimer.start(_messageDelay);
457 if (networkInfo().useSasl) {
458 putRawLine(serverEncode(QString("CAP REQ :sasl")));
460 if (!server.password.isEmpty()) {
461 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
464 if (identity->nicks().isEmpty()) {
466 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
469 nick = identity->nicks()[0];
471 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
472 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
476 void CoreNetwork::socketDisconnected()
478 disablePingTimeout();
481 _autoWhoCycleTimer.stop();
482 _autoWhoTimer.stop();
483 _autoWhoQueue.clear();
484 _autoWhoPending.clear();
486 _socketCloseTimer.stop();
488 _tokenBucketTimer.stop();
492 foreach(QString channel, me_->channels())
493 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
497 emit disconnected(networkId());
498 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
499 if (_quitRequested) {
500 _quitRequested = false;
501 setConnectionState(Network::Disconnected);
502 Core::setNetworkConnected(userId(), networkId(), false);
504 else if (_autoReconnectCount != 0) {
505 setConnectionState(Network::Reconnecting);
506 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
507 doAutoReconnect(); // first try is immediate
509 _autoReconnectTimer.start();
514 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
516 Network::ConnectionState state;
517 switch (socketState) {
518 case QAbstractSocket::UnconnectedState:
519 state = Network::Disconnected;
521 case QAbstractSocket::HostLookupState:
522 case QAbstractSocket::ConnectingState:
523 state = Network::Connecting;
525 case QAbstractSocket::ConnectedState:
526 state = Network::Initializing;
528 case QAbstractSocket::ClosingState:
529 state = Network::Disconnecting;
532 state = Network::Disconnected;
534 setConnectionState(state);
538 void CoreNetwork::networkInitialized()
540 setConnectionState(Network::Initialized);
542 _quitRequested = false;
544 if (useAutoReconnect()) {
546 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
549 // restore away state
550 QString awayMsg = Core::awayMessage(userId(), networkId());
551 if (!awayMsg.isEmpty())
552 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
558 if (networkConfig()->autoWhoEnabled()) {
559 _autoWhoCycleTimer.start();
560 _autoWhoTimer.start();
561 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
564 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
565 Core::setNetworkConnected(userId(), networkId(), true);
569 void CoreNetwork::sendPerform()
571 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
574 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
575 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
578 // restore old user modes if server default mode is set.
581 if (!me_->userModes().isEmpty()) {
585 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
586 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
591 foreach(QString line, perform()) {
592 if (!line.isEmpty()) userInput(statusBuf, line);
595 // rejoin channels we've been in
596 if (rejoinChannels()) {
597 QStringList channels, keys;
598 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
599 QString key = channelKey(chan);
600 if (!key.isEmpty()) {
601 channels.prepend(chan);
605 channels.append(chan);
608 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
609 if (!joinString.isEmpty())
610 userInputHandler()->handleJoin(statusBuf, joinString);
615 void CoreNetwork::restoreUserModes()
620 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
621 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
623 QString modesDelta = Core::userModes(userId(), networkId());
624 QString currentModes = me_->userModes();
626 QString addModes, removeModes;
627 if (modesDelta.contains('-')) {
628 addModes = modesDelta.section('-', 0, 0);
629 removeModes = modesDelta.section('-', 1);
632 addModes = modesDelta;
635 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
636 if (currentModes.isEmpty())
637 removeModes = QString();
639 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
641 if (addModes.isEmpty() && removeModes.isEmpty())
644 if (!addModes.isEmpty())
645 addModes = '+' + addModes;
646 if (!removeModes.isEmpty())
647 removeModes = '-' + removeModes;
649 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
650 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
654 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
660 for (int i = 0; i < requestedModes.length(); i++) {
661 if (requestedModes[i] == '+') {
665 if (requestedModes[i] == '-') {
670 addModes += requestedModes[i];
673 removeModes += requestedModes[i];
677 QString addModesOld = _requestedUserModes.section('-', 0, 0);
678 QString removeModesOld = _requestedUserModes.section('-', 1);
680 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
681 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
682 addModes += addModesOld;
684 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
685 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
686 removeModes += removeModesOld;
688 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
692 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
694 QString persistentUserModes = Core::userModes(userId(), networkId());
696 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
697 QString requestedRemove = _requestedUserModes.section('-', 1);
699 QString persistentAdd, persistentRemove;
700 if (persistentUserModes.contains('-')) {
701 persistentAdd = persistentUserModes.section('-', 0, 0);
702 persistentRemove = persistentUserModes.section('-', 1);
705 persistentAdd = persistentUserModes;
708 // remove modes we didn't issue
709 if (requestedAdd.isEmpty())
710 addModes = QString();
712 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
714 if (requestedRemove.isEmpty())
715 removeModes = QString();
717 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
720 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
721 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
724 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
725 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
727 // update issued mode list
728 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
729 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
730 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
732 persistentAdd += addModes;
733 persistentRemove += removeModes;
734 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
738 void CoreNetwork::resetPersistentModes()
740 _requestedUserModes = QString('-');
741 Core::setUserModes(userId(), networkId(), QString());
745 void CoreNetwork::setUseAutoReconnect(bool use)
747 Network::setUseAutoReconnect(use);
749 _autoReconnectTimer.stop();
753 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
755 Network::setAutoReconnectInterval(interval);
756 _autoReconnectTimer.setInterval(interval * 1000);
760 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
762 Network::setAutoReconnectRetries(retries);
763 if (_autoReconnectCount != 0) {
764 if (unlimitedReconnectRetries())
765 _autoReconnectCount = -1;
767 _autoReconnectCount = autoReconnectRetries();
772 void CoreNetwork::doAutoReconnect()
774 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
775 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
778 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
779 _autoReconnectCount--; // -2 means we delay the next reconnect
784 void CoreNetwork::sendPing()
786 uint now = QDateTime::currentDateTime().toTime_t();
787 if (_pingCount != 0) {
788 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
789 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
791 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
792 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
793 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
794 // and unable to even handle a ping answer. So we ignore those misses.
795 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
800 // Don't send pings until the network is initialized
802 userInputHandler()->handlePing(BufferInfo(), QString());
807 void CoreNetwork::enablePingTimeout(bool enable)
810 disablePingTimeout();
813 if (networkConfig()->pingTimeoutEnabled())
819 void CoreNetwork::disablePingTimeout()
827 void CoreNetwork::setPingInterval(int interval)
829 _pingTimer.setInterval(interval * 1000);
833 /******** AutoWHO ********/
835 void CoreNetwork::startAutoWhoCycle()
837 if (!_autoWhoQueue.isEmpty()) {
838 _autoWhoCycleTimer.stop();
841 _autoWhoQueue = channels();
845 void CoreNetwork::setAutoWhoDelay(int delay)
847 _autoWhoTimer.setInterval(delay * 1000);
851 void CoreNetwork::setAutoWhoInterval(int interval)
853 _autoWhoCycleTimer.setInterval(interval * 1000);
857 void CoreNetwork::setAutoWhoEnabled(bool enabled)
859 if (enabled && isConnected() && !_autoWhoTimer.isActive())
860 _autoWhoTimer.start();
862 _autoWhoTimer.stop();
863 _autoWhoCycleTimer.stop();
868 void CoreNetwork::sendAutoWho()
870 // Don't send autowho if there are still some pending
871 if (_autoWhoPending.count())
874 while (!_autoWhoQueue.isEmpty()) {
875 QString chan = _autoWhoQueue.takeFirst();
876 IrcChannel *ircchan = ircChannel(chan);
877 if (!ircchan) continue;
878 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
880 _autoWhoPending[chan]++;
881 putRawLine("WHO " + serverEncode(chan));
884 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
885 // Timer was stopped, means a new cycle is due immediately
886 _autoWhoCycleTimer.start();
893 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
896 socket.ignoreSslErrors();
897 // TODO errorhandling
903 void CoreNetwork::fillBucketAndProcessQueue()
905 if (_tokenBucket < _burstSize) {
909 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
910 writeToSocket(_msgQueue.takeFirst());
915 void CoreNetwork::writeToSocket(const QByteArray &data)
918 socket.write("\r\n");
923 Network::Server CoreNetwork::usedServer() const
925 if (_lastUsedServerIndex < serverList().count())
926 return serverList()[_lastUsedServerIndex];
928 if (!serverList().isEmpty())
929 return serverList()[0];
931 return Network::Server();
935 void CoreNetwork::requestConnect() const
937 if (connectionState() != Disconnected) {
938 qWarning() << "Requesting connect while already being connected!";
941 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
945 void CoreNetwork::requestDisconnect() const
947 if (connectionState() == Disconnected) {
948 qWarning() << "Requesting disconnect while not being connected!";
951 userInputHandler()->handleQuit(BufferInfo(), QString());
955 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
957 Network::Server currentServer = usedServer();
958 setNetworkInfo(info);
959 Core::updateNetwork(coreSession()->user(), info);
961 // the order of the servers might have changed,
962 // so we try to find the previously used server
963 _lastUsedServerIndex = 0;
964 for (int i = 0; i < serverList().count(); i++) {
965 Network::Server server = serverList()[i];
966 if (server.host == currentServer.host && server.port == currentServer.port) {
967 _lastUsedServerIndex = i;