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),
43 _requestedUserModes('-')
45 _autoReconnectTimer.setSingleShot(true);
46 _socketCloseTimer.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);
186 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
188 CoreIdentity *identity = identityPtr();
190 socket.setLocalCertificate(identity->sslCert());
191 socket.setPrivateKey(identity->sslKey());
193 socket.connectToHostEncrypted(server.host, server.port);
196 socket.connectToHost(server.host, server.port);
199 socket.connectToHost(server.host, server.port);
204 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
206 _quitRequested = requested; // see socketDisconnected();
207 if (!withReconnect) {
208 _autoReconnectTimer.stop();
209 _autoReconnectCount = 0; // prohibiting auto reconnect
211 disablePingTimeout();
218 awayMsg = me_->awayMessage();
219 Core::setAwayMessage(userId(), networkId(), awayMsg);
222 if (reason.isEmpty() && identityPtr())
223 _quitReason = identityPtr()->quitReason();
225 _quitReason = reason;
227 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
228 switch (socket.state()) {
229 case QAbstractSocket::ConnectedState:
230 userInputHandler()->issueQuit(_quitReason);
231 if (requested || withReconnect) {
232 // the irc server has 10 seconds to close the socket
233 _socketCloseTimer.start(10000);
238 socketDisconnected();
243 void CoreNetwork::userInput(BufferInfo buf, QString msg)
245 userInputHandler()->handleUserInput(buf, msg);
249 void CoreNetwork::putRawLine(QByteArray s)
251 if (_tokenBucket > 0)
258 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix)
262 if (!prefix.isEmpty())
263 msg += ":" + prefix + " ";
264 msg += cmd.toUpper().toAscii();
266 for (int i = 0; i < params.size() - 1; i++) {
267 msg += " " + params[i];
269 if (!params.isEmpty())
270 msg += " :" + params.last();
276 void CoreNetwork::setChannelJoined(const QString &channel)
278 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
280 Core::setChannelPersistent(userId(), networkId(), channel, true);
281 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
285 void CoreNetwork::setChannelParted(const QString &channel)
287 removeChannelKey(channel);
288 _autoWhoQueue.removeAll(channel.toLower());
289 _autoWhoPending.remove(channel.toLower());
291 Core::setChannelPersistent(userId(), networkId(), channel, false);
295 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
298 removeChannelKey(channel);
301 _channelKeys[channel.toLower()] = key;
306 void CoreNetwork::removeChannelKey(const QString &channel)
308 _channelKeys.remove(channel.toLower());
313 Cipher *CoreNetwork::cipher(const QString &target)
315 if (target.isEmpty())
318 if (!Cipher::neededFeaturesAvailable())
321 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
323 return channel->cipher();
325 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
327 return user->cipher();
328 } else if (!isChannelName(target)) {
329 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
335 QByteArray CoreNetwork::cipherKey(const QString &target) const
337 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
339 return c->cipher()->key();
341 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
343 return u->cipher()->key();
349 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
351 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
353 c->setEncrypted(c->cipher()->setKey(key));
357 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
358 if (!u && !isChannelName(target))
359 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
362 u->setEncrypted(u->cipher()->setKey(key));
368 bool CoreNetwork::cipherUsesCBC(const QString &target)
370 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
372 return c->cipher()->usesCBC();
373 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
375 return u->cipher()->usesCBC();
379 #endif /* HAVE_QCA2 */
381 bool CoreNetwork::setAutoWhoDone(const QString &channel)
383 QString chan = channel.toLower();
384 if (_autoWhoPending.value(chan, 0) <= 0)
386 if (--_autoWhoPending[chan] <= 0)
387 _autoWhoPending.remove(chan);
392 void CoreNetwork::setMyNick(const QString &mynick)
394 Network::setMyNick(mynick);
395 if (connectionState() == Network::Initializing)
396 networkInitialized();
400 void CoreNetwork::socketHasData()
402 while (socket.canReadLine()) {
403 QByteArray s = socket.readLine();
405 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
406 #if QT_VERSION >= 0x040700
407 event->setTimestamp(QDateTime::currentDateTimeUtc());
409 event->setTimestamp(QDateTime::currentDateTime().toUTC());
411 emit newEvent(event);
416 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
418 if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
421 _previousConnectionAttemptFailed = true;
422 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
423 emit connectionError(socket.errorString());
424 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
425 emitConnectionError(socket.errorString());
426 if (socket.state() < QAbstractSocket::ConnectedState) {
427 socketDisconnected();
432 void CoreNetwork::socketInitialized()
434 Server server = usedServer();
436 if (server.useSsl && !socket.isEncrypted())
440 CoreIdentity *identity = identityPtr();
442 qCritical() << "Identity invalid!";
447 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
449 // TokenBucket to avoid sending too much at once
450 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
452 _tokenBucket = _burstSize; // init with a full bucket
453 _tokenBucketTimer.start(_messageDelay);
455 if (networkInfo().useSasl) {
456 putRawLine(serverEncode(QString("CAP REQ :sasl")));
458 if (!server.password.isEmpty()) {
459 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
462 if (identity->nicks().isEmpty()) {
464 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
467 nick = identity->nicks()[0];
469 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
470 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
474 void CoreNetwork::socketDisconnected()
476 disablePingTimeout();
479 _autoWhoCycleTimer.stop();
480 _autoWhoTimer.stop();
481 _autoWhoQueue.clear();
482 _autoWhoPending.clear();
484 _socketCloseTimer.stop();
486 _tokenBucketTimer.stop();
490 foreach(QString channel, me_->channels())
491 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
495 emit disconnected(networkId());
496 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
497 if (_quitRequested) {
498 _quitRequested = false;
499 setConnectionState(Network::Disconnected);
500 Core::setNetworkConnected(userId(), networkId(), false);
502 else if (_autoReconnectCount != 0) {
503 setConnectionState(Network::Reconnecting);
504 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
505 doAutoReconnect(); // first try is immediate
507 _autoReconnectTimer.start();
512 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
514 Network::ConnectionState state;
515 switch (socketState) {
516 case QAbstractSocket::UnconnectedState:
517 state = Network::Disconnected;
519 case QAbstractSocket::HostLookupState:
520 case QAbstractSocket::ConnectingState:
521 state = Network::Connecting;
523 case QAbstractSocket::ConnectedState:
524 state = Network::Initializing;
526 case QAbstractSocket::ClosingState:
527 state = Network::Disconnecting;
530 state = Network::Disconnected;
532 setConnectionState(state);
536 void CoreNetwork::networkInitialized()
538 setConnectionState(Network::Initialized);
540 _quitRequested = false;
542 if (useAutoReconnect()) {
544 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
547 // restore away state
548 QString awayMsg = Core::awayMessage(userId(), networkId());
549 if (!awayMsg.isEmpty())
550 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
556 if (networkConfig()->autoWhoEnabled()) {
557 _autoWhoCycleTimer.start();
558 _autoWhoTimer.start();
559 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
562 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
563 Core::setNetworkConnected(userId(), networkId(), true);
567 void CoreNetwork::sendPerform()
569 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
572 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
573 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
576 // restore old user modes if server default mode is set.
579 if (!me_->userModes().isEmpty()) {
583 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
584 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
589 foreach(QString line, perform()) {
590 if (!line.isEmpty()) userInput(statusBuf, line);
593 // rejoin channels we've been in
594 if (rejoinChannels()) {
595 QStringList channels, keys;
596 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
597 QString key = channelKey(chan);
598 if (!key.isEmpty()) {
599 channels.prepend(chan);
603 channels.append(chan);
606 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
607 if (!joinString.isEmpty())
608 userInputHandler()->handleJoin(statusBuf, joinString);
613 void CoreNetwork::restoreUserModes()
618 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
619 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
621 QString modesDelta = Core::userModes(userId(), networkId());
622 QString currentModes = me_->userModes();
624 QString addModes, removeModes;
625 if (modesDelta.contains('-')) {
626 addModes = modesDelta.section('-', 0, 0);
627 removeModes = modesDelta.section('-', 1);
630 addModes = modesDelta;
633 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
634 if (currentModes.isEmpty())
635 removeModes = QString();
637 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
639 if (addModes.isEmpty() && removeModes.isEmpty())
642 if (!addModes.isEmpty())
643 addModes = '+' + addModes;
644 if (!removeModes.isEmpty())
645 removeModes = '-' + removeModes;
647 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
648 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
652 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
658 for (int i = 0; i < requestedModes.length(); i++) {
659 if (requestedModes[i] == '+') {
663 if (requestedModes[i] == '-') {
668 addModes += requestedModes[i];
671 removeModes += requestedModes[i];
675 QString addModesOld = _requestedUserModes.section('-', 0, 0);
676 QString removeModesOld = _requestedUserModes.section('-', 1);
678 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
679 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
680 addModes += addModesOld;
682 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
683 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
684 removeModes += removeModesOld;
686 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
690 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
692 QString persistentUserModes = Core::userModes(userId(), networkId());
694 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
695 QString requestedRemove = _requestedUserModes.section('-', 1);
697 QString persistentAdd, persistentRemove;
698 if (persistentUserModes.contains('-')) {
699 persistentAdd = persistentUserModes.section('-', 0, 0);
700 persistentRemove = persistentUserModes.section('-', 1);
703 persistentAdd = persistentUserModes;
706 // remove modes we didn't issue
707 if (requestedAdd.isEmpty())
708 addModes = QString();
710 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
712 if (requestedRemove.isEmpty())
713 removeModes = QString();
715 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
718 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
719 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
722 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
723 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
725 // update issued mode list
726 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
727 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
728 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
730 persistentAdd += addModes;
731 persistentRemove += removeModes;
732 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
736 void CoreNetwork::resetPersistentModes()
738 _requestedUserModes = QString('-');
739 Core::setUserModes(userId(), networkId(), QString());
743 void CoreNetwork::setUseAutoReconnect(bool use)
745 Network::setUseAutoReconnect(use);
747 _autoReconnectTimer.stop();
751 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
753 Network::setAutoReconnectInterval(interval);
754 _autoReconnectTimer.setInterval(interval * 1000);
758 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
760 Network::setAutoReconnectRetries(retries);
761 if (_autoReconnectCount != 0) {
762 if (unlimitedReconnectRetries())
763 _autoReconnectCount = -1;
765 _autoReconnectCount = autoReconnectRetries();
770 void CoreNetwork::doAutoReconnect()
772 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
773 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
776 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
777 _autoReconnectCount--; // -2 means we delay the next reconnect
782 void CoreNetwork::sendPing()
784 uint now = QDateTime::currentDateTime().toTime_t();
785 if (_pingCount != 0) {
786 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
787 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
789 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
790 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
791 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
792 // and unable to even handle a ping answer. So we ignore those misses.
793 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
798 userInputHandler()->handlePing(BufferInfo(), QString());
803 void CoreNetwork::enablePingTimeout(bool enable)
806 disablePingTimeout();
809 if (networkConfig()->pingTimeoutEnabled())
815 void CoreNetwork::disablePingTimeout()
822 void CoreNetwork::setPingInterval(int interval)
824 _pingTimer.setInterval(interval * 1000);
828 /******** AutoWHO ********/
830 void CoreNetwork::startAutoWhoCycle()
832 if (!_autoWhoQueue.isEmpty()) {
833 _autoWhoCycleTimer.stop();
836 _autoWhoQueue = channels();
840 void CoreNetwork::setAutoWhoDelay(int delay)
842 _autoWhoTimer.setInterval(delay * 1000);
846 void CoreNetwork::setAutoWhoInterval(int interval)
848 _autoWhoCycleTimer.setInterval(interval * 1000);
852 void CoreNetwork::setAutoWhoEnabled(bool enabled)
854 if (enabled && isConnected() && !_autoWhoTimer.isActive())
855 _autoWhoTimer.start();
857 _autoWhoTimer.stop();
858 _autoWhoCycleTimer.stop();
863 void CoreNetwork::sendAutoWho()
865 // Don't send autowho if there are still some pending
866 if (_autoWhoPending.count())
869 while (!_autoWhoQueue.isEmpty()) {
870 QString chan = _autoWhoQueue.takeFirst();
871 IrcChannel *ircchan = ircChannel(chan);
872 if (!ircchan) continue;
873 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
875 _autoWhoPending[chan]++;
876 putRawLine("WHO " + serverEncode(chan));
879 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
880 // Timer was stopped, means a new cycle is due immediately
881 _autoWhoCycleTimer.start();
888 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
891 socket.ignoreSslErrors();
892 // TODO errorhandling
898 void CoreNetwork::fillBucketAndProcessQueue()
900 if (_tokenBucket < _burstSize) {
904 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
905 writeToSocket(_msgQueue.takeFirst());
910 void CoreNetwork::writeToSocket(const QByteArray &data)
913 socket.write("\r\n");
918 Network::Server CoreNetwork::usedServer() const
920 if (_lastUsedServerIndex < serverList().count())
921 return serverList()[_lastUsedServerIndex];
923 if (!serverList().isEmpty())
924 return serverList()[0];
926 return Network::Server();
930 void CoreNetwork::requestConnect() const
932 if (connectionState() != Disconnected) {
933 qWarning() << "Requesting connect while already being connected!";
936 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
940 void CoreNetwork::requestDisconnect() const
942 if (connectionState() == Disconnected) {
943 qWarning() << "Requesting disconnect while not being connected!";
946 userInputHandler()->handleQuit(BufferInfo(), QString());
950 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
952 Network::Server currentServer = usedServer();
953 setNetworkInfo(info);
954 Core::updateNetwork(coreSession()->user(), info);
956 // the order of the servers might have changed,
957 // so we try to find the previously used server
958 _lastUsedServerIndex = 0;
959 for (int i = 0; i < serverList().count(); i++) {
960 Network::Server server = serverList()[i];
961 if (server.host == currentServer.host && server.port == currentServer.port) {
962 _lastUsedServerIndex = i;