1 /***************************************************************************
2 * Copyright (C) 2005-09 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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(newSocket(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)));
86 CoreNetwork::~CoreNetwork() {
87 if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
88 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
89 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
90 delete _userInputHandler;
93 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
94 if(!bufferName.isEmpty()) {
95 IrcChannel *channel = ircChannel(bufferName);
97 return channel->decodeString(string);
99 return decodeString(string);
102 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
103 IrcUser *user = ircUser(userNick);
105 return user->decodeString(string);
106 return decodeString(string);
109 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
110 if(!bufferName.isEmpty()) {
111 IrcChannel *channel = ircChannel(bufferName);
113 return channel->encodeString(string);
115 return encodeString(string);
118 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
119 IrcUser *user = ircUser(userNick);
121 return user->encodeString(string);
122 return encodeString(string);
125 void CoreNetwork::connectToIrc(bool reconnecting) {
126 if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
127 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
128 if(unlimitedReconnectRetries())
129 _autoReconnectCount = -1;
131 _autoReconnectCount = autoReconnectRetries();
133 if(serverList().isEmpty()) {
134 qWarning() << "Server list empty, ignoring connect request!";
137 CoreIdentity *identity = identityPtr();
139 qWarning() << "Invalid identity configures, ignoring connect request!";
143 // cleaning up old quit reason
146 // use a random server?
147 if(useRandomServer()) {
148 _lastUsedServerIndex = qrand() % serverList().size();
149 } else if(_previousConnectionAttemptFailed) {
150 // cycle to next server if previous connection attempt failed
151 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
152 if(++_lastUsedServerIndex >= serverList().size()) {
153 _lastUsedServerIndex = 0;
156 _previousConnectionAttemptFailed = false;
158 Server server = usedServer();
159 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
160 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
162 if(server.useProxy) {
163 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
164 socket.setProxy(proxy);
166 socket.setProxy(QNetworkProxy::NoProxy);
170 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
172 CoreIdentity *identity = identityPtr();
174 socket.setLocalCertificate(identity->sslCert());
175 socket.setPrivateKey(identity->sslKey());
177 socket.connectToHostEncrypted(server.host, server.port);
179 socket.connectToHost(server.host, server.port);
182 socket.connectToHost(server.host, server.port);
186 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) {
187 _quitRequested = requested; // see socketDisconnected();
189 _autoReconnectTimer.stop();
190 _autoReconnectCount = 0; // prohibiting auto reconnect
192 disablePingTimeout();
199 awayMsg = me_->awayMessage();
200 Core::setAwayMessage(userId(), networkId(), awayMsg);
203 if(reason.isEmpty() && identityPtr())
204 _quitReason = identityPtr()->quitReason();
206 _quitReason = reason;
208 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
209 switch(socket.state()) {
210 case QAbstractSocket::ConnectedState:
211 userInputHandler()->issueQuit(_quitReason);
212 if(requested || withReconnect) {
213 // the irc server has 10 seconds to close the socket
214 _socketCloseTimer.start(10000);
219 socketDisconnected();
223 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
224 userInputHandler()->handleUserInput(buf, msg);
227 void CoreNetwork::putRawLine(QByteArray s) {
234 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
237 if(!prefix.isEmpty())
238 msg += ":" + prefix + " ";
239 msg += cmd.toUpper().toAscii();
241 for(int i = 0; i < params.size() - 1; i++) {
242 msg += " " + params[i];
244 if(!params.isEmpty())
245 msg += " :" + params.last();
250 void CoreNetwork::setChannelJoined(const QString &channel) {
251 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
253 Core::setChannelPersistent(userId(), networkId(), channel, true);
254 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
257 void CoreNetwork::setChannelParted(const QString &channel) {
258 removeChannelKey(channel);
259 _autoWhoQueue.removeAll(channel.toLower());
260 _autoWhoPending.remove(channel.toLower());
262 Core::setChannelPersistent(userId(), networkId(), channel, false);
265 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
267 removeChannelKey(channel);
269 _channelKeys[channel.toLower()] = key;
273 void CoreNetwork::removeChannelKey(const QString &channel) {
274 _channelKeys.remove(channel.toLower());
278 Cipher *CoreNetwork::cipher(const QString &target) const {
282 if(!Cipher::neededFeaturesAvailable())
285 QByteArray key = cipherKey(target);
289 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
291 if(channel->cipher()->setKey(key))
292 return channel->cipher();
294 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
295 if(user && user->cipher()->setKey(key))
296 return user->cipher();
301 QByteArray CoreNetwork::cipherKey(const QString &recipient) const {
302 return _cipherKeys.value(recipient.toLower(), QByteArray());
305 void CoreNetwork::setCipherKey(const QString &recipient, const QByteArray &key) {
307 _cipherKeys[recipient.toLower()] = key;
309 _cipherKeys.remove(recipient.toLower());
311 #endif /* HAVE_QCA2 */
313 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
314 QString chan = channel.toLower();
315 if(_autoWhoPending.value(chan, 0) <= 0)
317 if(--_autoWhoPending[chan] <= 0)
318 _autoWhoPending.remove(chan);
322 void CoreNetwork::setMyNick(const QString &mynick) {
323 Network::setMyNick(mynick);
324 if(connectionState() == Network::Initializing)
325 networkInitialized();
328 void CoreNetwork::socketHasData() {
329 while(socket.canReadLine()) {
330 QByteArray s = socket.readLine().trimmed();
331 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
332 #if QT_VERSION >= 0x040700
333 event->setTimestamp(QDateTime::currentDateTimeUtc());
335 event->setTimestamp(QDateTime::currentDateTime().toUTC());
337 emit newEvent(event);
341 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
342 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
345 _previousConnectionAttemptFailed = true;
346 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
347 emit connectionError(socket.errorString());
348 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
349 emitConnectionError(socket.errorString());
350 if(socket.state() < QAbstractSocket::ConnectedState) {
351 socketDisconnected();
355 void CoreNetwork::socketInitialized() {
356 qDebug() << "connected()";
357 Server server = usedServer();
359 if(server.useSsl && !socket.isEncrypted())
363 CoreIdentity *identity = identityPtr();
365 qCritical() << "Identity invalid!";
370 emit newSocket(identity, localAddress(), localPort(), peerAddress(), peerPort());
372 // TokenBucket to avoid sending too much at once
373 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
375 _tokenBucket = _burstSize; // init with a full bucket
376 _tokenBucketTimer.start(_messageDelay);
378 if(networkInfo().useSasl) {
379 putRawLine(serverEncode(QString("CAP REQ :sasl")));
381 if(!server.password.isEmpty()) {
382 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
385 if(identity->nicks().isEmpty()) {
387 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
389 nick = identity->nicks()[0];
391 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
392 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
395 void CoreNetwork::socketDisconnected() {
396 disablePingTimeout();
399 _autoWhoCycleTimer.stop();
400 _autoWhoTimer.stop();
401 _autoWhoQueue.clear();
402 _autoWhoPending.clear();
404 _socketCloseTimer.stop();
406 _tokenBucketTimer.stop();
410 foreach(QString channel, me_->channels())
411 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
415 emit disconnected(networkId());
417 _quitRequested = false;
418 setConnectionState(Network::Disconnected);
419 Core::setNetworkConnected(userId(), networkId(), false);
420 } else if(_autoReconnectCount != 0) {
421 setConnectionState(Network::Reconnecting);
422 if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
423 doAutoReconnect(); // first try is immediate
425 _autoReconnectTimer.start();
429 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
430 Network::ConnectionState state;
431 switch(socketState) {
432 case QAbstractSocket::UnconnectedState:
433 state = Network::Disconnected;
435 case QAbstractSocket::HostLookupState:
436 case QAbstractSocket::ConnectingState:
437 state = Network::Connecting;
439 case QAbstractSocket::ConnectedState:
440 state = Network::Initializing;
442 case QAbstractSocket::ClosingState:
443 state = Network::Disconnecting;
446 state = Network::Disconnected;
448 setConnectionState(state);
451 void CoreNetwork::networkInitialized() {
452 setConnectionState(Network::Initialized);
454 _quitRequested = false;
456 if(useAutoReconnect()) {
458 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
461 // restore away state
462 QString awayMsg = Core::awayMessage(userId(), networkId());
463 if(!awayMsg.isEmpty())
464 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
470 if(networkConfig()->autoWhoEnabled()) {
471 _autoWhoCycleTimer.start();
472 _autoWhoTimer.start();
473 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
476 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
477 Core::setNetworkConnected(userId(), networkId(), true);
480 void CoreNetwork::sendPerform() {
481 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
484 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
485 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
488 // restore old user modes if server default mode is set.
491 if(!me_->userModes().isEmpty()) {
494 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
495 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
500 foreach(QString line, perform()) {
501 if(!line.isEmpty()) userInput(statusBuf, line);
504 // rejoin channels we've been in
505 if(rejoinChannels()) {
506 QStringList channels, keys;
507 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
508 QString key = channelKey(chan);
510 channels.prepend(chan);
513 channels.append(chan);
516 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
517 if(!joinString.isEmpty())
518 userInputHandler()->handleJoin(statusBuf, joinString);
522 void CoreNetwork::restoreUserModes() {
526 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
527 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
529 QString modesDelta = Core::userModes(userId(), networkId());
530 QString currentModes = me_->userModes();
532 QString addModes, removeModes;
533 if(modesDelta.contains('-')) {
534 addModes = modesDelta.section('-', 0, 0);
535 removeModes = modesDelta.section('-', 1);
537 addModes = modesDelta;
541 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
542 if(currentModes.isEmpty())
543 removeModes = QString();
545 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
547 if(addModes.isEmpty() && removeModes.isEmpty())
550 if(!addModes.isEmpty())
551 addModes = '+' + addModes;
552 if(!removeModes.isEmpty())
553 removeModes = '-' + removeModes;
555 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
556 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
559 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
564 for(int i = 0; i < requestedModes.length(); i++) {
565 if(requestedModes[i] == '+') {
569 if(requestedModes[i] == '-') {
574 addModes += requestedModes[i];
576 removeModes += requestedModes[i];
581 QString addModesOld = _requestedUserModes.section('-', 0, 0);
582 QString removeModesOld = _requestedUserModes.section('-', 1);
584 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
585 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
586 addModes += addModesOld;
588 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
589 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
590 removeModes += removeModesOld;
592 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
595 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
596 QString persistentUserModes = Core::userModes(userId(), networkId());
598 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
599 QString requestedRemove = _requestedUserModes.section('-', 1);
601 QString persistentAdd, persistentRemove;
602 if(persistentUserModes.contains('-')) {
603 persistentAdd = persistentUserModes.section('-', 0, 0);
604 persistentRemove = persistentUserModes.section('-', 1);
606 persistentAdd = persistentUserModes;
609 // remove modes we didn't issue
610 if(requestedAdd.isEmpty())
611 addModes = QString();
613 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
615 if(requestedRemove.isEmpty())
616 removeModes = QString();
618 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
621 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
622 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
625 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
626 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
628 // update issued mode list
629 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
630 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
631 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
633 persistentAdd += addModes;
634 persistentRemove += removeModes;
635 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
638 void CoreNetwork::resetPersistentModes() {
639 _requestedUserModes = QString('-');
640 Core::setUserModes(userId(), networkId(), QString());
643 void CoreNetwork::setUseAutoReconnect(bool use) {
644 Network::setUseAutoReconnect(use);
646 _autoReconnectTimer.stop();
649 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
650 Network::setAutoReconnectInterval(interval);
651 _autoReconnectTimer.setInterval(interval * 1000);
654 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
655 Network::setAutoReconnectRetries(retries);
656 if(_autoReconnectCount != 0) {
657 if(unlimitedReconnectRetries())
658 _autoReconnectCount = -1;
660 _autoReconnectCount = autoReconnectRetries();
664 void CoreNetwork::doAutoReconnect() {
665 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
666 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
669 if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
670 _autoReconnectCount--; // -2 means we delay the next reconnect
674 void CoreNetwork::sendPing() {
675 uint now = QDateTime::currentDateTime().toTime_t();
676 if(_pingCount != 0) {
677 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
678 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
680 if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
681 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
682 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
683 // and unable to even handle a ping answer. So we ignore those misses.
684 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
688 userInputHandler()->handlePing(BufferInfo(), QString());
692 void CoreNetwork::enablePingTimeout(bool enable) {
694 disablePingTimeout();
697 if(networkConfig()->pingTimeoutEnabled())
702 void CoreNetwork::disablePingTimeout() {
707 void CoreNetwork::setPingInterval(int interval) {
708 _pingTimer.setInterval(interval * 1000);
711 /******** AutoWHO ********/
713 void CoreNetwork::startAutoWhoCycle() {
714 if(!_autoWhoQueue.isEmpty()) {
715 _autoWhoCycleTimer.stop();
718 _autoWhoQueue = channels();
721 void CoreNetwork::setAutoWhoDelay(int delay) {
722 _autoWhoTimer.setInterval(delay * 1000);
725 void CoreNetwork::setAutoWhoInterval(int interval) {
726 _autoWhoCycleTimer.setInterval(interval * 1000);
729 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
730 if(enabled && isConnected() && !_autoWhoTimer.isActive())
731 _autoWhoTimer.start();
733 _autoWhoTimer.stop();
734 _autoWhoCycleTimer.stop();
738 void CoreNetwork::sendAutoWho() {
739 // Don't send autowho if there are still some pending
740 if(_autoWhoPending.count())
743 while(!_autoWhoQueue.isEmpty()) {
744 QString chan = _autoWhoQueue.takeFirst();
745 IrcChannel *ircchan = ircChannel(chan);
746 if(!ircchan) continue;
747 if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
749 _autoWhoPending[chan]++;
750 putRawLine("WHO " + serverEncode(chan));
753 if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
754 // Timer was stopped, means a new cycle is due immediately
755 _autoWhoCycleTimer.start();
761 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
763 socket.ignoreSslErrors();
764 // TODO errorhandling
768 void CoreNetwork::fillBucketAndProcessQueue() {
769 if(_tokenBucket < _burstSize) {
773 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
774 writeToSocket(_msgQueue.takeFirst());
778 void CoreNetwork::writeToSocket(const QByteArray &data) {
780 socket.write("\r\n");
784 Network::Server CoreNetwork::usedServer() const {
785 if(_lastUsedServerIndex < serverList().count())
786 return serverList()[_lastUsedServerIndex];
788 if(!serverList().isEmpty())
789 return serverList()[0];
791 return Network::Server();
794 void CoreNetwork::requestConnect() const {
795 if(connectionState() != Disconnected) {
796 qWarning() << "Requesting connect while already being connected!";
799 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
802 void CoreNetwork::requestDisconnect() const {
803 if(connectionState() == Disconnected) {
804 qWarning() << "Requesting disconnect while not being connected!";
807 userInputHandler()->handleQuit(BufferInfo(), QString());
810 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
811 Network::Server currentServer = usedServer();
812 setNetworkInfo(info);
813 Core::updateNetwork(coreSession()->user(), info);
815 // the order of the servers might have changed,
816 // so we try to find the previously used server
817 _lastUsedServerIndex = 0;
818 for(int i = 0; i < serverList().count(); i++) {
819 Network::Server server = serverList()[i];
820 if(server.host == currentServer.host && server.port == currentServer.port) {
821 _lastUsedServerIndex = i;