1 /***************************************************************************
2 * Copyright (C) 2005-2013 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 ***************************************************************************/
21 #include "corenetwork.h"
24 #include "coreidentity.h"
25 #include "corenetworkconfig.h"
26 #include "coresession.h"
27 #include "coreuserinputhandler.h"
28 #include "networkevent.h"
30 INIT_SYNCABLE_OBJECT(CoreNetwork)
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32 : Network(networkid, session),
33 _coreSession(session),
34 _userInputHandler(new CoreUserInputHandler(this)),
35 _autoReconnectCount(0),
36 _quitRequested(false),
38 _previousConnectionAttemptFailed(false),
39 _lastUsedServerIndex(0),
43 _requestedUserModes('-')
45 _autoReconnectTimer.setSingleShot(true);
46 _socketCloseTimer.setSingleShot(true);
47 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
49 setPingInterval(networkConfig()->pingInterval());
50 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
52 setAutoWhoDelay(networkConfig()->autoWhoDelay());
53 setAutoWhoInterval(networkConfig()->autoWhoInterval());
55 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
56 foreach(QString chan, channels.keys()) {
57 _channelKeys[chan.toLower()] = channels[chan];
60 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
61 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
62 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
63 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
64 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
66 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
67 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
68 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
69 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
71 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
72 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
73 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
74 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
75 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
77 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
78 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
80 connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
82 if (Quassel::isOptionSet("oidentd")) {
83 connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
84 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
89 CoreNetwork::~CoreNetwork()
91 if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
92 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
93 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
94 delete _userInputHandler;
98 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
100 if (!bufferName.isEmpty()) {
101 IrcChannel *channel = ircChannel(bufferName);
103 return channel->decodeString(string);
105 return decodeString(string);
109 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
111 IrcUser *user = ircUser(userNick);
113 return user->decodeString(string);
114 return decodeString(string);
118 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
120 if (!bufferName.isEmpty()) {
121 IrcChannel *channel = ircChannel(bufferName);
123 return channel->encodeString(string);
125 return encodeString(string);
129 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
131 IrcUser *user = ircUser(userNick);
133 return user->encodeString(string);
134 return encodeString(string);
138 void CoreNetwork::connectToIrc(bool reconnecting)
140 if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
141 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
142 if (unlimitedReconnectRetries())
143 _autoReconnectCount = -1;
145 _autoReconnectCount = autoReconnectRetries();
147 if (serverList().isEmpty()) {
148 qWarning() << "Server list empty, ignoring connect request!";
151 CoreIdentity *identity = identityPtr();
153 qWarning() << "Invalid identity configures, ignoring connect request!";
157 // cleaning up old quit reason
160 // use a random server?
161 if (useRandomServer()) {
162 _lastUsedServerIndex = qrand() % serverList().size();
164 else if (_previousConnectionAttemptFailed) {
165 // cycle to next server if previous connection attempt failed
166 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
167 if (++_lastUsedServerIndex >= serverList().size()) {
168 _lastUsedServerIndex = 0;
171 _previousConnectionAttemptFailed = false;
173 Server server = usedServer();
174 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
175 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
177 if (server.useProxy) {
178 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
179 socket.setProxy(proxy);
182 socket.setProxy(QNetworkProxy::NoProxy);
186 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
188 CoreIdentity *identity = identityPtr();
190 socket.setLocalCertificate(identity->sslCert());
191 socket.setPrivateKey(identity->sslKey());
193 socket.connectToHostEncrypted(server.host, server.port);
196 socket.connectToHost(server.host, server.port);
199 socket.connectToHost(server.host, server.port);
204 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
206 _quitRequested = requested; // see socketDisconnected();
207 if (!withReconnect) {
208 _autoReconnectTimer.stop();
209 _autoReconnectCount = 0; // prohibiting auto reconnect
211 disablePingTimeout();
218 awayMsg = me_->awayMessage();
219 Core::setAwayMessage(userId(), networkId(), awayMsg);
222 if (reason.isEmpty() && identityPtr())
223 _quitReason = identityPtr()->quitReason();
225 _quitReason = reason;
227 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
228 switch (socket.state()) {
229 case QAbstractSocket::ConnectedState:
230 userInputHandler()->issueQuit(_quitReason);
231 if (requested || withReconnect) {
232 // the irc server has 10 seconds to close the socket
233 _socketCloseTimer.start(10000);
238 socketDisconnected();
243 void CoreNetwork::userInput(BufferInfo buf, QString msg)
245 userInputHandler()->handleUserInput(buf, msg);
249 void CoreNetwork::putRawLine(QByteArray s)
251 if (_tokenBucket > 0)
258 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix)
262 if (!prefix.isEmpty())
263 msg += ":" + prefix + " ";
264 msg += cmd.toUpper().toAscii();
266 for (int i = 0; i < params.size() - 1; i++) {
267 msg += " " + params[i];
269 if (!params.isEmpty())
270 msg += " :" + params.last();
276 void CoreNetwork::setChannelJoined(const QString &channel)
278 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
280 Core::setChannelPersistent(userId(), networkId(), channel, true);
281 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
285 void CoreNetwork::setChannelParted(const QString &channel)
287 removeChannelKey(channel);
288 _autoWhoQueue.removeAll(channel.toLower());
289 _autoWhoPending.remove(channel.toLower());
291 Core::setChannelPersistent(userId(), networkId(), channel, false);
295 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
298 removeChannelKey(channel);
301 _channelKeys[channel.toLower()] = key;
306 void CoreNetwork::removeChannelKey(const QString &channel)
308 _channelKeys.remove(channel.toLower());
313 Cipher *CoreNetwork::cipher(const QString &target) const
315 if (target.isEmpty())
318 if (!Cipher::neededFeaturesAvailable())
321 QByteArray key = cipherKey(target);
325 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
327 if (channel->cipher()->setKey(key))
328 return channel->cipher();
331 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
332 if (user && user->cipher()->setKey(key))
333 return user->cipher();
339 QByteArray CoreNetwork::cipherKey(const QString &recipient) const
341 return _cipherKeys.value(recipient.toLower(), QByteArray());
345 void CoreNetwork::setCipherKey(const QString &recipient, const QByteArray &key)
348 _cipherKeys[recipient.toLower()] = key;
350 _cipherKeys.remove(recipient.toLower());
354 #endif /* HAVE_QCA2 */
356 bool CoreNetwork::setAutoWhoDone(const QString &channel)
358 QString chan = channel.toLower();
359 if (_autoWhoPending.value(chan, 0) <= 0)
361 if (--_autoWhoPending[chan] <= 0)
362 _autoWhoPending.remove(chan);
367 void CoreNetwork::setMyNick(const QString &mynick)
369 Network::setMyNick(mynick);
370 if (connectionState() == Network::Initializing)
371 networkInitialized();
375 void CoreNetwork::socketHasData()
377 while (socket.canReadLine()) {
378 QByteArray s = socket.readLine();
380 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
381 #if QT_VERSION >= 0x040700
382 event->setTimestamp(QDateTime::currentDateTimeUtc());
384 event->setTimestamp(QDateTime::currentDateTime().toUTC());
386 emit newEvent(event);
391 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
393 if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
396 _previousConnectionAttemptFailed = true;
397 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
398 emit connectionError(socket.errorString());
399 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
400 emitConnectionError(socket.errorString());
401 if (socket.state() < QAbstractSocket::ConnectedState) {
402 socketDisconnected();
407 void CoreNetwork::socketInitialized()
409 Server server = usedServer();
411 if (server.useSsl && !socket.isEncrypted())
415 CoreIdentity *identity = identityPtr();
417 qCritical() << "Identity invalid!";
422 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
424 // TokenBucket to avoid sending too much at once
425 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
427 _tokenBucket = _burstSize; // init with a full bucket
428 _tokenBucketTimer.start(_messageDelay);
430 if (networkInfo().useSasl) {
431 putRawLine(serverEncode(QString("CAP REQ :sasl")));
433 if (!server.password.isEmpty()) {
434 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
437 if (identity->nicks().isEmpty()) {
439 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
442 nick = identity->nicks()[0];
444 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
445 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
449 void CoreNetwork::socketDisconnected()
451 disablePingTimeout();
454 _autoWhoCycleTimer.stop();
455 _autoWhoTimer.stop();
456 _autoWhoQueue.clear();
457 _autoWhoPending.clear();
459 _socketCloseTimer.stop();
461 _tokenBucketTimer.stop();
465 foreach(QString channel, me_->channels())
466 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
470 emit disconnected(networkId());
471 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
472 if (_quitRequested) {
473 _quitRequested = false;
474 setConnectionState(Network::Disconnected);
475 Core::setNetworkConnected(userId(), networkId(), false);
477 else if (_autoReconnectCount != 0) {
478 setConnectionState(Network::Reconnecting);
479 if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
480 doAutoReconnect(); // first try is immediate
482 _autoReconnectTimer.start();
487 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
489 Network::ConnectionState state;
490 switch (socketState) {
491 case QAbstractSocket::UnconnectedState:
492 state = Network::Disconnected;
494 case QAbstractSocket::HostLookupState:
495 case QAbstractSocket::ConnectingState:
496 state = Network::Connecting;
498 case QAbstractSocket::ConnectedState:
499 state = Network::Initializing;
501 case QAbstractSocket::ClosingState:
502 state = Network::Disconnecting;
505 state = Network::Disconnected;
507 setConnectionState(state);
511 void CoreNetwork::networkInitialized()
513 setConnectionState(Network::Initialized);
515 _quitRequested = false;
517 if (useAutoReconnect()) {
519 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
522 // restore away state
523 QString awayMsg = Core::awayMessage(userId(), networkId());
524 if (!awayMsg.isEmpty())
525 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
531 if (networkConfig()->autoWhoEnabled()) {
532 _autoWhoCycleTimer.start();
533 _autoWhoTimer.start();
534 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
537 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
538 Core::setNetworkConnected(userId(), networkId(), true);
542 void CoreNetwork::sendPerform()
544 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
547 if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
548 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
551 // restore old user modes if server default mode is set.
554 if (!me_->userModes().isEmpty()) {
558 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
559 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
564 foreach(QString line, perform()) {
565 if (!line.isEmpty()) userInput(statusBuf, line);
568 // rejoin channels we've been in
569 if (rejoinChannels()) {
570 QStringList channels, keys;
571 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
572 QString key = channelKey(chan);
573 if (!key.isEmpty()) {
574 channels.prepend(chan);
578 channels.append(chan);
581 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
582 if (!joinString.isEmpty())
583 userInputHandler()->handleJoin(statusBuf, joinString);
588 void CoreNetwork::restoreUserModes()
593 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
594 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
596 QString modesDelta = Core::userModes(userId(), networkId());
597 QString currentModes = me_->userModes();
599 QString addModes, removeModes;
600 if (modesDelta.contains('-')) {
601 addModes = modesDelta.section('-', 0, 0);
602 removeModes = modesDelta.section('-', 1);
605 addModes = modesDelta;
608 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
609 if (currentModes.isEmpty())
610 removeModes = QString();
612 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
614 if (addModes.isEmpty() && removeModes.isEmpty())
617 if (!addModes.isEmpty())
618 addModes = '+' + addModes;
619 if (!removeModes.isEmpty())
620 removeModes = '-' + removeModes;
622 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
623 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
627 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
633 for (int i = 0; i < requestedModes.length(); i++) {
634 if (requestedModes[i] == '+') {
638 if (requestedModes[i] == '-') {
643 addModes += requestedModes[i];
646 removeModes += requestedModes[i];
650 QString addModesOld = _requestedUserModes.section('-', 0, 0);
651 QString removeModesOld = _requestedUserModes.section('-', 1);
653 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
654 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
655 addModes += addModesOld;
657 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
658 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
659 removeModes += removeModesOld;
661 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
665 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
667 QString persistentUserModes = Core::userModes(userId(), networkId());
669 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
670 QString requestedRemove = _requestedUserModes.section('-', 1);
672 QString persistentAdd, persistentRemove;
673 if (persistentUserModes.contains('-')) {
674 persistentAdd = persistentUserModes.section('-', 0, 0);
675 persistentRemove = persistentUserModes.section('-', 1);
678 persistentAdd = persistentUserModes;
681 // remove modes we didn't issue
682 if (requestedAdd.isEmpty())
683 addModes = QString();
685 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
687 if (requestedRemove.isEmpty())
688 removeModes = QString();
690 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
693 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
694 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
697 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
698 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
700 // update issued mode list
701 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
702 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
703 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
705 persistentAdd += addModes;
706 persistentRemove += removeModes;
707 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
711 void CoreNetwork::resetPersistentModes()
713 _requestedUserModes = QString('-');
714 Core::setUserModes(userId(), networkId(), QString());
718 void CoreNetwork::setUseAutoReconnect(bool use)
720 Network::setUseAutoReconnect(use);
722 _autoReconnectTimer.stop();
726 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
728 Network::setAutoReconnectInterval(interval);
729 _autoReconnectTimer.setInterval(interval * 1000);
733 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
735 Network::setAutoReconnectRetries(retries);
736 if (_autoReconnectCount != 0) {
737 if (unlimitedReconnectRetries())
738 _autoReconnectCount = -1;
740 _autoReconnectCount = autoReconnectRetries();
745 void CoreNetwork::doAutoReconnect()
747 if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
748 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
751 if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
752 _autoReconnectCount--; // -2 means we delay the next reconnect
757 void CoreNetwork::sendPing()
759 uint now = QDateTime::currentDateTime().toTime_t();
760 if (_pingCount != 0) {
761 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
762 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
764 if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
765 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
766 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
767 // and unable to even handle a ping answer. So we ignore those misses.
768 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
773 userInputHandler()->handlePing(BufferInfo(), QString());
778 void CoreNetwork::enablePingTimeout(bool enable)
781 disablePingTimeout();
784 if (networkConfig()->pingTimeoutEnabled())
790 void CoreNetwork::disablePingTimeout()
797 void CoreNetwork::setPingInterval(int interval)
799 _pingTimer.setInterval(interval * 1000);
803 /******** AutoWHO ********/
805 void CoreNetwork::startAutoWhoCycle()
807 if (!_autoWhoQueue.isEmpty()) {
808 _autoWhoCycleTimer.stop();
811 _autoWhoQueue = channels();
815 void CoreNetwork::setAutoWhoDelay(int delay)
817 _autoWhoTimer.setInterval(delay * 1000);
821 void CoreNetwork::setAutoWhoInterval(int interval)
823 _autoWhoCycleTimer.setInterval(interval * 1000);
827 void CoreNetwork::setAutoWhoEnabled(bool enabled)
829 if (enabled && isConnected() && !_autoWhoTimer.isActive())
830 _autoWhoTimer.start();
832 _autoWhoTimer.stop();
833 _autoWhoCycleTimer.stop();
838 void CoreNetwork::sendAutoWho()
840 // Don't send autowho if there are still some pending
841 if (_autoWhoPending.count())
844 while (!_autoWhoQueue.isEmpty()) {
845 QString chan = _autoWhoQueue.takeFirst();
846 IrcChannel *ircchan = ircChannel(chan);
847 if (!ircchan) continue;
848 if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
850 _autoWhoPending[chan]++;
851 putRawLine("WHO " + serverEncode(chan));
854 if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
855 // Timer was stopped, means a new cycle is due immediately
856 _autoWhoCycleTimer.start();
863 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
866 socket.ignoreSslErrors();
867 // TODO errorhandling
873 void CoreNetwork::fillBucketAndProcessQueue()
875 if (_tokenBucket < _burstSize) {
879 while (_msgQueue.size() > 0 && _tokenBucket > 0) {
880 writeToSocket(_msgQueue.takeFirst());
885 void CoreNetwork::writeToSocket(const QByteArray &data)
888 socket.write("\r\n");
893 Network::Server CoreNetwork::usedServer() const
895 if (_lastUsedServerIndex < serverList().count())
896 return serverList()[_lastUsedServerIndex];
898 if (!serverList().isEmpty())
899 return serverList()[0];
901 return Network::Server();
905 void CoreNetwork::requestConnect() const
907 if (connectionState() != Disconnected) {
908 qWarning() << "Requesting connect while already being connected!";
911 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
915 void CoreNetwork::requestDisconnect() const
917 if (connectionState() == Disconnected) {
918 qWarning() << "Requesting disconnect while not being connected!";
921 userInputHandler()->handleQuit(BufferInfo(), QString());
925 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
927 Network::Server currentServer = usedServer();
928 setNetworkInfo(info);
929 Core::updateNetwork(coreSession()->user(), info);
931 // the order of the servers might have changed,
932 // so we try to find the previously used server
933 _lastUsedServerIndex = 0;
934 for (int i = 0; i < serverList().count(); i++) {
935 Network::Server server = serverList()[i];
936 if (server.host == currentServer.host && server.port == currentServer.port) {
937 _lastUsedServerIndex = i;