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 ***************************************************************************/
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(disconnected()), this, SLOT(socketDisconnected()));
75 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
76 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
77 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
79 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
80 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
82 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
84 if (Quassel::isOptionSet("oidentd")) {
85 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
86 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
91 CoreNetwork::~CoreNetwork()
93 if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
94 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
95 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
96 delete _userInputHandler;
100 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
102 if (!bufferName.isEmpty()) {
103 IrcChannel *channel = ircChannel(bufferName);
105 return channel->decodeString(string);
107 return decodeString(string);
111 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
113 IrcUser *user = ircUser(userNick);
115 return user->decodeString(string);
116 return decodeString(string);
120 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
122 if (!bufferName.isEmpty()) {
123 IrcChannel *channel = ircChannel(bufferName);
125 return channel->encodeString(string);
127 return encodeString(string);
131 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
133 IrcUser *user = ircUser(userNick);
135 return user->encodeString(string);
136 return encodeString(string);
140 void CoreNetwork::connectToIrc(bool reconnecting)
142 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
143 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
144 if (unlimitedReconnectRetries())
145 _autoReconnectCount = -1;
147 _autoReconnectCount = autoReconnectRetries();
149 if (serverList().isEmpty()) {
150 qWarning() << "Server list empty, ignoring connect request!";
153 CoreIdentity *identity = identityPtr();
155 qWarning() << "Invalid identity configures, ignoring connect request!";
159 // cleaning up old quit reason
162 // use a random server?
163 if (useRandomServer()) {
164 _lastUsedServerIndex = qrand() % serverList().size();
166 else if (_previousConnectionAttemptFailed) {
167 // cycle to next server if previous connection attempt failed
168 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
169 if (++_lastUsedServerIndex >= serverList().size()) {
170 _lastUsedServerIndex = 0;
173 _previousConnectionAttemptFailed = false;
175 Server server = usedServer();
176 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
177 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
179 if (server.useProxy) {
180 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
181 socket.setProxy(proxy);
184 socket.setProxy(QNetworkProxy::NoProxy);
189 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
190 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
191 QHostInfo::fromName(server.host);
195 CoreIdentity *identity = identityPtr();
197 socket.setLocalCertificate(identity->sslCert());
198 socket.setPrivateKey(identity->sslKey());
200 socket.connectToHostEncrypted(server.host, server.port);
203 socket.connectToHost(server.host, server.port);
206 socket.connectToHost(server.host, server.port);
211 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
213 _quitRequested = requested; // see socketDisconnected();
214 if (!withReconnect) {
215 _autoReconnectTimer.stop();
216 _autoReconnectCount = 0; // prohibiting auto reconnect
218 disablePingTimeout();
225 awayMsg = me_->awayMessage();
226 Core::setAwayMessage(userId(), networkId(), awayMsg);
229 if (reason.isEmpty() && identityPtr())
230 _quitReason = identityPtr()->quitReason();
232 _quitReason = reason;
234 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
235 switch (socket.state()) {
236 case QAbstractSocket::ConnectedState:
237 userInputHandler()->issueQuit(_quitReason);
238 if (requested || withReconnect) {
239 // the irc server has 10 seconds to close the socket
240 _socketCloseTimer.start(10000);
245 socketDisconnected();
250 void CoreNetwork::userInput(BufferInfo buf, QString msg)
252 userInputHandler()->handleUserInput(buf, msg);
256 void CoreNetwork::putRawLine(QByteArray s)
258 if (_tokenBucket > 0)
265 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix)
269 if (!prefix.isEmpty())
270 msg += ":" + prefix + " ";
271 msg += cmd.toUpper().toAscii();
273 for (int i = 0; i < params.size(); i++) {
276 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
286 void CoreNetwork::setChannelJoined(const QString &channel)
288 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
290 Core::setChannelPersistent(userId(), networkId(), channel, true);
291 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
295 void CoreNetwork::setChannelParted(const QString &channel)
297 removeChannelKey(channel);
298 _autoWhoQueue.removeAll(channel.toLower());
299 _autoWhoPending.remove(channel.toLower());
301 Core::setChannelPersistent(userId(), networkId(), channel, false);
305 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
308 removeChannelKey(channel);
311 _channelKeys[channel.toLower()] = key;
316 void CoreNetwork::removeChannelKey(const QString &channel)
318 _channelKeys.remove(channel.toLower());
323 Cipher *CoreNetwork::cipher(const QString &target)
325 if (target.isEmpty())
328 if (!Cipher::neededFeaturesAvailable())
331 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
333 return channel->cipher();
335 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
337 return user->cipher();
338 } else if (!isChannelName(target)) {
339 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
345 QByteArray CoreNetwork::cipherKey(const QString &target) const
347 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
349 return c->cipher()->key();
351 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
353 return u->cipher()->key();
359 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
361 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
363 c->setEncrypted(c->cipher()->setKey(key));
367 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
368 if (!u && !isChannelName(target))
369 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
372 u->setEncrypted(u->cipher()->setKey(key));
378 bool CoreNetwork::cipherUsesCBC(const QString &target)
380 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
382 return c->cipher()->usesCBC();
383 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
385 return u->cipher()->usesCBC();
389 #endif /* HAVE_QCA2 */
391 bool CoreNetwork::setAutoWhoDone(const QString &channel)
393 QString chan = channel.toLower();
394 if (_autoWhoPending.value(chan, 0) <= 0)
396 if (--_autoWhoPending[chan] <= 0)
397 _autoWhoPending.remove(chan);
402 void CoreNetwork::setMyNick(const QString &mynick)
404 Network::setMyNick(mynick);
405 if (connectionState() == Network::Initializing)
406 networkInitialized();
410 void CoreNetwork::socketHasData()
412 while (socket.canReadLine()) {
413 QByteArray s = socket.readLine();
415 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
416 #if QT_VERSION >= 0x040700
417 event->setTimestamp(QDateTime::currentDateTimeUtc());
419 event->setTimestamp(QDateTime::currentDateTime().toUTC());
421 emit newEvent(event);
426 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
428 if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
431 _previousConnectionAttemptFailed = true;
432 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
433 emit connectionError(socket.errorString());
434 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
435 emitConnectionError(socket.errorString());
436 if (socket.state() < QAbstractSocket::ConnectedState) {
437 socketDisconnected();
442 void CoreNetwork::socketInitialized()
444 Server server = usedServer();
446 if (server.useSsl && !socket.isEncrypted())
449 #if QT_VERSION >= 0x040600
450 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
452 CoreIdentity *identity = identityPtr();
454 qCritical() << "Identity invalid!";
459 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
461 // TokenBucket to avoid sending too much at once
462 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
464 _tokenBucket = _burstSize; // init with a full bucket
465 _tokenBucketTimer.start(_messageDelay);
467 if (networkInfo().useSasl) {
468 putRawLine(serverEncode(QString("CAP REQ :sasl")));
470 if (!server.password.isEmpty()) {
471 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
474 if (identity->nicks().isEmpty()) {
476 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
479 nick = identity->nicks()[0];
481 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
482 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
486 void CoreNetwork::socketDisconnected()
488 disablePingTimeout();
491 _autoWhoCycleTimer.stop();
492 _autoWhoTimer.stop();
493 _autoWhoQueue.clear();
494 _autoWhoPending.clear();
496 _socketCloseTimer.stop();
498 _tokenBucketTimer.stop();
502 foreach(QString channel, me_->channels())
503 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
507 emit disconnected(networkId());
508 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
509 if (_quitRequested) {
510 _quitRequested = false;
511 setConnectionState(Network::Disconnected);
512 Core::setNetworkConnected(userId(), networkId(), false);
514 else if (_autoReconnectCount != 0) {
515 setConnectionState(Network::Reconnecting);
516 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
517 doAutoReconnect(); // first try is immediate
519 _autoReconnectTimer.start();
524 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
526 Network::ConnectionState state;
527 switch (socketState) {
528 case QAbstractSocket::UnconnectedState:
529 state = Network::Disconnected;
531 case QAbstractSocket::HostLookupState:
532 case QAbstractSocket::ConnectingState:
533 state = Network::Connecting;
535 case QAbstractSocket::ConnectedState:
536 state = Network::Initializing;
538 case QAbstractSocket::ClosingState:
539 state = Network::Disconnecting;
542 state = Network::Disconnected;
544 setConnectionState(state);
548 void CoreNetwork::networkInitialized()
550 setConnectionState(Network::Initialized);
552 _quitRequested = false;
554 if (useAutoReconnect()) {
556 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
559 // restore away state
560 QString awayMsg = Core::awayMessage(userId(), networkId());
561 if (!awayMsg.isEmpty())
562 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
568 if (networkConfig()->autoWhoEnabled()) {
569 _autoWhoCycleTimer.start();
570 _autoWhoTimer.start();
571 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
574 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
575 Core::setNetworkConnected(userId(), networkId(), true);
579 void CoreNetwork::sendPerform()
581 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
584 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
585 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
588 // restore old user modes if server default mode is set.
591 if (!me_->userModes().isEmpty()) {
595 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
596 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
601 foreach(QString line, perform()) {
602 if (!line.isEmpty()) userInput(statusBuf, line);
605 // rejoin channels we've been in
606 if (rejoinChannels()) {
607 QStringList channels, keys;
608 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
609 QString key = channelKey(chan);
610 if (!key.isEmpty()) {
611 channels.prepend(chan);
615 channels.append(chan);
618 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
619 if (!joinString.isEmpty())
620 userInputHandler()->handleJoin(statusBuf, joinString);
625 void CoreNetwork::restoreUserModes()
630 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
631 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
633 QString modesDelta = Core::userModes(userId(), networkId());
634 QString currentModes = me_->userModes();
636 QString addModes, removeModes;
637 if (modesDelta.contains('-')) {
638 addModes = modesDelta.section('-', 0, 0);
639 removeModes = modesDelta.section('-', 1);
642 addModes = modesDelta;
645 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
646 if (currentModes.isEmpty())
647 removeModes = QString();
649 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
651 if (addModes.isEmpty() && removeModes.isEmpty())
654 if (!addModes.isEmpty())
655 addModes = '+' + addModes;
656 if (!removeModes.isEmpty())
657 removeModes = '-' + removeModes;
659 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
660 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
664 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
670 for (int i = 0; i < requestedModes.length(); i++) {
671 if (requestedModes[i] == '+') {
675 if (requestedModes[i] == '-') {
680 addModes += requestedModes[i];
683 removeModes += requestedModes[i];
687 QString addModesOld = _requestedUserModes.section('-', 0, 0);
688 QString removeModesOld = _requestedUserModes.section('-', 1);
690 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
691 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
692 addModes += addModesOld;
694 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
695 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
696 removeModes += removeModesOld;
698 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
702 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
704 QString persistentUserModes = Core::userModes(userId(), networkId());
706 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
707 QString requestedRemove = _requestedUserModes.section('-', 1);
709 QString persistentAdd, persistentRemove;
710 if (persistentUserModes.contains('-')) {
711 persistentAdd = persistentUserModes.section('-', 0, 0);
712 persistentRemove = persistentUserModes.section('-', 1);
715 persistentAdd = persistentUserModes;
718 // remove modes we didn't issue
719 if (requestedAdd.isEmpty())
720 addModes = QString();
722 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
724 if (requestedRemove.isEmpty())
725 removeModes = QString();
727 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
730 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
731 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
734 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
735 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
737 // update issued mode list
738 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
739 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
740 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
742 persistentAdd += addModes;
743 persistentRemove += removeModes;
744 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
748 void CoreNetwork::resetPersistentModes()
750 _requestedUserModes = QString('-');
751 Core::setUserModes(userId(), networkId(), QString());
755 void CoreNetwork::setUseAutoReconnect(bool use)
757 Network::setUseAutoReconnect(use);
759 _autoReconnectTimer.stop();
763 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
765 Network::setAutoReconnectInterval(interval);
766 _autoReconnectTimer.setInterval(interval * 1000);
770 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
772 Network::setAutoReconnectRetries(retries);
773 if (_autoReconnectCount != 0) {
774 if (unlimitedReconnectRetries())
775 _autoReconnectCount = -1;
777 _autoReconnectCount = autoReconnectRetries();
782 void CoreNetwork::doAutoReconnect()
784 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
785 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
788 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
789 _autoReconnectCount--; // -2 means we delay the next reconnect
794 void CoreNetwork::sendPing()
796 uint now = QDateTime::currentDateTime().toTime_t();
797 if (_pingCount != 0) {
798 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
799 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
801 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
802 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
803 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
804 // and unable to even handle a ping answer. So we ignore those misses.
805 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
810 // Don't send pings until the network is initialized
812 userInputHandler()->handlePing(BufferInfo(), QString());
817 void CoreNetwork::enablePingTimeout(bool enable)
820 disablePingTimeout();
823 if (networkConfig()->pingTimeoutEnabled())
829 void CoreNetwork::disablePingTimeout()
837 void CoreNetwork::setPingInterval(int interval)
839 _pingTimer.setInterval(interval * 1000);
843 /******** AutoWHO ********/
845 void CoreNetwork::startAutoWhoCycle()
847 if (!_autoWhoQueue.isEmpty()) {
848 _autoWhoCycleTimer.stop();
851 _autoWhoQueue = channels();
855 void CoreNetwork::setAutoWhoDelay(int delay)
857 _autoWhoTimer.setInterval(delay * 1000);
861 void CoreNetwork::setAutoWhoInterval(int interval)
863 _autoWhoCycleTimer.setInterval(interval * 1000);
867 void CoreNetwork::setAutoWhoEnabled(bool enabled)
869 if (enabled && isConnected() && !_autoWhoTimer.isActive())
870 _autoWhoTimer.start();
872 _autoWhoTimer.stop();
873 _autoWhoCycleTimer.stop();
878 void CoreNetwork::sendAutoWho()
880 // Don't send autowho if there are still some pending
881 if (_autoWhoPending.count())
884 while (!_autoWhoQueue.isEmpty()) {
885 QString chan = _autoWhoQueue.takeFirst();
886 IrcChannel *ircchan = ircChannel(chan);
887 if (!ircchan) continue;
888 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
890 _autoWhoPending[chan]++;
891 putRawLine("WHO " + serverEncode(chan));
894 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
895 // Timer was stopped, means a new cycle is due immediately
896 _autoWhoCycleTimer.start();
903 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
906 socket.ignoreSslErrors();
907 // TODO errorhandling
913 void CoreNetwork::fillBucketAndProcessQueue()
915 if (_tokenBucket < _burstSize) {
919 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
920 writeToSocket(_msgQueue.takeFirst());
925 void CoreNetwork::writeToSocket(const QByteArray &data)
928 socket.write("\r\n");
933 Network::Server CoreNetwork::usedServer() const
935 if (_lastUsedServerIndex < serverList().count())
936 return serverList()[_lastUsedServerIndex];
938 if (!serverList().isEmpty())
939 return serverList()[0];
941 return Network::Server();
945 void CoreNetwork::requestConnect() const
947 if (connectionState() != Disconnected) {
948 qWarning() << "Requesting connect while already being connected!";
951 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
955 void CoreNetwork::requestDisconnect() const
957 if (connectionState() == Disconnected) {
958 qWarning() << "Requesting disconnect while not being connected!";
961 userInputHandler()->handleQuit(BufferInfo(), QString());
965 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
967 Network::Server currentServer = usedServer();
968 setNetworkInfo(info);
969 Core::updateNetwork(coreSession()->user(), info);
971 // the order of the servers might have changed,
972 // so we try to find the previously used server
973 _lastUsedServerIndex = 0;
974 for (int i = 0; i < serverList().count(); i++) {
975 Network::Server server = serverList()[i];
976 if (server.host == currentServer.host && server.port == currentServer.port) {
977 _lastUsedServerIndex = i;