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(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
75 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
76 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
78 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
79 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
81 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
83 if (Quassel::isOptionSet("oidentd")) {
84 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
85 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
90 CoreNetwork::~CoreNetwork()
92 if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
93 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
94 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
95 delete _userInputHandler;
99 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
101 if (!bufferName.isEmpty()) {
102 IrcChannel *channel = ircChannel(bufferName);
104 return channel->decodeString(string);
106 return decodeString(string);
110 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
112 IrcUser *user = ircUser(userNick);
114 return user->decodeString(string);
115 return decodeString(string);
119 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
121 if (!bufferName.isEmpty()) {
122 IrcChannel *channel = ircChannel(bufferName);
124 return channel->encodeString(string);
126 return encodeString(string);
130 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
132 IrcUser *user = ircUser(userNick);
134 return user->encodeString(string);
135 return encodeString(string);
139 void CoreNetwork::connectToIrc(bool reconnecting)
141 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
142 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
143 if (unlimitedReconnectRetries())
144 _autoReconnectCount = -1;
146 _autoReconnectCount = autoReconnectRetries();
148 if (serverList().isEmpty()) {
149 qWarning() << "Server list empty, ignoring connect request!";
152 CoreIdentity *identity = identityPtr();
154 qWarning() << "Invalid identity configures, ignoring connect request!";
158 // cleaning up old quit reason
161 // use a random server?
162 if (useRandomServer()) {
163 _lastUsedServerIndex = qrand() % serverList().size();
165 else if (_previousConnectionAttemptFailed) {
166 // cycle to next server if previous connection attempt failed
167 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
168 if (++_lastUsedServerIndex >= serverList().size()) {
169 _lastUsedServerIndex = 0;
172 _previousConnectionAttemptFailed = false;
174 Server server = usedServer();
175 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
176 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
178 if (server.useProxy) {
179 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
180 socket.setProxy(proxy);
183 socket.setProxy(QNetworkProxy::NoProxy);
188 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
189 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
190 QHostInfo::fromName(server.host);
194 CoreIdentity *identity = identityPtr();
196 socket.setLocalCertificate(identity->sslCert());
197 socket.setPrivateKey(identity->sslKey());
199 socket.connectToHostEncrypted(server.host, server.port);
202 socket.connectToHost(server.host, server.port);
205 socket.connectToHost(server.host, server.port);
210 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, forceImmediate);
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(const QByteArray s, const bool prepend)
259 if (_tokenBucket > 0) {
263 _msgQueue.prepend(s);
271 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
275 if (!prefix.isEmpty())
276 msg += ":" + prefix + " ";
277 msg += cmd.toUpper().toLatin1();
279 for (int i = 0; i < params.size(); i++) {
282 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
288 putRawLine(msg, prepend);
292 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
294 QListIterator<QList<QByteArray>> i(params);
295 while (i.hasNext()) {
296 QList<QByteArray> msg = i.next();
297 putCmd(cmd, msg, prefix, prependAll);
302 void CoreNetwork::setChannelJoined(const QString &channel)
304 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
306 Core::setChannelPersistent(userId(), networkId(), channel, true);
307 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
311 void CoreNetwork::setChannelParted(const QString &channel)
313 removeChannelKey(channel);
314 _autoWhoQueue.removeAll(channel.toLower());
315 _autoWhoPending.remove(channel.toLower());
317 Core::setChannelPersistent(userId(), networkId(), channel, false);
321 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
324 removeChannelKey(channel);
327 _channelKeys[channel.toLower()] = key;
332 void CoreNetwork::removeChannelKey(const QString &channel)
334 _channelKeys.remove(channel.toLower());
339 Cipher *CoreNetwork::cipher(const QString &target)
341 if (target.isEmpty())
344 if (!Cipher::neededFeaturesAvailable())
347 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
349 return channel->cipher();
351 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
353 return user->cipher();
354 } else if (!isChannelName(target)) {
355 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
361 QByteArray CoreNetwork::cipherKey(const QString &target) const
363 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
365 return c->cipher()->key();
367 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
369 return u->cipher()->key();
375 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
377 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
379 c->setEncrypted(c->cipher()->setKey(key));
383 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
384 if (!u && !isChannelName(target))
385 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
388 u->setEncrypted(u->cipher()->setKey(key));
394 bool CoreNetwork::cipherUsesCBC(const QString &target)
396 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
398 return c->cipher()->usesCBC();
399 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
401 return u->cipher()->usesCBC();
405 #endif /* HAVE_QCA2 */
407 bool CoreNetwork::setAutoWhoDone(const QString &channel)
409 QString chan = channel.toLower();
410 if (_autoWhoPending.value(chan, 0) <= 0)
412 if (--_autoWhoPending[chan] <= 0)
413 _autoWhoPending.remove(chan);
418 void CoreNetwork::setMyNick(const QString &mynick)
420 Network::setMyNick(mynick);
421 if (connectionState() == Network::Initializing)
422 networkInitialized();
426 void CoreNetwork::socketHasData()
428 while (socket.canReadLine()) {
429 QByteArray s = socket.readLine();
430 if (s.endsWith("\r\n"))
432 else if (s.endsWith("\n"))
434 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
435 event->setTimestamp(QDateTime::currentDateTimeUtc());
436 emit newEvent(event);
441 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
443 if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
446 _previousConnectionAttemptFailed = true;
447 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
448 emit connectionError(socket.errorString());
449 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
450 emitConnectionError(socket.errorString());
451 if (socket.state() < QAbstractSocket::ConnectedState) {
452 socketDisconnected();
457 void CoreNetwork::socketInitialized()
459 CoreIdentity *identity = identityPtr();
461 qCritical() << "Identity invalid!";
466 Server server = usedServer();
469 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
470 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
471 if (!server.useSsl || !socket.isEncrypted()) {
472 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
475 if (server.useSsl && !socket.isEncrypted()) {
476 // We'll finish setup once we're encrypted, and called again
480 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
483 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
485 // TokenBucket to avoid sending too much at once
486 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
488 _tokenBucket = _burstSize; // init with a full bucket
489 _tokenBucketTimer.start(_messageDelay);
491 if (networkInfo().useSasl) {
492 putRawLine(serverEncode(QString("CAP REQ :sasl")));
494 if (!server.password.isEmpty()) {
495 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
498 if (identity->nicks().isEmpty()) {
500 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
503 nick = identity->nicks()[0];
505 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
506 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
510 void CoreNetwork::socketDisconnected()
512 disablePingTimeout();
515 _autoWhoCycleTimer.stop();
516 _autoWhoTimer.stop();
517 _autoWhoQueue.clear();
518 _autoWhoPending.clear();
520 _socketCloseTimer.stop();
522 _tokenBucketTimer.stop();
526 foreach(QString channel, me_->channels())
527 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
531 emit disconnected(networkId());
532 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
533 if (_quitRequested) {
534 _quitRequested = false;
535 setConnectionState(Network::Disconnected);
536 Core::setNetworkConnected(userId(), networkId(), false);
538 else if (_autoReconnectCount != 0) {
539 setConnectionState(Network::Reconnecting);
540 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
541 doAutoReconnect(); // first try is immediate
543 _autoReconnectTimer.start();
548 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
550 Network::ConnectionState state;
551 switch (socketState) {
552 case QAbstractSocket::UnconnectedState:
553 state = Network::Disconnected;
554 socketDisconnected();
556 case QAbstractSocket::HostLookupState:
557 case QAbstractSocket::ConnectingState:
558 state = Network::Connecting;
560 case QAbstractSocket::ConnectedState:
561 state = Network::Initializing;
563 case QAbstractSocket::ClosingState:
564 state = Network::Disconnecting;
567 state = Network::Disconnected;
569 setConnectionState(state);
573 void CoreNetwork::networkInitialized()
575 setConnectionState(Network::Initialized);
577 _quitRequested = false;
579 if (useAutoReconnect()) {
581 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
584 // restore away state
585 QString awayMsg = Core::awayMessage(userId(), networkId());
586 if (!awayMsg.isEmpty())
587 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
593 if (networkConfig()->autoWhoEnabled()) {
594 _autoWhoCycleTimer.start();
595 _autoWhoTimer.start();
596 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
599 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
600 Core::setNetworkConnected(userId(), networkId(), true);
604 void CoreNetwork::sendPerform()
606 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
609 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
610 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
613 // restore old user modes if server default mode is set.
616 if (!me_->userModes().isEmpty()) {
620 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
621 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
626 foreach(QString line, perform()) {
627 if (!line.isEmpty()) userInput(statusBuf, line);
630 // rejoin channels we've been in
631 if (rejoinChannels()) {
632 QStringList channels, keys;
633 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
634 QString key = channelKey(chan);
635 if (!key.isEmpty()) {
636 channels.prepend(chan);
640 channels.append(chan);
643 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
644 if (!joinString.isEmpty())
645 userInputHandler()->handleJoin(statusBuf, joinString);
650 void CoreNetwork::restoreUserModes()
655 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
656 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
658 QString modesDelta = Core::userModes(userId(), networkId());
659 QString currentModes = me_->userModes();
661 QString addModes, removeModes;
662 if (modesDelta.contains('-')) {
663 addModes = modesDelta.section('-', 0, 0);
664 removeModes = modesDelta.section('-', 1);
667 addModes = modesDelta;
670 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
671 if (currentModes.isEmpty())
672 removeModes = QString();
674 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
676 if (addModes.isEmpty() && removeModes.isEmpty())
679 if (!addModes.isEmpty())
680 addModes = '+' + addModes;
681 if (!removeModes.isEmpty())
682 removeModes = '-' + removeModes;
684 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
685 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
689 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
695 for (int i = 0; i < requestedModes.length(); i++) {
696 if (requestedModes[i] == '+') {
700 if (requestedModes[i] == '-') {
705 addModes += requestedModes[i];
708 removeModes += requestedModes[i];
712 QString addModesOld = _requestedUserModes.section('-', 0, 0);
713 QString removeModesOld = _requestedUserModes.section('-', 1);
715 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
716 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
717 addModes += addModesOld;
719 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
720 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
721 removeModes += removeModesOld;
723 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
727 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
729 QString persistentUserModes = Core::userModes(userId(), networkId());
731 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
732 QString requestedRemove = _requestedUserModes.section('-', 1);
734 QString persistentAdd, persistentRemove;
735 if (persistentUserModes.contains('-')) {
736 persistentAdd = persistentUserModes.section('-', 0, 0);
737 persistentRemove = persistentUserModes.section('-', 1);
740 persistentAdd = persistentUserModes;
743 // remove modes we didn't issue
744 if (requestedAdd.isEmpty())
745 addModes = QString();
747 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
749 if (requestedRemove.isEmpty())
750 removeModes = QString();
752 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
755 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
756 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
759 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
760 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
762 // update issued mode list
763 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
764 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
765 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
767 persistentAdd += addModes;
768 persistentRemove += removeModes;
769 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
773 void CoreNetwork::resetPersistentModes()
775 _requestedUserModes = QString('-');
776 Core::setUserModes(userId(), networkId(), QString());
780 void CoreNetwork::setUseAutoReconnect(bool use)
782 Network::setUseAutoReconnect(use);
784 _autoReconnectTimer.stop();
788 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
790 Network::setAutoReconnectInterval(interval);
791 _autoReconnectTimer.setInterval(interval * 1000);
795 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
797 Network::setAutoReconnectRetries(retries);
798 if (_autoReconnectCount != 0) {
799 if (unlimitedReconnectRetries())
800 _autoReconnectCount = -1;
802 _autoReconnectCount = autoReconnectRetries();
807 void CoreNetwork::doAutoReconnect()
809 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
810 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
813 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
814 _autoReconnectCount--; // -2 means we delay the next reconnect
819 void CoreNetwork::sendPing()
821 uint now = QDateTime::currentDateTime().toTime_t();
822 if (_pingCount != 0) {
823 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
824 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
826 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
827 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
828 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
829 // and unable to even handle a ping answer. So we ignore those misses.
830 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
835 // Don't send pings until the network is initialized
837 userInputHandler()->handlePing(BufferInfo(), QString());
842 void CoreNetwork::enablePingTimeout(bool enable)
845 disablePingTimeout();
848 if (networkConfig()->pingTimeoutEnabled())
854 void CoreNetwork::disablePingTimeout()
862 void CoreNetwork::setPingInterval(int interval)
864 _pingTimer.setInterval(interval * 1000);
868 /******** AutoWHO ********/
870 void CoreNetwork::startAutoWhoCycle()
872 if (!_autoWhoQueue.isEmpty()) {
873 _autoWhoCycleTimer.stop();
876 _autoWhoQueue = channels();
880 void CoreNetwork::setAutoWhoDelay(int delay)
882 _autoWhoTimer.setInterval(delay * 1000);
886 void CoreNetwork::setAutoWhoInterval(int interval)
888 _autoWhoCycleTimer.setInterval(interval * 1000);
892 void CoreNetwork::setAutoWhoEnabled(bool enabled)
894 if (enabled && isConnected() && !_autoWhoTimer.isActive())
895 _autoWhoTimer.start();
897 _autoWhoTimer.stop();
898 _autoWhoCycleTimer.stop();
903 void CoreNetwork::sendAutoWho()
905 // Don't send autowho if there are still some pending
906 if (_autoWhoPending.count())
909 while (!_autoWhoQueue.isEmpty()) {
910 QString chan = _autoWhoQueue.takeFirst();
911 IrcChannel *ircchan = ircChannel(chan);
912 if (!ircchan) continue;
913 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
915 _autoWhoPending[chan]++;
916 putRawLine("WHO " + serverEncode(chan));
919 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
920 // Timer was stopped, means a new cycle is due immediately
921 _autoWhoCycleTimer.start();
928 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
931 socket.ignoreSslErrors();
932 // TODO errorhandling
938 void CoreNetwork::fillBucketAndProcessQueue()
940 if (_tokenBucket < _burstSize) {
944 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
945 writeToSocket(_msgQueue.takeFirst());
950 void CoreNetwork::writeToSocket(const QByteArray &data)
953 socket.write("\r\n");
958 Network::Server CoreNetwork::usedServer() const
960 if (_lastUsedServerIndex < serverList().count())
961 return serverList()[_lastUsedServerIndex];
963 if (!serverList().isEmpty())
964 return serverList()[0];
966 return Network::Server();
970 void CoreNetwork::requestConnect() const
972 if (connectionState() != Disconnected) {
973 qWarning() << "Requesting connect while already being connected!";
976 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
980 void CoreNetwork::requestDisconnect() const
982 if (connectionState() == Disconnected) {
983 qWarning() << "Requesting disconnect while not being connected!";
986 userInputHandler()->handleQuit(BufferInfo(), QString());
990 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
992 Network::Server currentServer = usedServer();
993 setNetworkInfo(info);
994 Core::updateNetwork(coreSession()->user(), info);
996 // the order of the servers might have changed,
997 // so we try to find the previously used server
998 _lastUsedServerIndex = 0;
999 for (int i = 0; i < serverList().count(); i++) {
1000 Network::Server server = serverList()[i];
1001 if (server.host == currentServer.host && server.port == currentServer.port) {
1002 _lastUsedServerIndex = i;
1009 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1011 QString wrkMsg(message);
1012 QList<QList<QByteArray>> msgsToSend;
1014 // do while (wrkMsg.size() > 0)
1016 // First, check to see if the whole message can be sent at once. The
1017 // cmdGenerator function is passed in by the caller and is used to encode
1018 // and encrypt (if applicable) the message, since different callers might
1019 // want to use different encoding or encode different values.
1020 int splitPos = wrkMsg.size();
1021 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1022 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1024 if (initialOverrun) {
1025 // If the message was too long to be sent, first try splitting it along
1026 // word boundaries with QTextBoundaryFinder.
1027 QString splitMsg(wrkMsg);
1028 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1029 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1030 QList<QByteArray> splitMsgEnc;
1031 int overrun = initialOverrun;
1034 splitPos = qtbf.toPreviousBoundary();
1036 // splitPos==-1 means the QTBF couldn't find a split point at all and
1037 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1038 // the string. Neither one of these works for us.
1040 // If a split point could be found, split the message there, calculate the
1041 // overrun, and continue with the loop.
1042 splitMsg = splitMsg.left(splitPos);
1043 splitMsgEnc = cmdGenerator(splitMsg);
1044 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1047 // If a split point could not be found (the beginning of the message
1048 // is reached without finding a split point short enough to send) and we
1049 // are still in Word mode, switch to Grapheme mode. We also need to restore
1050 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1051 // the previous attempt to find a split point.
1052 if (qtbf.type() == QTextBoundaryFinder::Word) {
1054 splitPos = splitMsg.size();
1055 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1056 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1057 qtbf = graphemeQtbf;
1060 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1061 // This should never happen, but it should be handled anyway.
1062 qWarning() << "Unexpected failure to split message!";
1068 // Once a message of sendable length has been found, remove it from the wrkMsg and
1069 // add it to the list of messages to be sent.
1070 wrkMsg.remove(0, splitPos);
1071 msgsToSend.append(splitMsgEnc);
1074 // If the entire remaining message is short enough to be sent all at once, remove
1075 // it from the wrkMsg and add it to the list of messages to be sent.
1076 wrkMsg.remove(0, splitPos);
1077 msgsToSend.append(initialSplitMsgEnc);
1079 } while (wrkMsg.size() > 0);