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),
39 _disconnectExpected(false),
41 _previousConnectionAttemptFailed(false),
42 _lastUsedServerIndex(0),
47 _requestedUserModes('-')
49 _autoReconnectTimer.setSingleShot(true);
50 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
52 setPingInterval(networkConfig()->pingInterval());
53 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
55 setAutoWhoDelay(networkConfig()->autoWhoDelay());
56 setAutoWhoInterval(networkConfig()->autoWhoInterval());
58 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
59 foreach(QString chan, channels.keys()) {
60 _channelKeys[chan.toLower()] = channels[chan];
63 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
64 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
65 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
66 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
67 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
69 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
70 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
71 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
72 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
74 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
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,
214 // Disconnecting from the network, should expect a socket close or error
215 _disconnectExpected = true;
216 _quitRequested = requested; // see socketDisconnected();
217 if (!withReconnect) {
218 _autoReconnectTimer.stop();
219 _autoReconnectCount = 0; // prohibiting auto reconnect
221 disablePingTimeout();
228 awayMsg = me_->awayMessage();
229 Core::setAwayMessage(userId(), networkId(), awayMsg);
232 if (reason.isEmpty() && identityPtr())
233 _quitReason = identityPtr()->quitReason();
235 _quitReason = reason;
237 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
238 if (socket.state() == QAbstractSocket::UnconnectedState) {
239 socketDisconnected();
241 if (socket.state() == QAbstractSocket::ConnectedState) {
242 userInputHandler()->issueQuit(_quitReason, forceImmediate);
246 if (requested || withReconnect) {
247 // the irc server has 10 seconds to close the socket
248 _socketCloseTimer.start(10000);
254 void CoreNetwork::userInput(BufferInfo buf, QString msg)
256 userInputHandler()->handleUserInput(buf, msg);
260 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
262 if (_tokenBucket > 0) {
266 _msgQueue.prepend(s);
274 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
278 if (!prefix.isEmpty())
279 msg += ":" + prefix + " ";
280 msg += cmd.toUpper().toLatin1();
282 for (int i = 0; i < params.size(); i++) {
285 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
291 putRawLine(msg, prepend);
295 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
297 QListIterator<QList<QByteArray>> i(params);
298 while (i.hasNext()) {
299 QList<QByteArray> msg = i.next();
300 putCmd(cmd, msg, prefix, prependAll);
305 void CoreNetwork::setChannelJoined(const QString &channel)
307 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
309 Core::setChannelPersistent(userId(), networkId(), channel, true);
310 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
314 void CoreNetwork::setChannelParted(const QString &channel)
316 removeChannelKey(channel);
317 _autoWhoQueue.removeAll(channel.toLower());
318 _autoWhoPending.remove(channel.toLower());
320 Core::setChannelPersistent(userId(), networkId(), channel, false);
324 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
327 removeChannelKey(channel);
330 _channelKeys[channel.toLower()] = key;
335 void CoreNetwork::removeChannelKey(const QString &channel)
337 _channelKeys.remove(channel.toLower());
342 Cipher *CoreNetwork::cipher(const QString &target)
344 if (target.isEmpty())
347 if (!Cipher::neededFeaturesAvailable())
350 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
352 return channel->cipher();
354 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
356 return user->cipher();
357 } else if (!isChannelName(target)) {
358 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
364 QByteArray CoreNetwork::cipherKey(const QString &target) const
366 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
368 return c->cipher()->key();
370 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
372 return u->cipher()->key();
378 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
380 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
382 c->setEncrypted(c->cipher()->setKey(key));
386 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
387 if (!u && !isChannelName(target))
388 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
391 u->setEncrypted(u->cipher()->setKey(key));
397 bool CoreNetwork::cipherUsesCBC(const QString &target)
399 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
401 return c->cipher()->usesCBC();
402 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
404 return u->cipher()->usesCBC();
408 #endif /* HAVE_QCA2 */
410 bool CoreNetwork::setAutoWhoDone(const QString &channel)
412 QString chan = channel.toLower();
413 if (_autoWhoPending.value(chan, 0) <= 0)
415 if (--_autoWhoPending[chan] <= 0)
416 _autoWhoPending.remove(chan);
421 void CoreNetwork::setMyNick(const QString &mynick)
423 Network::setMyNick(mynick);
424 if (connectionState() == Network::Initializing)
425 networkInitialized();
429 void CoreNetwork::socketHasData()
431 while (socket.canReadLine()) {
432 QByteArray s = socket.readLine();
433 if (s.endsWith("\r\n"))
435 else if (s.endsWith("\n"))
437 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
438 event->setTimestamp(QDateTime::currentDateTimeUtc());
439 emit newEvent(event);
444 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
446 // Ignore socket closed errors if expected
447 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
451 _previousConnectionAttemptFailed = true;
452 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
453 emit connectionError(socket.errorString());
454 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
455 emitConnectionError(socket.errorString());
456 if (socket.state() < QAbstractSocket::ConnectedState) {
457 socketDisconnected();
462 void CoreNetwork::socketInitialized()
464 CoreIdentity *identity = identityPtr();
466 qCritical() << "Identity invalid!";
471 Server server = usedServer();
474 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
475 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
476 if (!server.useSsl || !socket.isEncrypted()) {
477 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
480 if (server.useSsl && !socket.isEncrypted()) {
481 // We'll finish setup once we're encrypted, and called again
485 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
488 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
490 // TokenBucket to avoid sending too much at once
491 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
493 _tokenBucket = _burstSize; // init with a full bucket
494 _tokenBucketTimer.start(_messageDelay);
496 if (networkInfo().useSasl) {
497 putRawLine(serverEncode(QString("CAP REQ :sasl")));
499 if (!server.password.isEmpty()) {
500 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
503 if (identity->nicks().isEmpty()) {
505 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
508 nick = identity->nicks()[0];
510 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
511 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
515 void CoreNetwork::socketDisconnected()
517 disablePingTimeout();
520 _autoWhoCycleTimer.stop();
521 _autoWhoTimer.stop();
522 _autoWhoQueue.clear();
523 _autoWhoPending.clear();
525 _socketCloseTimer.stop();
527 _tokenBucketTimer.stop();
531 foreach(QString channel, me_->channels())
532 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
536 emit disconnected(networkId());
537 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
538 // Reset disconnect expectations
539 _disconnectExpected = false;
540 if (_quitRequested) {
541 _quitRequested = false;
542 setConnectionState(Network::Disconnected);
543 Core::setNetworkConnected(userId(), networkId(), false);
545 else if (_autoReconnectCount != 0) {
546 setConnectionState(Network::Reconnecting);
547 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
548 doAutoReconnect(); // first try is immediate
550 _autoReconnectTimer.start();
555 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
557 Network::ConnectionState state;
558 switch (socketState) {
559 case QAbstractSocket::UnconnectedState:
560 state = Network::Disconnected;
561 socketDisconnected();
563 case QAbstractSocket::HostLookupState:
564 case QAbstractSocket::ConnectingState:
565 state = Network::Connecting;
567 case QAbstractSocket::ConnectedState:
568 state = Network::Initializing;
570 case QAbstractSocket::ClosingState:
571 state = Network::Disconnecting;
574 state = Network::Disconnected;
576 setConnectionState(state);
580 void CoreNetwork::networkInitialized()
582 setConnectionState(Network::Initialized);
584 _disconnectExpected = false;
585 _quitRequested = false;
587 if (useAutoReconnect()) {
589 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
592 // restore away state
593 QString awayMsg = Core::awayMessage(userId(), networkId());
594 if (!awayMsg.isEmpty())
595 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
601 if (networkConfig()->autoWhoEnabled()) {
602 _autoWhoCycleTimer.start();
603 _autoWhoTimer.start();
604 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
607 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
608 Core::setNetworkConnected(userId(), networkId(), true);
612 void CoreNetwork::sendPerform()
614 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
617 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
618 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
621 // restore old user modes if server default mode is set.
624 if (!me_->userModes().isEmpty()) {
628 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
629 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
634 foreach(QString line, perform()) {
635 if (!line.isEmpty()) userInput(statusBuf, line);
638 // rejoin channels we've been in
639 if (rejoinChannels()) {
640 QStringList channels, keys;
641 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
642 QString key = channelKey(chan);
643 if (!key.isEmpty()) {
644 channels.prepend(chan);
648 channels.append(chan);
651 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
652 if (!joinString.isEmpty())
653 userInputHandler()->handleJoin(statusBuf, joinString);
658 void CoreNetwork::restoreUserModes()
663 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
664 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
666 QString modesDelta = Core::userModes(userId(), networkId());
667 QString currentModes = me_->userModes();
669 QString addModes, removeModes;
670 if (modesDelta.contains('-')) {
671 addModes = modesDelta.section('-', 0, 0);
672 removeModes = modesDelta.section('-', 1);
675 addModes = modesDelta;
678 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
679 if (currentModes.isEmpty())
680 removeModes = QString();
682 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
684 if (addModes.isEmpty() && removeModes.isEmpty())
687 if (!addModes.isEmpty())
688 addModes = '+' + addModes;
689 if (!removeModes.isEmpty())
690 removeModes = '-' + removeModes;
692 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
693 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
697 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
703 for (int i = 0; i < requestedModes.length(); i++) {
704 if (requestedModes[i] == '+') {
708 if (requestedModes[i] == '-') {
713 addModes += requestedModes[i];
716 removeModes += requestedModes[i];
720 QString addModesOld = _requestedUserModes.section('-', 0, 0);
721 QString removeModesOld = _requestedUserModes.section('-', 1);
723 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
724 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
725 addModes += addModesOld;
727 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
728 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
729 removeModes += removeModesOld;
731 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
735 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
737 QString persistentUserModes = Core::userModes(userId(), networkId());
739 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
740 QString requestedRemove = _requestedUserModes.section('-', 1);
742 QString persistentAdd, persistentRemove;
743 if (persistentUserModes.contains('-')) {
744 persistentAdd = persistentUserModes.section('-', 0, 0);
745 persistentRemove = persistentUserModes.section('-', 1);
748 persistentAdd = persistentUserModes;
751 // remove modes we didn't issue
752 if (requestedAdd.isEmpty())
753 addModes = QString();
755 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
757 if (requestedRemove.isEmpty())
758 removeModes = QString();
760 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
763 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
764 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
767 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
768 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
770 // update issued mode list
771 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
772 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
773 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
775 persistentAdd += addModes;
776 persistentRemove += removeModes;
777 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
781 void CoreNetwork::resetPersistentModes()
783 _requestedUserModes = QString('-');
784 Core::setUserModes(userId(), networkId(), QString());
788 void CoreNetwork::setUseAutoReconnect(bool use)
790 Network::setUseAutoReconnect(use);
792 _autoReconnectTimer.stop();
796 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
798 Network::setAutoReconnectInterval(interval);
799 _autoReconnectTimer.setInterval(interval * 1000);
803 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
805 Network::setAutoReconnectRetries(retries);
806 if (_autoReconnectCount != 0) {
807 if (unlimitedReconnectRetries())
808 _autoReconnectCount = -1;
810 _autoReconnectCount = autoReconnectRetries();
815 void CoreNetwork::doAutoReconnect()
817 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
818 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
821 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
822 _autoReconnectCount--; // -2 means we delay the next reconnect
827 void CoreNetwork::sendPing()
829 uint now = QDateTime::currentDateTime().toTime_t();
830 if (_pingCount != 0) {
831 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
832 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
834 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
835 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
836 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
837 // and unable to even handle a ping answer. So we ignore those misses.
838 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
843 // Don't send pings until the network is initialized
845 userInputHandler()->handlePing(BufferInfo(), QString());
850 void CoreNetwork::enablePingTimeout(bool enable)
853 disablePingTimeout();
856 if (networkConfig()->pingTimeoutEnabled())
862 void CoreNetwork::disablePingTimeout()
870 void CoreNetwork::setPingInterval(int interval)
872 _pingTimer.setInterval(interval * 1000);
876 /******** AutoWHO ********/
878 void CoreNetwork::startAutoWhoCycle()
880 if (!_autoWhoQueue.isEmpty()) {
881 _autoWhoCycleTimer.stop();
884 _autoWhoQueue = channels();
888 void CoreNetwork::setAutoWhoDelay(int delay)
890 _autoWhoTimer.setInterval(delay * 1000);
894 void CoreNetwork::setAutoWhoInterval(int interval)
896 _autoWhoCycleTimer.setInterval(interval * 1000);
900 void CoreNetwork::setAutoWhoEnabled(bool enabled)
902 if (enabled && isConnected() && !_autoWhoTimer.isActive())
903 _autoWhoTimer.start();
905 _autoWhoTimer.stop();
906 _autoWhoCycleTimer.stop();
911 void CoreNetwork::sendAutoWho()
913 // Don't send autowho if there are still some pending
914 if (_autoWhoPending.count())
917 while (!_autoWhoQueue.isEmpty()) {
918 QString chan = _autoWhoQueue.takeFirst();
919 IrcChannel *ircchan = ircChannel(chan);
920 if (!ircchan) continue;
921 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
923 _autoWhoPending[chan]++;
924 putRawLine("WHO " + serverEncode(chan));
927 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
928 // Timer was stopped, means a new cycle is due immediately
929 _autoWhoCycleTimer.start();
936 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
939 socket.ignoreSslErrors();
940 // TODO errorhandling
946 void CoreNetwork::fillBucketAndProcessQueue()
948 if (_tokenBucket < _burstSize) {
952 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
953 writeToSocket(_msgQueue.takeFirst());
958 void CoreNetwork::writeToSocket(const QByteArray &data)
961 socket.write("\r\n");
966 Network::Server CoreNetwork::usedServer() const
968 if (_lastUsedServerIndex < serverList().count())
969 return serverList()[_lastUsedServerIndex];
971 if (!serverList().isEmpty())
972 return serverList()[0];
974 return Network::Server();
978 void CoreNetwork::requestConnect() const
980 if (connectionState() != Disconnected) {
981 qWarning() << "Requesting connect while already being connected!";
984 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
988 void CoreNetwork::requestDisconnect() const
990 if (connectionState() == Disconnected) {
991 qWarning() << "Requesting disconnect while not being connected!";
994 userInputHandler()->handleQuit(BufferInfo(), QString());
998 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1000 Network::Server currentServer = usedServer();
1001 setNetworkInfo(info);
1002 Core::updateNetwork(coreSession()->user(), info);
1004 // the order of the servers might have changed,
1005 // so we try to find the previously used server
1006 _lastUsedServerIndex = 0;
1007 for (int i = 0; i < serverList().count(); i++) {
1008 Network::Server server = serverList()[i];
1009 if (server.host == currentServer.host && server.port == currentServer.port) {
1010 _lastUsedServerIndex = i;
1017 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1019 QString wrkMsg(message);
1020 QList<QList<QByteArray>> msgsToSend;
1022 // do while (wrkMsg.size() > 0)
1024 // First, check to see if the whole message can be sent at once. The
1025 // cmdGenerator function is passed in by the caller and is used to encode
1026 // and encrypt (if applicable) the message, since different callers might
1027 // want to use different encoding or encode different values.
1028 int splitPos = wrkMsg.size();
1029 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1030 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1032 if (initialOverrun) {
1033 // If the message was too long to be sent, first try splitting it along
1034 // word boundaries with QTextBoundaryFinder.
1035 QString splitMsg(wrkMsg);
1036 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1037 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1038 QList<QByteArray> splitMsgEnc;
1039 int overrun = initialOverrun;
1042 splitPos = qtbf.toPreviousBoundary();
1044 // splitPos==-1 means the QTBF couldn't find a split point at all and
1045 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1046 // the string. Neither one of these works for us.
1048 // If a split point could be found, split the message there, calculate the
1049 // overrun, and continue with the loop.
1050 splitMsg = splitMsg.left(splitPos);
1051 splitMsgEnc = cmdGenerator(splitMsg);
1052 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1055 // If a split point could not be found (the beginning of the message
1056 // is reached without finding a split point short enough to send) and we
1057 // are still in Word mode, switch to Grapheme mode. We also need to restore
1058 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1059 // the previous attempt to find a split point.
1060 if (qtbf.type() == QTextBoundaryFinder::Word) {
1062 splitPos = splitMsg.size();
1063 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1064 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1065 qtbf = graphemeQtbf;
1068 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1069 // This should never happen, but it should be handled anyway.
1070 qWarning() << "Unexpected failure to split message!";
1076 // Once a message of sendable length has been found, remove it from the wrkMsg and
1077 // add it to the list of messages to be sent.
1078 wrkMsg.remove(0, splitPos);
1079 msgsToSend.append(splitMsgEnc);
1082 // If the entire remaining message is short enough to be sent all at once, remove
1083 // it from the wrkMsg and add it to the list of messages to be sent.
1084 wrkMsg.remove(0, splitPos);
1085 msgsToSend.append(initialSplitMsgEnc);
1087 } while (wrkMsg.size() > 0);