1 /***************************************************************************
2 * Copyright (C) 2005-2014 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);
189 CoreIdentity *identity = identityPtr();
191 socket.setLocalCertificate(identity->sslCert());
192 socket.setPrivateKey(identity->sslKey());
194 socket.connectToHostEncrypted(server.host, server.port);
197 socket.connectToHost(server.host, server.port);
200 socket.connectToHost(server.host, server.port);
205 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
207 _quitRequested = requested; // see socketDisconnected();
208 if (!withReconnect) {
209 _autoReconnectTimer.stop();
210 _autoReconnectCount = 0; // prohibiting auto reconnect
212 disablePingTimeout();
219 awayMsg = me_->awayMessage();
220 Core::setAwayMessage(userId(), networkId(), awayMsg);
223 if (reason.isEmpty() && identityPtr())
224 _quitReason = identityPtr()->quitReason();
226 _quitReason = reason;
228 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
229 switch (socket.state()) {
230 case QAbstractSocket::ConnectedState:
231 userInputHandler()->issueQuit(_quitReason);
232 if (requested || withReconnect) {
233 // the irc server has 10 seconds to close the socket
234 _socketCloseTimer.start(10000);
239 socketDisconnected();
244 void CoreNetwork::userInput(BufferInfo buf, QString msg)
246 userInputHandler()->handleUserInput(buf, msg);
250 void CoreNetwork::putRawLine(QByteArray s)
252 if (_tokenBucket > 0)
259 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix)
263 if (!prefix.isEmpty())
264 msg += ":" + prefix + " ";
265 msg += cmd.toUpper().toAscii();
267 for (int i = 0; i < params.size(); i++) {
270 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
280 void CoreNetwork::setChannelJoined(const QString &channel)
282 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
284 Core::setChannelPersistent(userId(), networkId(), channel, true);
285 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
289 void CoreNetwork::setChannelParted(const QString &channel)
291 removeChannelKey(channel);
292 _autoWhoQueue.removeAll(channel.toLower());
293 _autoWhoPending.remove(channel.toLower());
295 Core::setChannelPersistent(userId(), networkId(), channel, false);
299 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
302 removeChannelKey(channel);
305 _channelKeys[channel.toLower()] = key;
310 void CoreNetwork::removeChannelKey(const QString &channel)
312 _channelKeys.remove(channel.toLower());
317 Cipher *CoreNetwork::cipher(const QString &target)
319 if (target.isEmpty())
322 if (!Cipher::neededFeaturesAvailable())
325 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
327 return channel->cipher();
329 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
331 return user->cipher();
332 } else if (!isChannelName(target)) {
333 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
339 QByteArray CoreNetwork::cipherKey(const QString &target) const
341 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
343 return c->cipher()->key();
345 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
347 return u->cipher()->key();
353 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
355 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
357 c->setEncrypted(c->cipher()->setKey(key));
361 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
362 if (!u && !isChannelName(target))
363 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
366 u->setEncrypted(u->cipher()->setKey(key));
372 bool CoreNetwork::cipherUsesCBC(const QString &target)
374 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
376 return c->cipher()->usesCBC();
377 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
379 return u->cipher()->usesCBC();
383 #endif /* HAVE_QCA2 */
385 bool CoreNetwork::setAutoWhoDone(const QString &channel)
387 QString chan = channel.toLower();
388 if (_autoWhoPending.value(chan, 0) <= 0)
390 if (--_autoWhoPending[chan] <= 0)
391 _autoWhoPending.remove(chan);
396 void CoreNetwork::setMyNick(const QString &mynick)
398 Network::setMyNick(mynick);
399 if (connectionState() == Network::Initializing)
400 networkInitialized();
404 void CoreNetwork::socketHasData()
406 while (socket.canReadLine()) {
407 QByteArray s = socket.readLine();
409 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
410 #if QT_VERSION >= 0x040700
411 event->setTimestamp(QDateTime::currentDateTimeUtc());
413 event->setTimestamp(QDateTime::currentDateTime().toUTC());
415 emit newEvent(event);
420 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
422 if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
425 _previousConnectionAttemptFailed = true;
426 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
427 emit connectionError(socket.errorString());
428 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
429 emitConnectionError(socket.errorString());
430 if (socket.state() < QAbstractSocket::ConnectedState) {
431 socketDisconnected();
436 void CoreNetwork::socketInitialized()
438 Server server = usedServer();
440 if (server.useSsl && !socket.isEncrypted())
443 #if QT_VERSION >= 0x040600
444 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
446 CoreIdentity *identity = identityPtr();
448 qCritical() << "Identity invalid!";
453 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
455 // TokenBucket to avoid sending too much at once
456 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
458 _tokenBucket = _burstSize; // init with a full bucket
459 _tokenBucketTimer.start(_messageDelay);
461 if (networkInfo().useSasl) {
462 putRawLine(serverEncode(QString("CAP REQ :sasl")));
464 if (!server.password.isEmpty()) {
465 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
468 if (identity->nicks().isEmpty()) {
470 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
473 nick = identity->nicks()[0];
475 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
476 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
480 void CoreNetwork::socketDisconnected()
482 disablePingTimeout();
485 _autoWhoCycleTimer.stop();
486 _autoWhoTimer.stop();
487 _autoWhoQueue.clear();
488 _autoWhoPending.clear();
490 _socketCloseTimer.stop();
492 _tokenBucketTimer.stop();
496 foreach(QString channel, me_->channels())
497 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
501 emit disconnected(networkId());
502 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
503 if (_quitRequested) {
504 _quitRequested = false;
505 setConnectionState(Network::Disconnected);
506 Core::setNetworkConnected(userId(), networkId(), false);
508 else if (_autoReconnectCount != 0) {
509 setConnectionState(Network::Reconnecting);
510 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
511 doAutoReconnect(); // first try is immediate
513 _autoReconnectTimer.start();
518 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
520 Network::ConnectionState state;
521 switch (socketState) {
522 case QAbstractSocket::UnconnectedState:
523 state = Network::Disconnected;
525 case QAbstractSocket::HostLookupState:
526 case QAbstractSocket::ConnectingState:
527 state = Network::Connecting;
529 case QAbstractSocket::ConnectedState:
530 state = Network::Initializing;
532 case QAbstractSocket::ClosingState:
533 state = Network::Disconnecting;
536 state = Network::Disconnected;
538 setConnectionState(state);
542 void CoreNetwork::networkInitialized()
544 setConnectionState(Network::Initialized);
546 _quitRequested = false;
548 if (useAutoReconnect()) {
550 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
553 // restore away state
554 QString awayMsg = Core::awayMessage(userId(), networkId());
555 if (!awayMsg.isEmpty())
556 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
562 if (networkConfig()->autoWhoEnabled()) {
563 _autoWhoCycleTimer.start();
564 _autoWhoTimer.start();
565 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
568 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
569 Core::setNetworkConnected(userId(), networkId(), true);
573 void CoreNetwork::sendPerform()
575 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
578 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
579 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
582 // restore old user modes if server default mode is set.
585 if (!me_->userModes().isEmpty()) {
589 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
590 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
595 foreach(QString line, perform()) {
596 if (!line.isEmpty()) userInput(statusBuf, line);
599 // rejoin channels we've been in
600 if (rejoinChannels()) {
601 QStringList channels, keys;
602 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
603 QString key = channelKey(chan);
604 if (!key.isEmpty()) {
605 channels.prepend(chan);
609 channels.append(chan);
612 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
613 if (!joinString.isEmpty())
614 userInputHandler()->handleJoin(statusBuf, joinString);
619 void CoreNetwork::restoreUserModes()
624 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
625 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
627 QString modesDelta = Core::userModes(userId(), networkId());
628 QString currentModes = me_->userModes();
630 QString addModes, removeModes;
631 if (modesDelta.contains('-')) {
632 addModes = modesDelta.section('-', 0, 0);
633 removeModes = modesDelta.section('-', 1);
636 addModes = modesDelta;
639 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
640 if (currentModes.isEmpty())
641 removeModes = QString();
643 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
645 if (addModes.isEmpty() && removeModes.isEmpty())
648 if (!addModes.isEmpty())
649 addModes = '+' + addModes;
650 if (!removeModes.isEmpty())
651 removeModes = '-' + removeModes;
653 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
654 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
658 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
664 for (int i = 0; i < requestedModes.length(); i++) {
665 if (requestedModes[i] == '+') {
669 if (requestedModes[i] == '-') {
674 addModes += requestedModes[i];
677 removeModes += requestedModes[i];
681 QString addModesOld = _requestedUserModes.section('-', 0, 0);
682 QString removeModesOld = _requestedUserModes.section('-', 1);
684 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
685 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
686 addModes += addModesOld;
688 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
689 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
690 removeModes += removeModesOld;
692 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
696 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
698 QString persistentUserModes = Core::userModes(userId(), networkId());
700 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
701 QString requestedRemove = _requestedUserModes.section('-', 1);
703 QString persistentAdd, persistentRemove;
704 if (persistentUserModes.contains('-')) {
705 persistentAdd = persistentUserModes.section('-', 0, 0);
706 persistentRemove = persistentUserModes.section('-', 1);
709 persistentAdd = persistentUserModes;
712 // remove modes we didn't issue
713 if (requestedAdd.isEmpty())
714 addModes = QString();
716 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
718 if (requestedRemove.isEmpty())
719 removeModes = QString();
721 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
724 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
725 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
728 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
729 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
731 // update issued mode list
732 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
733 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
734 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
736 persistentAdd += addModes;
737 persistentRemove += removeModes;
738 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
742 void CoreNetwork::resetPersistentModes()
744 _requestedUserModes = QString('-');
745 Core::setUserModes(userId(), networkId(), QString());
749 void CoreNetwork::setUseAutoReconnect(bool use)
751 Network::setUseAutoReconnect(use);
753 _autoReconnectTimer.stop();
757 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
759 Network::setAutoReconnectInterval(interval);
760 _autoReconnectTimer.setInterval(interval * 1000);
764 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
766 Network::setAutoReconnectRetries(retries);
767 if (_autoReconnectCount != 0) {
768 if (unlimitedReconnectRetries())
769 _autoReconnectCount = -1;
771 _autoReconnectCount = autoReconnectRetries();
776 void CoreNetwork::doAutoReconnect()
778 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
779 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
782 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
783 _autoReconnectCount--; // -2 means we delay the next reconnect
788 void CoreNetwork::sendPing()
790 uint now = QDateTime::currentDateTime().toTime_t();
791 if (_pingCount != 0) {
792 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
793 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
795 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
796 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
797 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
798 // and unable to even handle a ping answer. So we ignore those misses.
799 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
804 // Don't send pings until the network is initialized
806 userInputHandler()->handlePing(BufferInfo(), QString());
811 void CoreNetwork::enablePingTimeout(bool enable)
814 disablePingTimeout();
817 if (networkConfig()->pingTimeoutEnabled())
823 void CoreNetwork::disablePingTimeout()
831 void CoreNetwork::setPingInterval(int interval)
833 _pingTimer.setInterval(interval * 1000);
837 /******** AutoWHO ********/
839 void CoreNetwork::startAutoWhoCycle()
841 if (!_autoWhoQueue.isEmpty()) {
842 _autoWhoCycleTimer.stop();
845 _autoWhoQueue = channels();
849 void CoreNetwork::setAutoWhoDelay(int delay)
851 _autoWhoTimer.setInterval(delay * 1000);
855 void CoreNetwork::setAutoWhoInterval(int interval)
857 _autoWhoCycleTimer.setInterval(interval * 1000);
861 void CoreNetwork::setAutoWhoEnabled(bool enabled)
863 if (enabled && isConnected() && !_autoWhoTimer.isActive())
864 _autoWhoTimer.start();
866 _autoWhoTimer.stop();
867 _autoWhoCycleTimer.stop();
872 void CoreNetwork::sendAutoWho()
874 // Don't send autowho if there are still some pending
875 if (_autoWhoPending.count())
878 while (!_autoWhoQueue.isEmpty()) {
879 QString chan = _autoWhoQueue.takeFirst();
880 IrcChannel *ircchan = ircChannel(chan);
881 if (!ircchan) continue;
882 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
884 _autoWhoPending[chan]++;
885 putRawLine("WHO " + serverEncode(chan));
888 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
889 // Timer was stopped, means a new cycle is due immediately
890 _autoWhoCycleTimer.start();
897 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
900 socket.ignoreSslErrors();
901 // TODO errorhandling
907 void CoreNetwork::fillBucketAndProcessQueue()
909 if (_tokenBucket < _burstSize) {
913 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
914 writeToSocket(_msgQueue.takeFirst());
919 void CoreNetwork::writeToSocket(const QByteArray &data)
922 socket.write("\r\n");
927 Network::Server CoreNetwork::usedServer() const
929 if (_lastUsedServerIndex < serverList().count())
930 return serverList()[_lastUsedServerIndex];
932 if (!serverList().isEmpty())
933 return serverList()[0];
935 return Network::Server();
939 void CoreNetwork::requestConnect() const
941 if (connectionState() != Disconnected) {
942 qWarning() << "Requesting connect while already being connected!";
945 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
949 void CoreNetwork::requestDisconnect() const
951 if (connectionState() == Disconnected) {
952 qWarning() << "Requesting disconnect while not being connected!";
955 userInputHandler()->handleQuit(BufferInfo(), QString());
959 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
961 Network::Server currentServer = usedServer();
962 setNetworkInfo(info);
963 Core::updateNetwork(coreSession()->user(), info);
965 // the order of the servers might have changed,
966 // so we try to find the previously used server
967 _lastUsedServerIndex = 0;
968 for (int i = 0; i < serverList().count(); i++) {
969 Network::Server server = serverList()[i];
970 if (server.host == currentServer.host && server.port == currentServer.port) {
971 _lastUsedServerIndex = i;