1 /***************************************************************************
2 * Copyright (C) 2005-2018 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 // Request a proper disconnect, but don't count as user-requested disconnect
94 if (socketConnected()) {
95 // Only try if the socket's fully connected (not initializing or disconnecting).
96 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
97 // shown even if other messages are queued.
98 disconnectFromIrc(false, QString(), false, true);
99 // Process the putCmd events that trigger the quit. Without this, shutting down the core
100 // results in abrubtly closing the socket rather than sending the QUIT as expected.
101 QCoreApplication::processEvents();
102 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
103 if (!forceDisconnect()) {
104 qWarning() << "Timed out quitting network" << networkName() <<
105 "(user ID " << userId() << ")";
108 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
109 delete _userInputHandler;
113 bool CoreNetwork::forceDisconnect(int msecs)
115 if (socket.state() == QAbstractSocket::UnconnectedState) {
116 // Socket already disconnected.
119 // Request a socket-level disconnect if not already happened
120 socket.disconnectFromHost();
121 // Return the result of waiting for disconnect; true if successful, otherwise false
122 return socket.waitForDisconnected(msecs);
126 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
128 if (!bufferName.isEmpty()) {
129 IrcChannel *channel = ircChannel(bufferName);
131 return channel->decodeString(string);
133 return decodeString(string);
137 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
139 IrcUser *user = ircUser(userNick);
141 return user->decodeString(string);
142 return decodeString(string);
146 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
148 if (!bufferName.isEmpty()) {
149 IrcChannel *channel = ircChannel(bufferName);
151 return channel->encodeString(string);
153 return encodeString(string);
157 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
159 IrcUser *user = ircUser(userNick);
161 return user->encodeString(string);
162 return encodeString(string);
166 void CoreNetwork::connectToIrc(bool reconnecting)
168 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
169 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
170 if (unlimitedReconnectRetries())
171 _autoReconnectCount = -1;
173 _autoReconnectCount = autoReconnectRetries();
175 if (serverList().isEmpty()) {
176 qWarning() << "Server list empty, ignoring connect request!";
179 CoreIdentity *identity = identityPtr();
181 qWarning() << "Invalid identity configures, ignoring connect request!";
185 // cleaning up old quit reason
188 // use a random server?
189 if (useRandomServer()) {
190 _lastUsedServerIndex = qrand() % serverList().size();
192 else if (_previousConnectionAttemptFailed) {
193 // cycle to next server if previous connection attempt failed
194 _previousConnectionAttemptFailed = false;
195 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
196 if (++_lastUsedServerIndex >= serverList().size()) {
197 _lastUsedServerIndex = 0;
201 // Start out with the top server in the list
202 _lastUsedServerIndex = 0;
205 Server server = usedServer();
206 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
207 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
209 if (server.useProxy) {
210 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
211 socket.setProxy(proxy);
214 socket.setProxy(QNetworkProxy::NoProxy);
219 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
220 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
221 if (! server.useProxy) {
222 //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
223 //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
224 QHostInfo::fromName(server.host);
228 CoreIdentity *identity = identityPtr();
230 socket.setLocalCertificate(identity->sslCert());
231 socket.setPrivateKey(identity->sslKey());
233 socket.connectToHostEncrypted(server.host, server.port);
236 socket.connectToHost(server.host, server.port);
239 socket.connectToHost(server.host, server.port);
244 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
247 // Disconnecting from the network, should expect a socket close or error
248 _disconnectExpected = true;
249 _quitRequested = requested; // see socketDisconnected();
250 if (!withReconnect) {
251 _autoReconnectTimer.stop();
252 _autoReconnectCount = 0; // prohibiting auto reconnect
254 disablePingTimeout();
261 awayMsg = me_->awayMessage();
262 Core::setAwayMessage(userId(), networkId(), awayMsg);
265 if (reason.isEmpty() && identityPtr())
266 _quitReason = identityPtr()->quitReason();
268 _quitReason = reason;
270 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
271 if (socket.state() == QAbstractSocket::UnconnectedState) {
272 socketDisconnected();
274 if (socket.state() == QAbstractSocket::ConnectedState) {
275 userInputHandler()->issueQuit(_quitReason, forceImmediate);
279 if (requested || withReconnect) {
280 // the irc server has 10 seconds to close the socket
281 _socketCloseTimer.start(10000);
287 void CoreNetwork::userInput(BufferInfo buf, QString msg)
289 userInputHandler()->handleUserInput(buf, msg);
293 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
295 if (_tokenBucket > 0) {
299 _msgQueue.prepend(s);
307 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
311 if (!prefix.isEmpty())
312 msg += ":" + prefix + " ";
313 msg += cmd.toUpper().toLatin1();
315 for (int i = 0; i < params.size(); i++) {
318 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
324 putRawLine(msg, prepend);
328 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
330 QListIterator<QList<QByteArray>> i(params);
331 while (i.hasNext()) {
332 QList<QByteArray> msg = i.next();
333 putCmd(cmd, msg, prefix, prependAll);
338 void CoreNetwork::setChannelJoined(const QString &channel)
340 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
342 Core::setChannelPersistent(userId(), networkId(), channel, true);
343 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
347 void CoreNetwork::setChannelParted(const QString &channel)
349 removeChannelKey(channel);
350 _autoWhoQueue.removeAll(channel.toLower());
351 _autoWhoPending.remove(channel.toLower());
353 Core::setChannelPersistent(userId(), networkId(), channel, false);
357 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
360 removeChannelKey(channel);
363 _channelKeys[channel.toLower()] = key;
368 void CoreNetwork::removeChannelKey(const QString &channel)
370 _channelKeys.remove(channel.toLower());
375 Cipher *CoreNetwork::cipher(const QString &target)
377 if (target.isEmpty())
380 if (!Cipher::neededFeaturesAvailable())
383 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
385 return channel->cipher();
387 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
389 return user->cipher();
390 } else if (!isChannelName(target)) {
391 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
397 QByteArray CoreNetwork::cipherKey(const QString &target) const
399 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
401 return c->cipher()->key();
403 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
405 return u->cipher()->key();
411 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
413 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
415 c->setEncrypted(c->cipher()->setKey(key));
419 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
420 if (!u && !isChannelName(target))
421 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
424 u->setEncrypted(u->cipher()->setKey(key));
430 bool CoreNetwork::cipherUsesCBC(const QString &target)
432 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
434 return c->cipher()->usesCBC();
435 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
437 return u->cipher()->usesCBC();
441 #endif /* HAVE_QCA2 */
443 bool CoreNetwork::setAutoWhoDone(const QString &channel)
445 QString chan = channel.toLower();
446 if (_autoWhoPending.value(chan, 0) <= 0)
448 if (--_autoWhoPending[chan] <= 0)
449 _autoWhoPending.remove(chan);
454 void CoreNetwork::setMyNick(const QString &mynick)
456 Network::setMyNick(mynick);
457 if (connectionState() == Network::Initializing)
458 networkInitialized();
462 void CoreNetwork::socketHasData()
464 while (socket.canReadLine()) {
465 QByteArray s = socket.readLine();
466 if (s.endsWith("\r\n"))
468 else if (s.endsWith("\n"))
470 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
471 event->setTimestamp(QDateTime::currentDateTimeUtc());
472 emit newEvent(event);
477 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
479 // Ignore socket closed errors if expected
480 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
484 _previousConnectionAttemptFailed = true;
485 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
486 emit connectionError(socket.errorString());
487 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
488 emitConnectionError(socket.errorString());
489 if (socket.state() < QAbstractSocket::ConnectedState) {
490 socketDisconnected();
495 void CoreNetwork::socketInitialized()
497 CoreIdentity *identity = identityPtr();
499 qCritical() << "Identity invalid!";
504 Server server = usedServer();
507 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
508 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
509 if (!server.useSsl || !socket.isEncrypted()) {
510 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
513 if (server.useSsl && !socket.isEncrypted()) {
514 // We'll finish setup once we're encrypted, and called again
518 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
521 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
523 // TokenBucket to avoid sending too much at once
524 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
526 _tokenBucket = _burstSize; // init with a full bucket
527 _tokenBucketTimer.start(_messageDelay);
529 if (networkInfo().useSasl) {
530 putRawLine(serverEncode(QString("CAP REQ :sasl")));
532 if (!server.password.isEmpty()) {
533 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
536 if (identity->nicks().isEmpty()) {
538 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
541 nick = identity->nicks()[0];
543 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
544 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
548 void CoreNetwork::socketDisconnected()
550 disablePingTimeout();
553 _autoWhoCycleTimer.stop();
554 _autoWhoTimer.stop();
555 _autoWhoQueue.clear();
556 _autoWhoPending.clear();
558 _socketCloseTimer.stop();
560 _tokenBucketTimer.stop();
564 foreach(QString channel, me_->channels())
565 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
569 emit disconnected(networkId());
570 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
571 // Reset disconnect expectations
572 _disconnectExpected = false;
573 if (_quitRequested) {
574 _quitRequested = false;
575 setConnectionState(Network::Disconnected);
576 Core::setNetworkConnected(userId(), networkId(), false);
578 else if (_autoReconnectCount != 0) {
579 setConnectionState(Network::Reconnecting);
580 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
581 doAutoReconnect(); // first try is immediate
583 _autoReconnectTimer.start();
588 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
590 Network::ConnectionState state;
591 switch (socketState) {
592 case QAbstractSocket::UnconnectedState:
593 state = Network::Disconnected;
594 socketDisconnected();
596 case QAbstractSocket::HostLookupState:
597 case QAbstractSocket::ConnectingState:
598 state = Network::Connecting;
600 case QAbstractSocket::ConnectedState:
601 state = Network::Initializing;
603 case QAbstractSocket::ClosingState:
604 state = Network::Disconnecting;
607 state = Network::Disconnected;
609 setConnectionState(state);
613 void CoreNetwork::networkInitialized()
615 setConnectionState(Network::Initialized);
617 _disconnectExpected = false;
618 _quitRequested = false;
620 if (useAutoReconnect()) {
622 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
625 // restore away state
626 QString awayMsg = Core::awayMessage(userId(), networkId());
627 if (!awayMsg.isEmpty())
628 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
634 if (networkConfig()->autoWhoEnabled()) {
635 _autoWhoCycleTimer.start();
636 _autoWhoTimer.start();
637 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
640 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
641 Core::setNetworkConnected(userId(), networkId(), true);
645 void CoreNetwork::sendPerform()
647 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
650 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
651 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
654 // restore old user modes if server default mode is set.
657 if (!me_->userModes().isEmpty()) {
661 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
662 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
667 foreach(QString line, perform()) {
668 if (!line.isEmpty()) userInput(statusBuf, line);
671 // rejoin channels we've been in
672 if (rejoinChannels()) {
673 QStringList channels, keys;
674 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
675 QString key = channelKey(chan);
676 if (!key.isEmpty()) {
677 channels.prepend(chan);
681 channels.append(chan);
684 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
685 if (!joinString.isEmpty())
686 userInputHandler()->handleJoin(statusBuf, joinString);
691 void CoreNetwork::restoreUserModes()
696 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
697 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
699 QString modesDelta = Core::userModes(userId(), networkId());
700 QString currentModes = me_->userModes();
702 QString addModes, removeModes;
703 if (modesDelta.contains('-')) {
704 addModes = modesDelta.section('-', 0, 0);
705 removeModes = modesDelta.section('-', 1);
708 addModes = modesDelta;
711 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
712 if (currentModes.isEmpty())
713 removeModes = QString();
715 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
717 if (addModes.isEmpty() && removeModes.isEmpty())
720 if (!addModes.isEmpty())
721 addModes = '+' + addModes;
722 if (!removeModes.isEmpty())
723 removeModes = '-' + removeModes;
725 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
726 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
730 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
736 for (int i = 0; i < requestedModes.length(); i++) {
737 if (requestedModes[i] == '+') {
741 if (requestedModes[i] == '-') {
746 addModes += requestedModes[i];
749 removeModes += requestedModes[i];
753 QString addModesOld = _requestedUserModes.section('-', 0, 0);
754 QString removeModesOld = _requestedUserModes.section('-', 1);
756 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
757 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
758 addModes += addModesOld;
760 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
761 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
762 removeModes += removeModesOld;
764 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
768 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
770 QString persistentUserModes = Core::userModes(userId(), networkId());
772 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
773 QString requestedRemove = _requestedUserModes.section('-', 1);
775 QString persistentAdd, persistentRemove;
776 if (persistentUserModes.contains('-')) {
777 persistentAdd = persistentUserModes.section('-', 0, 0);
778 persistentRemove = persistentUserModes.section('-', 1);
781 persistentAdd = persistentUserModes;
784 // remove modes we didn't issue
785 if (requestedAdd.isEmpty())
786 addModes = QString();
788 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
790 if (requestedRemove.isEmpty())
791 removeModes = QString();
793 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
796 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
797 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
800 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
801 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
803 // update issued mode list
804 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
805 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
806 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
808 persistentAdd += addModes;
809 persistentRemove += removeModes;
810 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
814 void CoreNetwork::resetPersistentModes()
816 _requestedUserModes = QString('-');
817 Core::setUserModes(userId(), networkId(), QString());
821 void CoreNetwork::setUseAutoReconnect(bool use)
823 Network::setUseAutoReconnect(use);
825 _autoReconnectTimer.stop();
829 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
831 Network::setAutoReconnectInterval(interval);
832 _autoReconnectTimer.setInterval(interval * 1000);
836 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
838 Network::setAutoReconnectRetries(retries);
839 if (_autoReconnectCount != 0) {
840 if (unlimitedReconnectRetries())
841 _autoReconnectCount = -1;
843 _autoReconnectCount = autoReconnectRetries();
848 void CoreNetwork::doAutoReconnect()
850 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
851 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
854 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
855 _autoReconnectCount--; // -2 means we delay the next reconnect
860 void CoreNetwork::sendPing()
862 uint now = QDateTime::currentDateTime().toTime_t();
863 if (_pingCount != 0) {
864 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
865 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
867 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
868 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
869 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
870 // and unable to even handle a ping answer. So we ignore those misses.
871 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
876 // Don't send pings until the network is initialized
878 userInputHandler()->handlePing(BufferInfo(), QString());
883 void CoreNetwork::enablePingTimeout(bool enable)
886 disablePingTimeout();
889 if (networkConfig()->pingTimeoutEnabled())
895 void CoreNetwork::disablePingTimeout()
903 void CoreNetwork::setPingInterval(int interval)
905 _pingTimer.setInterval(interval * 1000);
909 /******** AutoWHO ********/
911 void CoreNetwork::startAutoWhoCycle()
913 if (!_autoWhoQueue.isEmpty()) {
914 _autoWhoCycleTimer.stop();
917 _autoWhoQueue = channels();
921 void CoreNetwork::setAutoWhoDelay(int delay)
923 _autoWhoTimer.setInterval(delay * 1000);
927 void CoreNetwork::setAutoWhoInterval(int interval)
929 _autoWhoCycleTimer.setInterval(interval * 1000);
933 void CoreNetwork::setAutoWhoEnabled(bool enabled)
935 if (enabled && isConnected() && !_autoWhoTimer.isActive())
936 _autoWhoTimer.start();
938 _autoWhoTimer.stop();
939 _autoWhoCycleTimer.stop();
944 void CoreNetwork::sendAutoWho()
946 // Don't send autowho if there are still some pending
947 if (_autoWhoPending.count())
950 while (!_autoWhoQueue.isEmpty()) {
951 QString chan = _autoWhoQueue.takeFirst();
952 IrcChannel *ircchan = ircChannel(chan);
953 if (!ircchan) continue;
954 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
956 _autoWhoPending[chan]++;
957 putRawLine("WHO " + serverEncode(chan));
960 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
961 // Timer was stopped, means a new cycle is due immediately
962 _autoWhoCycleTimer.start();
969 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
972 socket.ignoreSslErrors();
973 // TODO errorhandling
979 void CoreNetwork::fillBucketAndProcessQueue()
981 if (_tokenBucket < _burstSize) {
985 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
986 writeToSocket(_msgQueue.takeFirst());
991 void CoreNetwork::writeToSocket(const QByteArray &data)
994 socket.write("\r\n");
999 Network::Server CoreNetwork::usedServer() const
1001 if (_lastUsedServerIndex < serverList().count())
1002 return serverList()[_lastUsedServerIndex];
1004 if (!serverList().isEmpty())
1005 return serverList()[0];
1007 return Network::Server();
1011 void CoreNetwork::requestConnect() const
1013 if (connectionState() != Disconnected) {
1014 qWarning() << "Requesting connect while already being connected!";
1017 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1021 void CoreNetwork::requestDisconnect() const
1023 if (connectionState() == Disconnected) {
1024 qWarning() << "Requesting disconnect while not being connected!";
1027 userInputHandler()->handleQuit(BufferInfo(), QString());
1031 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1033 Network::Server currentServer = usedServer();
1034 setNetworkInfo(info);
1035 Core::updateNetwork(coreSession()->user(), info);
1037 // the order of the servers might have changed,
1038 // so we try to find the previously used server
1039 _lastUsedServerIndex = 0;
1040 for (int i = 0; i < serverList().count(); i++) {
1041 Network::Server server = serverList()[i];
1042 if (server.host == currentServer.host && server.port == currentServer.port) {
1043 _lastUsedServerIndex = i;
1050 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1052 QString wrkMsg(message);
1053 QList<QList<QByteArray>> msgsToSend;
1055 // do while (wrkMsg.size() > 0)
1057 // First, check to see if the whole message can be sent at once. The
1058 // cmdGenerator function is passed in by the caller and is used to encode
1059 // and encrypt (if applicable) the message, since different callers might
1060 // want to use different encoding or encode different values.
1061 int splitPos = wrkMsg.size();
1062 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1063 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1065 if (initialOverrun) {
1066 // If the message was too long to be sent, first try splitting it along
1067 // word boundaries with QTextBoundaryFinder.
1068 QString splitMsg(wrkMsg);
1069 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1070 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1071 QList<QByteArray> splitMsgEnc;
1072 int overrun = initialOverrun;
1075 splitPos = qtbf.toPreviousBoundary();
1077 // splitPos==-1 means the QTBF couldn't find a split point at all and
1078 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1079 // the string. Neither one of these works for us.
1081 // If a split point could be found, split the message there, calculate the
1082 // overrun, and continue with the loop.
1083 splitMsg = splitMsg.left(splitPos);
1084 splitMsgEnc = cmdGenerator(splitMsg);
1085 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1088 // If a split point could not be found (the beginning of the message
1089 // is reached without finding a split point short enough to send) and we
1090 // are still in Word mode, switch to Grapheme mode. We also need to restore
1091 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1092 // the previous attempt to find a split point.
1093 if (qtbf.type() == QTextBoundaryFinder::Word) {
1095 splitPos = splitMsg.size();
1096 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1097 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1098 qtbf = graphemeQtbf;
1101 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1102 // This should never happen, but it should be handled anyway.
1103 qWarning() << "Unexpected failure to split message!";
1109 // Once a message of sendable length has been found, remove it from the wrkMsg and
1110 // add it to the list of messages to be sent.
1111 wrkMsg.remove(0, splitPos);
1112 msgsToSend.append(splitMsgEnc);
1115 // If the entire remaining message is short enough to be sent all at once, remove
1116 // it from the wrkMsg and add it to the list of messages to be sent.
1117 wrkMsg.remove(0, splitPos);
1118 msgsToSend.append(initialSplitMsgEnc);
1120 } while (wrkMsg.size() > 0);