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 // 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 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
195 if (++_lastUsedServerIndex >= serverList().size()) {
196 _lastUsedServerIndex = 0;
199 _previousConnectionAttemptFailed = false;
201 Server server = usedServer();
202 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
203 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
205 if (server.useProxy) {
206 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
207 socket.setProxy(proxy);
210 socket.setProxy(QNetworkProxy::NoProxy);
215 // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
216 // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
217 QHostInfo::fromName(server.host);
221 CoreIdentity *identity = identityPtr();
223 socket.setLocalCertificate(identity->sslCert());
224 socket.setPrivateKey(identity->sslKey());
226 socket.connectToHostEncrypted(server.host, server.port);
229 socket.connectToHost(server.host, server.port);
232 socket.connectToHost(server.host, server.port);
237 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
240 // Disconnecting from the network, should expect a socket close or error
241 _disconnectExpected = true;
242 _quitRequested = requested; // see socketDisconnected();
243 if (!withReconnect) {
244 _autoReconnectTimer.stop();
245 _autoReconnectCount = 0; // prohibiting auto reconnect
247 disablePingTimeout();
254 awayMsg = me_->awayMessage();
255 Core::setAwayMessage(userId(), networkId(), awayMsg);
258 if (reason.isEmpty() && identityPtr())
259 _quitReason = identityPtr()->quitReason();
261 _quitReason = reason;
263 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
264 if (socket.state() == QAbstractSocket::UnconnectedState) {
265 socketDisconnected();
267 if (socket.state() == QAbstractSocket::ConnectedState) {
268 userInputHandler()->issueQuit(_quitReason, forceImmediate);
272 if (requested || withReconnect) {
273 // the irc server has 10 seconds to close the socket
274 _socketCloseTimer.start(10000);
280 void CoreNetwork::userInput(BufferInfo buf, QString msg)
282 userInputHandler()->handleUserInput(buf, msg);
286 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
288 if (_tokenBucket > 0) {
292 _msgQueue.prepend(s);
300 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
304 if (!prefix.isEmpty())
305 msg += ":" + prefix + " ";
306 msg += cmd.toUpper().toLatin1();
308 for (int i = 0; i < params.size(); i++) {
311 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
317 putRawLine(msg, prepend);
321 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
323 QListIterator<QList<QByteArray>> i(params);
324 while (i.hasNext()) {
325 QList<QByteArray> msg = i.next();
326 putCmd(cmd, msg, prefix, prependAll);
331 void CoreNetwork::setChannelJoined(const QString &channel)
333 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
335 Core::setChannelPersistent(userId(), networkId(), channel, true);
336 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
340 void CoreNetwork::setChannelParted(const QString &channel)
342 removeChannelKey(channel);
343 _autoWhoQueue.removeAll(channel.toLower());
344 _autoWhoPending.remove(channel.toLower());
346 Core::setChannelPersistent(userId(), networkId(), channel, false);
350 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
353 removeChannelKey(channel);
356 _channelKeys[channel.toLower()] = key;
361 void CoreNetwork::removeChannelKey(const QString &channel)
363 _channelKeys.remove(channel.toLower());
368 Cipher *CoreNetwork::cipher(const QString &target)
370 if (target.isEmpty())
373 if (!Cipher::neededFeaturesAvailable())
376 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
378 return channel->cipher();
380 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
382 return user->cipher();
383 } else if (!isChannelName(target)) {
384 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
390 QByteArray CoreNetwork::cipherKey(const QString &target) const
392 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
394 return c->cipher()->key();
396 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
398 return u->cipher()->key();
404 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
406 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
408 c->setEncrypted(c->cipher()->setKey(key));
412 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
413 if (!u && !isChannelName(target))
414 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
417 u->setEncrypted(u->cipher()->setKey(key));
423 bool CoreNetwork::cipherUsesCBC(const QString &target)
425 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
427 return c->cipher()->usesCBC();
428 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
430 return u->cipher()->usesCBC();
434 #endif /* HAVE_QCA2 */
436 bool CoreNetwork::setAutoWhoDone(const QString &channel)
438 QString chan = channel.toLower();
439 if (_autoWhoPending.value(chan, 0) <= 0)
441 if (--_autoWhoPending[chan] <= 0)
442 _autoWhoPending.remove(chan);
447 void CoreNetwork::setMyNick(const QString &mynick)
449 Network::setMyNick(mynick);
450 if (connectionState() == Network::Initializing)
451 networkInitialized();
455 void CoreNetwork::socketHasData()
457 while (socket.canReadLine()) {
458 QByteArray s = socket.readLine();
459 if (s.endsWith("\r\n"))
461 else if (s.endsWith("\n"))
463 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
464 event->setTimestamp(QDateTime::currentDateTimeUtc());
465 emit newEvent(event);
470 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
472 // Ignore socket closed errors if expected
473 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
477 _previousConnectionAttemptFailed = true;
478 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
479 emit connectionError(socket.errorString());
480 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
481 emitConnectionError(socket.errorString());
482 if (socket.state() < QAbstractSocket::ConnectedState) {
483 socketDisconnected();
488 void CoreNetwork::socketInitialized()
490 CoreIdentity *identity = identityPtr();
492 qCritical() << "Identity invalid!";
497 Server server = usedServer();
500 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
501 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
502 if (!server.useSsl || !socket.isEncrypted()) {
503 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
506 if (server.useSsl && !socket.isEncrypted()) {
507 // We'll finish setup once we're encrypted, and called again
511 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
514 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
516 // TokenBucket to avoid sending too much at once
517 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
519 _tokenBucket = _burstSize; // init with a full bucket
520 _tokenBucketTimer.start(_messageDelay);
522 if (networkInfo().useSasl) {
523 putRawLine(serverEncode(QString("CAP REQ :sasl")));
525 if (!server.password.isEmpty()) {
526 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
529 if (identity->nicks().isEmpty()) {
531 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
534 nick = identity->nicks()[0];
536 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
537 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
541 void CoreNetwork::socketDisconnected()
543 disablePingTimeout();
546 _autoWhoCycleTimer.stop();
547 _autoWhoTimer.stop();
548 _autoWhoQueue.clear();
549 _autoWhoPending.clear();
551 _socketCloseTimer.stop();
553 _tokenBucketTimer.stop();
557 foreach(QString channel, me_->channels())
558 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
562 emit disconnected(networkId());
563 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
564 // Reset disconnect expectations
565 _disconnectExpected = false;
566 if (_quitRequested) {
567 _quitRequested = false;
568 setConnectionState(Network::Disconnected);
569 Core::setNetworkConnected(userId(), networkId(), false);
571 else if (_autoReconnectCount != 0) {
572 setConnectionState(Network::Reconnecting);
573 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
574 doAutoReconnect(); // first try is immediate
576 _autoReconnectTimer.start();
581 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
583 Network::ConnectionState state;
584 switch (socketState) {
585 case QAbstractSocket::UnconnectedState:
586 state = Network::Disconnected;
587 socketDisconnected();
589 case QAbstractSocket::HostLookupState:
590 case QAbstractSocket::ConnectingState:
591 state = Network::Connecting;
593 case QAbstractSocket::ConnectedState:
594 state = Network::Initializing;
596 case QAbstractSocket::ClosingState:
597 state = Network::Disconnecting;
600 state = Network::Disconnected;
602 setConnectionState(state);
606 void CoreNetwork::networkInitialized()
608 setConnectionState(Network::Initialized);
610 _disconnectExpected = false;
611 _quitRequested = false;
613 if (useAutoReconnect()) {
615 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
618 // restore away state
619 QString awayMsg = Core::awayMessage(userId(), networkId());
620 if (!awayMsg.isEmpty())
621 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
627 if (networkConfig()->autoWhoEnabled()) {
628 _autoWhoCycleTimer.start();
629 _autoWhoTimer.start();
630 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
633 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
634 Core::setNetworkConnected(userId(), networkId(), true);
638 void CoreNetwork::sendPerform()
640 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
643 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
644 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
647 // restore old user modes if server default mode is set.
650 if (!me_->userModes().isEmpty()) {
654 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
655 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
660 foreach(QString line, perform()) {
661 if (!line.isEmpty()) userInput(statusBuf, line);
664 // rejoin channels we've been in
665 if (rejoinChannels()) {
666 QStringList channels, keys;
667 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
668 QString key = channelKey(chan);
669 if (!key.isEmpty()) {
670 channels.prepend(chan);
674 channels.append(chan);
677 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
678 if (!joinString.isEmpty())
679 userInputHandler()->handleJoin(statusBuf, joinString);
684 void CoreNetwork::restoreUserModes()
689 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
690 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
692 QString modesDelta = Core::userModes(userId(), networkId());
693 QString currentModes = me_->userModes();
695 QString addModes, removeModes;
696 if (modesDelta.contains('-')) {
697 addModes = modesDelta.section('-', 0, 0);
698 removeModes = modesDelta.section('-', 1);
701 addModes = modesDelta;
704 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
705 if (currentModes.isEmpty())
706 removeModes = QString();
708 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
710 if (addModes.isEmpty() && removeModes.isEmpty())
713 if (!addModes.isEmpty())
714 addModes = '+' + addModes;
715 if (!removeModes.isEmpty())
716 removeModes = '-' + removeModes;
718 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
719 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
723 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
729 for (int i = 0; i < requestedModes.length(); i++) {
730 if (requestedModes[i] == '+') {
734 if (requestedModes[i] == '-') {
739 addModes += requestedModes[i];
742 removeModes += requestedModes[i];
746 QString addModesOld = _requestedUserModes.section('-', 0, 0);
747 QString removeModesOld = _requestedUserModes.section('-', 1);
749 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
750 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
751 addModes += addModesOld;
753 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
754 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
755 removeModes += removeModesOld;
757 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
761 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
763 QString persistentUserModes = Core::userModes(userId(), networkId());
765 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
766 QString requestedRemove = _requestedUserModes.section('-', 1);
768 QString persistentAdd, persistentRemove;
769 if (persistentUserModes.contains('-')) {
770 persistentAdd = persistentUserModes.section('-', 0, 0);
771 persistentRemove = persistentUserModes.section('-', 1);
774 persistentAdd = persistentUserModes;
777 // remove modes we didn't issue
778 if (requestedAdd.isEmpty())
779 addModes = QString();
781 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
783 if (requestedRemove.isEmpty())
784 removeModes = QString();
786 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
789 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
790 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
793 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
794 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
796 // update issued mode list
797 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
798 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
799 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
801 persistentAdd += addModes;
802 persistentRemove += removeModes;
803 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
807 void CoreNetwork::resetPersistentModes()
809 _requestedUserModes = QString('-');
810 Core::setUserModes(userId(), networkId(), QString());
814 void CoreNetwork::setUseAutoReconnect(bool use)
816 Network::setUseAutoReconnect(use);
818 _autoReconnectTimer.stop();
822 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
824 Network::setAutoReconnectInterval(interval);
825 _autoReconnectTimer.setInterval(interval * 1000);
829 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
831 Network::setAutoReconnectRetries(retries);
832 if (_autoReconnectCount != 0) {
833 if (unlimitedReconnectRetries())
834 _autoReconnectCount = -1;
836 _autoReconnectCount = autoReconnectRetries();
841 void CoreNetwork::doAutoReconnect()
843 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
844 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
847 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
848 _autoReconnectCount--; // -2 means we delay the next reconnect
853 void CoreNetwork::sendPing()
855 uint now = QDateTime::currentDateTime().toTime_t();
856 if (_pingCount != 0) {
857 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
858 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
860 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
861 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
862 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
863 // and unable to even handle a ping answer. So we ignore those misses.
864 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
869 // Don't send pings until the network is initialized
871 userInputHandler()->handlePing(BufferInfo(), QString());
876 void CoreNetwork::enablePingTimeout(bool enable)
879 disablePingTimeout();
882 if (networkConfig()->pingTimeoutEnabled())
888 void CoreNetwork::disablePingTimeout()
896 void CoreNetwork::setPingInterval(int interval)
898 _pingTimer.setInterval(interval * 1000);
902 /******** AutoWHO ********/
904 void CoreNetwork::startAutoWhoCycle()
906 if (!_autoWhoQueue.isEmpty()) {
907 _autoWhoCycleTimer.stop();
910 _autoWhoQueue = channels();
914 void CoreNetwork::setAutoWhoDelay(int delay)
916 _autoWhoTimer.setInterval(delay * 1000);
920 void CoreNetwork::setAutoWhoInterval(int interval)
922 _autoWhoCycleTimer.setInterval(interval * 1000);
926 void CoreNetwork::setAutoWhoEnabled(bool enabled)
928 if (enabled && isConnected() && !_autoWhoTimer.isActive())
929 _autoWhoTimer.start();
931 _autoWhoTimer.stop();
932 _autoWhoCycleTimer.stop();
937 void CoreNetwork::sendAutoWho()
939 // Don't send autowho if there are still some pending
940 if (_autoWhoPending.count())
943 while (!_autoWhoQueue.isEmpty()) {
944 QString chan = _autoWhoQueue.takeFirst();
945 IrcChannel *ircchan = ircChannel(chan);
946 if (!ircchan) continue;
947 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
949 _autoWhoPending[chan]++;
950 putRawLine("WHO " + serverEncode(chan));
953 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
954 // Timer was stopped, means a new cycle is due immediately
955 _autoWhoCycleTimer.start();
962 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
965 socket.ignoreSslErrors();
966 // TODO errorhandling
972 void CoreNetwork::fillBucketAndProcessQueue()
974 if (_tokenBucket < _burstSize) {
978 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
979 writeToSocket(_msgQueue.takeFirst());
984 void CoreNetwork::writeToSocket(const QByteArray &data)
987 socket.write("\r\n");
992 Network::Server CoreNetwork::usedServer() const
994 if (_lastUsedServerIndex < serverList().count())
995 return serverList()[_lastUsedServerIndex];
997 if (!serverList().isEmpty())
998 return serverList()[0];
1000 return Network::Server();
1004 void CoreNetwork::requestConnect() const
1006 if (connectionState() != Disconnected) {
1007 qWarning() << "Requesting connect while already being connected!";
1010 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1014 void CoreNetwork::requestDisconnect() const
1016 if (connectionState() == Disconnected) {
1017 qWarning() << "Requesting disconnect while not being connected!";
1020 userInputHandler()->handleQuit(BufferInfo(), QString());
1024 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1026 Network::Server currentServer = usedServer();
1027 setNetworkInfo(info);
1028 Core::updateNetwork(coreSession()->user(), info);
1030 // the order of the servers might have changed,
1031 // so we try to find the previously used server
1032 _lastUsedServerIndex = 0;
1033 for (int i = 0; i < serverList().count(); i++) {
1034 Network::Server server = serverList()[i];
1035 if (server.host == currentServer.host && server.port == currentServer.port) {
1036 _lastUsedServerIndex = i;
1043 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1045 QString wrkMsg(message);
1046 QList<QList<QByteArray>> msgsToSend;
1048 // do while (wrkMsg.size() > 0)
1050 // First, check to see if the whole message can be sent at once. The
1051 // cmdGenerator function is passed in by the caller and is used to encode
1052 // and encrypt (if applicable) the message, since different callers might
1053 // want to use different encoding or encode different values.
1054 int splitPos = wrkMsg.size();
1055 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1056 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1058 if (initialOverrun) {
1059 // If the message was too long to be sent, first try splitting it along
1060 // word boundaries with QTextBoundaryFinder.
1061 QString splitMsg(wrkMsg);
1062 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1063 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1064 QList<QByteArray> splitMsgEnc;
1065 int overrun = initialOverrun;
1068 splitPos = qtbf.toPreviousBoundary();
1070 // splitPos==-1 means the QTBF couldn't find a split point at all and
1071 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1072 // the string. Neither one of these works for us.
1074 // If a split point could be found, split the message there, calculate the
1075 // overrun, and continue with the loop.
1076 splitMsg = splitMsg.left(splitPos);
1077 splitMsgEnc = cmdGenerator(splitMsg);
1078 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1081 // If a split point could not be found (the beginning of the message
1082 // is reached without finding a split point short enough to send) and we
1083 // are still in Word mode, switch to Grapheme mode. We also need to restore
1084 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1085 // the previous attempt to find a split point.
1086 if (qtbf.type() == QTextBoundaryFinder::Word) {
1088 splitPos = splitMsg.size();
1089 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1090 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1091 qtbf = graphemeQtbf;
1094 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1095 // This should never happen, but it should be handled anyway.
1096 qWarning() << "Unexpected failure to split message!";
1102 // Once a message of sendable length has been found, remove it from the wrkMsg and
1103 // add it to the list of messages to be sent.
1104 wrkMsg.remove(0, splitPos);
1105 msgsToSend.append(splitMsgEnc);
1108 // If the entire remaining message is short enough to be sent all at once, remove
1109 // it from the wrkMsg and add it to the list of messages to be sent.
1110 wrkMsg.remove(0, splitPos);
1111 msgsToSend.append(initialSplitMsgEnc);
1113 } while (wrkMsg.size() > 0);