1 /***************************************************************************
2 * Copyright (C) 2005-2015 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
23 #include "corenetwork.h"
26 #include "coreidentity.h"
27 #include "corenetworkconfig.h"
28 #include "coresession.h"
29 #include "coreuserinputhandler.h"
30 #include "networkevent.h"
32 INIT_SYNCABLE_OBJECT(CoreNetwork)
33 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
34 : Network(networkid, session),
35 _coreSession(session),
36 _userInputHandler(new CoreUserInputHandler(this)),
37 _autoReconnectCount(0),
38 _quitRequested(false),
40 _previousConnectionAttemptFailed(false),
41 _lastUsedServerIndex(0),
46 _requestedUserModes('-')
48 _autoReconnectTimer.setSingleShot(true);
49 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
51 setPingInterval(networkConfig()->pingInterval());
52 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
54 setAutoWhoDelay(networkConfig()->autoWhoDelay());
55 setAutoWhoInterval(networkConfig()->autoWhoInterval());
57 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
58 foreach(QString chan, channels.keys()) {
59 _channelKeys[chan.toLower()] = channels[chan];
62 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
63 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
64 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
65 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
66 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
68 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
69 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
70 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
71 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
73 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
74 connect(&socket, SIGNAL(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(socketOpen(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 if (socket.state() == QAbstractSocket::UnconnectedState) {
236 socketDisconnected();
238 if (socket.state() == QAbstractSocket::ConnectedState) {
239 userInputHandler()->issueQuit(_quitReason);
243 if (requested || withReconnect) {
244 // the irc server has 10 seconds to close the socket
245 _socketCloseTimer.start(10000);
251 void CoreNetwork::userInput(BufferInfo buf, QString msg)
253 userInputHandler()->handleUserInput(buf, msg);
257 void CoreNetwork::putRawLine(QByteArray s)
259 if (_tokenBucket > 0)
266 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix)
270 if (!prefix.isEmpty())
271 msg += ":" + prefix + " ";
272 msg += cmd.toUpper().toLatin1();
274 for (int i = 0; i < params.size(); i++) {
277 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
287 void CoreNetwork::setChannelJoined(const QString &channel)
289 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
291 Core::setChannelPersistent(userId(), networkId(), channel, true);
292 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
296 void CoreNetwork::setChannelParted(const QString &channel)
298 removeChannelKey(channel);
299 _autoWhoQueue.removeAll(channel.toLower());
300 _autoWhoPending.remove(channel.toLower());
302 Core::setChannelPersistent(userId(), networkId(), channel, false);
306 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
309 removeChannelKey(channel);
312 _channelKeys[channel.toLower()] = key;
317 void CoreNetwork::removeChannelKey(const QString &channel)
319 _channelKeys.remove(channel.toLower());
324 Cipher *CoreNetwork::cipher(const QString &target)
326 if (target.isEmpty())
329 if (!Cipher::neededFeaturesAvailable())
332 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
334 return channel->cipher();
336 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
338 return user->cipher();
339 } else if (!isChannelName(target)) {
340 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
346 QByteArray CoreNetwork::cipherKey(const QString &target) const
348 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
350 return c->cipher()->key();
352 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
354 return u->cipher()->key();
360 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
362 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
364 c->setEncrypted(c->cipher()->setKey(key));
368 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
369 if (!u && !isChannelName(target))
370 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
373 u->setEncrypted(u->cipher()->setKey(key));
379 bool CoreNetwork::cipherUsesCBC(const QString &target)
381 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
383 return c->cipher()->usesCBC();
384 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
386 return u->cipher()->usesCBC();
390 #endif /* HAVE_QCA2 */
392 bool CoreNetwork::setAutoWhoDone(const QString &channel)
394 QString chan = channel.toLower();
395 if (_autoWhoPending.value(chan, 0) <= 0)
397 if (--_autoWhoPending[chan] <= 0)
398 _autoWhoPending.remove(chan);
403 void CoreNetwork::setMyNick(const QString &mynick)
405 Network::setMyNick(mynick);
406 if (connectionState() == Network::Initializing)
407 networkInitialized();
411 void CoreNetwork::socketHasData()
413 while (socket.canReadLine()) {
414 QByteArray s = socket.readLine();
415 if (s.endsWith("\r\n"))
417 else if (s.endsWith("\n"))
419 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
420 event->setTimestamp(QDateTime::currentDateTimeUtc());
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 CoreIdentity *identity = identityPtr();
446 qCritical() << "Identity invalid!";
451 emit socketOpen(identity, localAddress(), localPort(), peerAddress(), peerPort());
453 Server server = usedServer();
455 if (server.useSsl && !socket.isEncrypted())
458 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
460 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
462 // TokenBucket to avoid sending too much at once
463 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
465 _tokenBucket = _burstSize; // init with a full bucket
466 _tokenBucketTimer.start(_messageDelay);
468 if (networkInfo().useSasl) {
469 putRawLine(serverEncode(QString("CAP REQ :sasl")));
471 if (!server.password.isEmpty()) {
472 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
475 if (identity->nicks().isEmpty()) {
477 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
480 nick = identity->nicks()[0];
482 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
483 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
487 void CoreNetwork::socketDisconnected()
489 disablePingTimeout();
492 _autoWhoCycleTimer.stop();
493 _autoWhoTimer.stop();
494 _autoWhoQueue.clear();
495 _autoWhoPending.clear();
497 _socketCloseTimer.stop();
499 _tokenBucketTimer.stop();
503 foreach(QString channel, me_->channels())
504 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
508 emit disconnected(networkId());
509 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
510 if (_quitRequested) {
511 _quitRequested = false;
512 setConnectionState(Network::Disconnected);
513 Core::setNetworkConnected(userId(), networkId(), false);
515 else if (_autoReconnectCount != 0) {
516 setConnectionState(Network::Reconnecting);
517 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
518 doAutoReconnect(); // first try is immediate
520 _autoReconnectTimer.start();
525 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
527 Network::ConnectionState state;
528 switch (socketState) {
529 case QAbstractSocket::UnconnectedState:
530 state = Network::Disconnected;
532 case QAbstractSocket::HostLookupState:
533 case QAbstractSocket::ConnectingState:
534 state = Network::Connecting;
536 case QAbstractSocket::ConnectedState:
537 state = Network::Initializing;
539 case QAbstractSocket::ClosingState:
540 state = Network::Disconnecting;
543 state = Network::Disconnected;
545 setConnectionState(state);
549 void CoreNetwork::networkInitialized()
551 setConnectionState(Network::Initialized);
553 _quitRequested = false;
555 if (useAutoReconnect()) {
557 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
560 // restore away state
561 QString awayMsg = Core::awayMessage(userId(), networkId());
562 if (!awayMsg.isEmpty())
563 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
569 if (networkConfig()->autoWhoEnabled()) {
570 _autoWhoCycleTimer.start();
571 _autoWhoTimer.start();
572 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
575 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
576 Core::setNetworkConnected(userId(), networkId(), true);
580 void CoreNetwork::sendPerform()
582 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
585 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
586 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
589 // restore old user modes if server default mode is set.
592 if (!me_->userModes().isEmpty()) {
596 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
597 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
602 foreach(QString line, perform()) {
603 if (!line.isEmpty()) userInput(statusBuf, line);
606 // rejoin channels we've been in
607 if (rejoinChannels()) {
608 QStringList channels, keys;
609 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
610 QString key = channelKey(chan);
611 if (!key.isEmpty()) {
612 channels.prepend(chan);
616 channels.append(chan);
619 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
620 if (!joinString.isEmpty())
621 userInputHandler()->handleJoin(statusBuf, joinString);
626 void CoreNetwork::restoreUserModes()
631 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
632 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
634 QString modesDelta = Core::userModes(userId(), networkId());
635 QString currentModes = me_->userModes();
637 QString addModes, removeModes;
638 if (modesDelta.contains('-')) {
639 addModes = modesDelta.section('-', 0, 0);
640 removeModes = modesDelta.section('-', 1);
643 addModes = modesDelta;
646 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
647 if (currentModes.isEmpty())
648 removeModes = QString();
650 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
652 if (addModes.isEmpty() && removeModes.isEmpty())
655 if (!addModes.isEmpty())
656 addModes = '+' + addModes;
657 if (!removeModes.isEmpty())
658 removeModes = '-' + removeModes;
660 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
661 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
665 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
671 for (int i = 0; i < requestedModes.length(); i++) {
672 if (requestedModes[i] == '+') {
676 if (requestedModes[i] == '-') {
681 addModes += requestedModes[i];
684 removeModes += requestedModes[i];
688 QString addModesOld = _requestedUserModes.section('-', 0, 0);
689 QString removeModesOld = _requestedUserModes.section('-', 1);
691 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
692 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
693 addModes += addModesOld;
695 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
696 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
697 removeModes += removeModesOld;
699 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
703 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
705 QString persistentUserModes = Core::userModes(userId(), networkId());
707 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
708 QString requestedRemove = _requestedUserModes.section('-', 1);
710 QString persistentAdd, persistentRemove;
711 if (persistentUserModes.contains('-')) {
712 persistentAdd = persistentUserModes.section('-', 0, 0);
713 persistentRemove = persistentUserModes.section('-', 1);
716 persistentAdd = persistentUserModes;
719 // remove modes we didn't issue
720 if (requestedAdd.isEmpty())
721 addModes = QString();
723 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
725 if (requestedRemove.isEmpty())
726 removeModes = QString();
728 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
731 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
732 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
735 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
736 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
738 // update issued mode list
739 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
740 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
741 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
743 persistentAdd += addModes;
744 persistentRemove += removeModes;
745 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
749 void CoreNetwork::resetPersistentModes()
751 _requestedUserModes = QString('-');
752 Core::setUserModes(userId(), networkId(), QString());
756 void CoreNetwork::setUseAutoReconnect(bool use)
758 Network::setUseAutoReconnect(use);
760 _autoReconnectTimer.stop();
764 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
766 Network::setAutoReconnectInterval(interval);
767 _autoReconnectTimer.setInterval(interval * 1000);
771 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
773 Network::setAutoReconnectRetries(retries);
774 if (_autoReconnectCount != 0) {
775 if (unlimitedReconnectRetries())
776 _autoReconnectCount = -1;
778 _autoReconnectCount = autoReconnectRetries();
783 void CoreNetwork::doAutoReconnect()
785 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
786 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
789 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
790 _autoReconnectCount--; // -2 means we delay the next reconnect
795 void CoreNetwork::sendPing()
797 uint now = QDateTime::currentDateTime().toTime_t();
798 if (_pingCount != 0) {
799 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
800 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
802 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
803 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
804 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
805 // and unable to even handle a ping answer. So we ignore those misses.
806 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
811 // Don't send pings until the network is initialized
813 userInputHandler()->handlePing(BufferInfo(), QString());
818 void CoreNetwork::enablePingTimeout(bool enable)
821 disablePingTimeout();
824 if (networkConfig()->pingTimeoutEnabled())
830 void CoreNetwork::disablePingTimeout()
838 void CoreNetwork::setPingInterval(int interval)
840 _pingTimer.setInterval(interval * 1000);
844 /******** AutoWHO ********/
846 void CoreNetwork::startAutoWhoCycle()
848 if (!_autoWhoQueue.isEmpty()) {
849 _autoWhoCycleTimer.stop();
852 _autoWhoQueue = channels();
856 void CoreNetwork::setAutoWhoDelay(int delay)
858 _autoWhoTimer.setInterval(delay * 1000);
862 void CoreNetwork::setAutoWhoInterval(int interval)
864 _autoWhoCycleTimer.setInterval(interval * 1000);
868 void CoreNetwork::setAutoWhoEnabled(bool enabled)
870 if (enabled && isConnected() && !_autoWhoTimer.isActive())
871 _autoWhoTimer.start();
873 _autoWhoTimer.stop();
874 _autoWhoCycleTimer.stop();
879 void CoreNetwork::sendAutoWho()
881 // Don't send autowho if there are still some pending
882 if (_autoWhoPending.count())
885 while (!_autoWhoQueue.isEmpty()) {
886 QString chan = _autoWhoQueue.takeFirst();
887 IrcChannel *ircchan = ircChannel(chan);
888 if (!ircchan) continue;
889 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
891 _autoWhoPending[chan]++;
892 putRawLine("WHO " + serverEncode(chan));
895 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
896 // Timer was stopped, means a new cycle is due immediately
897 _autoWhoCycleTimer.start();
904 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
907 socket.ignoreSslErrors();
908 // TODO errorhandling
914 void CoreNetwork::fillBucketAndProcessQueue()
916 if (_tokenBucket < _burstSize) {
920 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
921 writeToSocket(_msgQueue.takeFirst());
926 void CoreNetwork::writeToSocket(const QByteArray &data)
929 socket.write("\r\n");
934 Network::Server CoreNetwork::usedServer() const
936 if (_lastUsedServerIndex < serverList().count())
937 return serverList()[_lastUsedServerIndex];
939 if (!serverList().isEmpty())
940 return serverList()[0];
942 return Network::Server();
946 void CoreNetwork::requestConnect() const
948 if (connectionState() != Disconnected) {
949 qWarning() << "Requesting connect while already being connected!";
952 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
956 void CoreNetwork::requestDisconnect() const
958 if (connectionState() == Disconnected) {
959 qWarning() << "Requesting disconnect while not being connected!";
962 userInputHandler()->handleQuit(BufferInfo(), QString());
966 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
968 Network::Server currentServer = usedServer();
969 setNetworkInfo(info);
970 Core::updateNetwork(coreSession()->user(), info);
972 // the order of the servers might have changed,
973 // so we try to find the previously used server
974 _lastUsedServerIndex = 0;
975 for (int i = 0; i < serverList().count(); i++) {
976 Network::Server server = serverList()[i];
977 if (server.host == currentServer.host && server.port == currentServer.port) {
978 _lastUsedServerIndex = i;