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 _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 QHostInfo::fromName(server.host);
225 CoreIdentity *identity = identityPtr();
227 socket.setLocalCertificate(identity->sslCert());
228 socket.setPrivateKey(identity->sslKey());
230 socket.connectToHostEncrypted(server.host, server.port);
233 socket.connectToHost(server.host, server.port);
236 socket.connectToHost(server.host, server.port);
241 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
244 // Disconnecting from the network, should expect a socket close or error
245 _disconnectExpected = true;
246 _quitRequested = requested; // see socketDisconnected();
247 if (!withReconnect) {
248 _autoReconnectTimer.stop();
249 _autoReconnectCount = 0; // prohibiting auto reconnect
251 disablePingTimeout();
258 awayMsg = me_->awayMessage();
259 Core::setAwayMessage(userId(), networkId(), awayMsg);
262 if (reason.isEmpty() && identityPtr())
263 _quitReason = identityPtr()->quitReason();
265 _quitReason = reason;
267 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
268 if (socket.state() == QAbstractSocket::UnconnectedState) {
269 socketDisconnected();
271 if (socket.state() == QAbstractSocket::ConnectedState) {
272 userInputHandler()->issueQuit(_quitReason, forceImmediate);
276 if (requested || withReconnect) {
277 // the irc server has 10 seconds to close the socket
278 _socketCloseTimer.start(10000);
284 void CoreNetwork::userInput(BufferInfo buf, QString msg)
286 userInputHandler()->handleUserInput(buf, msg);
290 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
292 if (_tokenBucket > 0) {
296 _msgQueue.prepend(s);
304 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
308 if (!prefix.isEmpty())
309 msg += ":" + prefix + " ";
310 msg += cmd.toUpper().toLatin1();
312 for (int i = 0; i < params.size(); i++) {
315 if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
321 putRawLine(msg, prepend);
325 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
327 QListIterator<QList<QByteArray>> i(params);
328 while (i.hasNext()) {
329 QList<QByteArray> msg = i.next();
330 putCmd(cmd, msg, prefix, prependAll);
335 void CoreNetwork::setChannelJoined(const QString &channel)
337 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
339 Core::setChannelPersistent(userId(), networkId(), channel, true);
340 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
344 void CoreNetwork::setChannelParted(const QString &channel)
346 removeChannelKey(channel);
347 _autoWhoQueue.removeAll(channel.toLower());
348 _autoWhoPending.remove(channel.toLower());
350 Core::setChannelPersistent(userId(), networkId(), channel, false);
354 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
357 removeChannelKey(channel);
360 _channelKeys[channel.toLower()] = key;
365 void CoreNetwork::removeChannelKey(const QString &channel)
367 _channelKeys.remove(channel.toLower());
372 Cipher *CoreNetwork::cipher(const QString &target)
374 if (target.isEmpty())
377 if (!Cipher::neededFeaturesAvailable())
380 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
382 return channel->cipher();
384 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
386 return user->cipher();
387 } else if (!isChannelName(target)) {
388 return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
394 QByteArray CoreNetwork::cipherKey(const QString &target) const
396 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
398 return c->cipher()->key();
400 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
402 return u->cipher()->key();
408 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
410 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
412 c->setEncrypted(c->cipher()->setKey(key));
416 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
417 if (!u && !isChannelName(target))
418 u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
421 u->setEncrypted(u->cipher()->setKey(key));
427 bool CoreNetwork::cipherUsesCBC(const QString &target)
429 CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
431 return c->cipher()->usesCBC();
432 CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
434 return u->cipher()->usesCBC();
438 #endif /* HAVE_QCA2 */
440 bool CoreNetwork::setAutoWhoDone(const QString &channel)
442 QString chan = channel.toLower();
443 if (_autoWhoPending.value(chan, 0) <= 0)
445 if (--_autoWhoPending[chan] <= 0)
446 _autoWhoPending.remove(chan);
451 void CoreNetwork::setMyNick(const QString &mynick)
453 Network::setMyNick(mynick);
454 if (connectionState() == Network::Initializing)
455 networkInitialized();
459 void CoreNetwork::socketHasData()
461 while (socket.canReadLine()) {
462 QByteArray s = socket.readLine();
463 if (s.endsWith("\r\n"))
465 else if (s.endsWith("\n"))
467 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
468 event->setTimestamp(QDateTime::currentDateTimeUtc());
469 emit newEvent(event);
474 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
476 // Ignore socket closed errors if expected
477 if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
481 _previousConnectionAttemptFailed = true;
482 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
483 emit connectionError(socket.errorString());
484 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
485 emitConnectionError(socket.errorString());
486 if (socket.state() < QAbstractSocket::ConnectedState) {
487 socketDisconnected();
492 void CoreNetwork::socketInitialized()
494 CoreIdentity *identity = identityPtr();
496 qCritical() << "Identity invalid!";
501 Server server = usedServer();
504 // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
505 // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
506 if (!server.useSsl || !socket.isEncrypted()) {
507 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
510 if (server.useSsl && !socket.isEncrypted()) {
511 // We'll finish setup once we're encrypted, and called again
515 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
518 socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
520 // TokenBucket to avoid sending too much at once
521 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
523 _tokenBucket = _burstSize; // init with a full bucket
524 _tokenBucketTimer.start(_messageDelay);
526 if (networkInfo().useSasl) {
527 putRawLine(serverEncode(QString("CAP REQ :sasl")));
529 if (!server.password.isEmpty()) {
530 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
533 if (identity->nicks().isEmpty()) {
535 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
538 nick = identity->nicks()[0];
540 putRawLine(serverEncode(QString("NICK %1").arg(nick)));
541 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
545 void CoreNetwork::socketDisconnected()
547 disablePingTimeout();
550 _autoWhoCycleTimer.stop();
551 _autoWhoTimer.stop();
552 _autoWhoQueue.clear();
553 _autoWhoPending.clear();
555 _socketCloseTimer.stop();
557 _tokenBucketTimer.stop();
561 foreach(QString channel, me_->channels())
562 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
566 emit disconnected(networkId());
567 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
568 // Reset disconnect expectations
569 _disconnectExpected = false;
570 if (_quitRequested) {
571 _quitRequested = false;
572 setConnectionState(Network::Disconnected);
573 Core::setNetworkConnected(userId(), networkId(), false);
575 else if (_autoReconnectCount != 0) {
576 setConnectionState(Network::Reconnecting);
577 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
578 doAutoReconnect(); // first try is immediate
580 _autoReconnectTimer.start();
585 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
587 Network::ConnectionState state;
588 switch (socketState) {
589 case QAbstractSocket::UnconnectedState:
590 state = Network::Disconnected;
591 socketDisconnected();
593 case QAbstractSocket::HostLookupState:
594 case QAbstractSocket::ConnectingState:
595 state = Network::Connecting;
597 case QAbstractSocket::ConnectedState:
598 state = Network::Initializing;
600 case QAbstractSocket::ClosingState:
601 state = Network::Disconnecting;
604 state = Network::Disconnected;
606 setConnectionState(state);
610 void CoreNetwork::networkInitialized()
612 setConnectionState(Network::Initialized);
614 _disconnectExpected = false;
615 _quitRequested = false;
617 if (useAutoReconnect()) {
619 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
622 // restore away state
623 QString awayMsg = Core::awayMessage(userId(), networkId());
624 if (!awayMsg.isEmpty())
625 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
631 if (networkConfig()->autoWhoEnabled()) {
632 _autoWhoCycleTimer.start();
633 _autoWhoTimer.start();
634 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
637 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
638 Core::setNetworkConnected(userId(), networkId(), true);
642 void CoreNetwork::sendPerform()
644 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
647 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
648 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
651 // restore old user modes if server default mode is set.
654 if (!me_->userModes().isEmpty()) {
658 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
659 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
664 foreach(QString line, perform()) {
665 if (!line.isEmpty()) userInput(statusBuf, line);
668 // rejoin channels we've been in
669 if (rejoinChannels()) {
670 QStringList channels, keys;
671 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
672 QString key = channelKey(chan);
673 if (!key.isEmpty()) {
674 channels.prepend(chan);
678 channels.append(chan);
681 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
682 if (!joinString.isEmpty())
683 userInputHandler()->handleJoin(statusBuf, joinString);
688 void CoreNetwork::restoreUserModes()
693 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
694 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
696 QString modesDelta = Core::userModes(userId(), networkId());
697 QString currentModes = me_->userModes();
699 QString addModes, removeModes;
700 if (modesDelta.contains('-')) {
701 addModes = modesDelta.section('-', 0, 0);
702 removeModes = modesDelta.section('-', 1);
705 addModes = modesDelta;
708 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
709 if (currentModes.isEmpty())
710 removeModes = QString();
712 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
714 if (addModes.isEmpty() && removeModes.isEmpty())
717 if (!addModes.isEmpty())
718 addModes = '+' + addModes;
719 if (!removeModes.isEmpty())
720 removeModes = '-' + removeModes;
722 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
723 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
727 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
733 for (int i = 0; i < requestedModes.length(); i++) {
734 if (requestedModes[i] == '+') {
738 if (requestedModes[i] == '-') {
743 addModes += requestedModes[i];
746 removeModes += requestedModes[i];
750 QString addModesOld = _requestedUserModes.section('-', 0, 0);
751 QString removeModesOld = _requestedUserModes.section('-', 1);
753 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
754 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
755 addModes += addModesOld;
757 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
758 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
759 removeModes += removeModesOld;
761 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
765 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
767 QString persistentUserModes = Core::userModes(userId(), networkId());
769 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
770 QString requestedRemove = _requestedUserModes.section('-', 1);
772 QString persistentAdd, persistentRemove;
773 if (persistentUserModes.contains('-')) {
774 persistentAdd = persistentUserModes.section('-', 0, 0);
775 persistentRemove = persistentUserModes.section('-', 1);
778 persistentAdd = persistentUserModes;
781 // remove modes we didn't issue
782 if (requestedAdd.isEmpty())
783 addModes = QString();
785 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
787 if (requestedRemove.isEmpty())
788 removeModes = QString();
790 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
793 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
794 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
797 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
798 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
800 // update issued mode list
801 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
802 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
803 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
805 persistentAdd += addModes;
806 persistentRemove += removeModes;
807 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
811 void CoreNetwork::resetPersistentModes()
813 _requestedUserModes = QString('-');
814 Core::setUserModes(userId(), networkId(), QString());
818 void CoreNetwork::setUseAutoReconnect(bool use)
820 Network::setUseAutoReconnect(use);
822 _autoReconnectTimer.stop();
826 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
828 Network::setAutoReconnectInterval(interval);
829 _autoReconnectTimer.setInterval(interval * 1000);
833 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
835 Network::setAutoReconnectRetries(retries);
836 if (_autoReconnectCount != 0) {
837 if (unlimitedReconnectRetries())
838 _autoReconnectCount = -1;
840 _autoReconnectCount = autoReconnectRetries();
845 void CoreNetwork::doAutoReconnect()
847 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
848 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
851 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
852 _autoReconnectCount--; // -2 means we delay the next reconnect
857 void CoreNetwork::sendPing()
859 uint now = QDateTime::currentDateTime().toTime_t();
860 if (_pingCount != 0) {
861 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
862 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
864 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
865 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
866 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
867 // and unable to even handle a ping answer. So we ignore those misses.
868 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
873 // Don't send pings until the network is initialized
875 userInputHandler()->handlePing(BufferInfo(), QString());
880 void CoreNetwork::enablePingTimeout(bool enable)
883 disablePingTimeout();
886 if (networkConfig()->pingTimeoutEnabled())
892 void CoreNetwork::disablePingTimeout()
900 void CoreNetwork::setPingInterval(int interval)
902 _pingTimer.setInterval(interval * 1000);
906 /******** AutoWHO ********/
908 void CoreNetwork::startAutoWhoCycle()
910 if (!_autoWhoQueue.isEmpty()) {
911 _autoWhoCycleTimer.stop();
914 _autoWhoQueue = channels();
918 void CoreNetwork::setAutoWhoDelay(int delay)
920 _autoWhoTimer.setInterval(delay * 1000);
924 void CoreNetwork::setAutoWhoInterval(int interval)
926 _autoWhoCycleTimer.setInterval(interval * 1000);
930 void CoreNetwork::setAutoWhoEnabled(bool enabled)
932 if (enabled && isConnected() && !_autoWhoTimer.isActive())
933 _autoWhoTimer.start();
935 _autoWhoTimer.stop();
936 _autoWhoCycleTimer.stop();
941 void CoreNetwork::sendAutoWho()
943 // Don't send autowho if there are still some pending
944 if (_autoWhoPending.count())
947 while (!_autoWhoQueue.isEmpty()) {
948 QString chan = _autoWhoQueue.takeFirst();
949 IrcChannel *ircchan = ircChannel(chan);
950 if (!ircchan) continue;
951 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
953 _autoWhoPending[chan]++;
954 putRawLine("WHO " + serverEncode(chan));
957 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
958 // Timer was stopped, means a new cycle is due immediately
959 _autoWhoCycleTimer.start();
966 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
969 socket.ignoreSslErrors();
970 // TODO errorhandling
976 void CoreNetwork::fillBucketAndProcessQueue()
978 if (_tokenBucket < _burstSize) {
982 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
983 writeToSocket(_msgQueue.takeFirst());
988 void CoreNetwork::writeToSocket(const QByteArray &data)
991 socket.write("\r\n");
996 Network::Server CoreNetwork::usedServer() const
998 if (_lastUsedServerIndex < serverList().count())
999 return serverList()[_lastUsedServerIndex];
1001 if (!serverList().isEmpty())
1002 return serverList()[0];
1004 return Network::Server();
1008 void CoreNetwork::requestConnect() const
1010 if (connectionState() != Disconnected) {
1011 qWarning() << "Requesting connect while already being connected!";
1014 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1018 void CoreNetwork::requestDisconnect() const
1020 if (connectionState() == Disconnected) {
1021 qWarning() << "Requesting disconnect while not being connected!";
1024 userInputHandler()->handleQuit(BufferInfo(), QString());
1028 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1030 Network::Server currentServer = usedServer();
1031 setNetworkInfo(info);
1032 Core::updateNetwork(coreSession()->user(), info);
1034 // the order of the servers might have changed,
1035 // so we try to find the previously used server
1036 _lastUsedServerIndex = 0;
1037 for (int i = 0; i < serverList().count(); i++) {
1038 Network::Server server = serverList()[i];
1039 if (server.host == currentServer.host && server.port == currentServer.port) {
1040 _lastUsedServerIndex = i;
1047 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1049 QString wrkMsg(message);
1050 QList<QList<QByteArray>> msgsToSend;
1052 // do while (wrkMsg.size() > 0)
1054 // First, check to see if the whole message can be sent at once. The
1055 // cmdGenerator function is passed in by the caller and is used to encode
1056 // and encrypt (if applicable) the message, since different callers might
1057 // want to use different encoding or encode different values.
1058 int splitPos = wrkMsg.size();
1059 QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1060 int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1062 if (initialOverrun) {
1063 // If the message was too long to be sent, first try splitting it along
1064 // word boundaries with QTextBoundaryFinder.
1065 QString splitMsg(wrkMsg);
1066 QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1067 qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1068 QList<QByteArray> splitMsgEnc;
1069 int overrun = initialOverrun;
1072 splitPos = qtbf.toPreviousBoundary();
1074 // splitPos==-1 means the QTBF couldn't find a split point at all and
1075 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1076 // the string. Neither one of these works for us.
1078 // If a split point could be found, split the message there, calculate the
1079 // overrun, and continue with the loop.
1080 splitMsg = splitMsg.left(splitPos);
1081 splitMsgEnc = cmdGenerator(splitMsg);
1082 overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1085 // If a split point could not be found (the beginning of the message
1086 // is reached without finding a split point short enough to send) and we
1087 // are still in Word mode, switch to Grapheme mode. We also need to restore
1088 // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1089 // the previous attempt to find a split point.
1090 if (qtbf.type() == QTextBoundaryFinder::Word) {
1092 splitPos = splitMsg.size();
1093 QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1094 graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1095 qtbf = graphemeQtbf;
1098 // If the QTBF fails to find a split point in Grapheme mode, we give up.
1099 // This should never happen, but it should be handled anyway.
1100 qWarning() << "Unexpected failure to split message!";
1106 // Once a message of sendable length has been found, remove it from the wrkMsg and
1107 // add it to the list of messages to be sent.
1108 wrkMsg.remove(0, splitPos);
1109 msgsToSend.append(splitMsgEnc);
1112 // If the entire remaining message is short enough to be sent all at once, remove
1113 // it from the wrkMsg and add it to the list of messages to be sent.
1114 wrkMsg.remove(0, splitPos);
1115 msgsToSend.append(initialSplitMsgEnc);
1117 } while (wrkMsg.size() > 0);