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(socketInitialized(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)));
84 connect(this, SIGNAL(socketDisconnected(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)));
88 CoreNetwork::~CoreNetwork() {
89 if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
90 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
91 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
92 delete _userInputHandler;
95 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
96 if(!bufferName.isEmpty()) {
97 IrcChannel *channel = ircChannel(bufferName);
99 return channel->decodeString(string);
101 return decodeString(string);
104 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
105 IrcUser *user = ircUser(userNick);
107 return user->decodeString(string);
108 return decodeString(string);
111 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
112 if(!bufferName.isEmpty()) {
113 IrcChannel *channel = ircChannel(bufferName);
115 return channel->encodeString(string);
117 return encodeString(string);
120 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
121 IrcUser *user = ircUser(userNick);
123 return user->encodeString(string);
124 return encodeString(string);
127 void CoreNetwork::connectToIrc(bool reconnecting) {
128 if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
129 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
130 if(unlimitedReconnectRetries())
131 _autoReconnectCount = -1;
133 _autoReconnectCount = autoReconnectRetries();
135 if(serverList().isEmpty()) {
136 qWarning() << "Server list empty, ignoring connect request!";
139 CoreIdentity *identity = identityPtr();
141 qWarning() << "Invalid identity configures, ignoring connect request!";
145 // cleaning up old quit reason
148 // use a random server?
149 if(useRandomServer()) {
150 _lastUsedServerIndex = qrand() % serverList().size();
151 } else if(_previousConnectionAttemptFailed) {
152 // cycle to next server if previous connection attempt failed
153 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
154 if(++_lastUsedServerIndex >= serverList().size()) {
155 _lastUsedServerIndex = 0;
158 _previousConnectionAttemptFailed = false;
160 Server server = usedServer();
161 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
162 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
164 if(server.useProxy) {
165 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
166 socket.setProxy(proxy);
168 socket.setProxy(QNetworkProxy::NoProxy);
172 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
174 CoreIdentity *identity = identityPtr();
176 socket.setLocalCertificate(identity->sslCert());
177 socket.setPrivateKey(identity->sslKey());
179 socket.connectToHostEncrypted(server.host, server.port);
181 socket.connectToHost(server.host, server.port);
184 socket.connectToHost(server.host, server.port);
188 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) {
189 _quitRequested = requested; // see socketDisconnected();
191 _autoReconnectTimer.stop();
192 _autoReconnectCount = 0; // prohibiting auto reconnect
194 disablePingTimeout();
201 awayMsg = me_->awayMessage();
202 Core::setAwayMessage(userId(), networkId(), awayMsg);
205 if(reason.isEmpty() && identityPtr())
206 _quitReason = identityPtr()->quitReason();
208 _quitReason = reason;
210 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
211 switch(socket.state()) {
212 case QAbstractSocket::ConnectedState:
213 userInputHandler()->issueQuit(_quitReason);
214 if(requested || withReconnect) {
215 // the irc server has 10 seconds to close the socket
216 _socketCloseTimer.start(10000);
221 socketDisconnected();
225 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
226 userInputHandler()->handleUserInput(buf, msg);
229 void CoreNetwork::putRawLine(QByteArray s) {
236 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
239 if(!prefix.isEmpty())
240 msg += ":" + prefix + " ";
241 msg += cmd.toUpper().toAscii();
243 for(int i = 0; i < params.size() - 1; i++) {
244 msg += " " + params[i];
246 if(!params.isEmpty())
247 msg += " :" + params.last();
252 void CoreNetwork::setChannelJoined(const QString &channel) {
253 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
255 Core::setChannelPersistent(userId(), networkId(), channel, true);
256 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
259 void CoreNetwork::setChannelParted(const QString &channel) {
260 removeChannelKey(channel);
261 _autoWhoQueue.removeAll(channel.toLower());
262 _autoWhoPending.remove(channel.toLower());
264 Core::setChannelPersistent(userId(), networkId(), channel, false);
267 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
269 removeChannelKey(channel);
271 _channelKeys[channel.toLower()] = key;
275 void CoreNetwork::removeChannelKey(const QString &channel) {
276 _channelKeys.remove(channel.toLower());
280 Cipher *CoreNetwork::cipher(const QString &target) const {
284 if(!Cipher::neededFeaturesAvailable())
287 QByteArray key = cipherKey(target);
291 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
293 if(channel->cipher()->setKey(key))
294 return channel->cipher();
296 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
297 if(user && user->cipher()->setKey(key))
298 return user->cipher();
303 QByteArray CoreNetwork::cipherKey(const QString &recipient) const {
304 return _cipherKeys.value(recipient.toLower(), QByteArray());
307 void CoreNetwork::setCipherKey(const QString &recipient, const QByteArray &key) {
309 _cipherKeys[recipient.toLower()] = key;
311 _cipherKeys.remove(recipient.toLower());
313 #endif /* HAVE_QCA2 */
315 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
316 QString chan = channel.toLower();
317 if(_autoWhoPending.value(chan, 0) <= 0)
319 if(--_autoWhoPending[chan] <= 0)
320 _autoWhoPending.remove(chan);
324 void CoreNetwork::setMyNick(const QString &mynick) {
325 Network::setMyNick(mynick);
326 if(connectionState() == Network::Initializing)
327 networkInitialized();
330 void CoreNetwork::socketHasData() {
331 while(socket.canReadLine()) {
332 QByteArray s = socket.readLine().trimmed();
333 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
334 #if QT_VERSION >= 0x040700
335 event->setTimestamp(QDateTime::currentDateTimeUtc());
337 event->setTimestamp(QDateTime::currentDateTime().toUTC());
339 emit newEvent(event);
343 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
344 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
347 _previousConnectionAttemptFailed = true;
348 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
349 emit connectionError(socket.errorString());
350 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
351 emitConnectionError(socket.errorString());
352 if(socket.state() < QAbstractSocket::ConnectedState) {
353 socketDisconnected();
357 void CoreNetwork::socketInitialized() {
358 qDebug() << "connected()";
359 Server server = usedServer();
361 if(server.useSsl && !socket.isEncrypted())
365 CoreIdentity *identity = identityPtr();
367 qCritical() << "Identity invalid!";
372 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
374 // TokenBucket to avoid sending too much at once
375 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
377 _tokenBucket = _burstSize; // init with a full bucket
378 _tokenBucketTimer.start(_messageDelay);
380 if(networkInfo().useSasl) {
381 putRawLine(serverEncode(QString("CAP REQ :sasl")));
383 if(!server.password.isEmpty()) {
384 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
387 if(identity->nicks().isEmpty()) {
389 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
391 nick = identity->nicks()[0];
393 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
394 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
397 void CoreNetwork::socketDisconnected() {
398 disablePingTimeout();
401 _autoWhoCycleTimer.stop();
402 _autoWhoTimer.stop();
403 _autoWhoQueue.clear();
404 _autoWhoPending.clear();
406 _socketCloseTimer.stop();
408 _tokenBucketTimer.stop();
412 foreach(QString channel, me_->channels())
413 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
417 emit disconnected(networkId());
418 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
420 _quitRequested = false;
421 setConnectionState(Network::Disconnected);
422 Core::setNetworkConnected(userId(), networkId(), false);
423 } else if(_autoReconnectCount != 0) {
424 setConnectionState(Network::Reconnecting);
425 if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
426 doAutoReconnect(); // first try is immediate
428 _autoReconnectTimer.start();
432 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
433 Network::ConnectionState state;
434 switch(socketState) {
435 case QAbstractSocket::UnconnectedState:
436 state = Network::Disconnected;
438 case QAbstractSocket::HostLookupState:
439 case QAbstractSocket::ConnectingState:
440 state = Network::Connecting;
442 case QAbstractSocket::ConnectedState:
443 state = Network::Initializing;
445 case QAbstractSocket::ClosingState:
446 state = Network::Disconnecting;
449 state = Network::Disconnected;
451 setConnectionState(state);
454 void CoreNetwork::networkInitialized() {
455 setConnectionState(Network::Initialized);
457 _quitRequested = false;
459 if(useAutoReconnect()) {
461 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
464 // restore away state
465 QString awayMsg = Core::awayMessage(userId(), networkId());
466 if(!awayMsg.isEmpty())
467 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
473 if(networkConfig()->autoWhoEnabled()) {
474 _autoWhoCycleTimer.start();
475 _autoWhoTimer.start();
476 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
479 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
480 Core::setNetworkConnected(userId(), networkId(), true);
483 void CoreNetwork::sendPerform() {
484 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
487 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
488 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
491 // restore old user modes if server default mode is set.
494 if(!me_->userModes().isEmpty()) {
497 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
498 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
503 foreach(QString line, perform()) {
504 if(!line.isEmpty()) userInput(statusBuf, line);
507 // rejoin channels we've been in
508 if(rejoinChannels()) {
509 QStringList channels, keys;
510 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
511 QString key = channelKey(chan);
513 channels.prepend(chan);
516 channels.append(chan);
519 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
520 if(!joinString.isEmpty())
521 userInputHandler()->handleJoin(statusBuf, joinString);
525 void CoreNetwork::restoreUserModes() {
529 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
530 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
532 QString modesDelta = Core::userModes(userId(), networkId());
533 QString currentModes = me_->userModes();
535 QString addModes, removeModes;
536 if(modesDelta.contains('-')) {
537 addModes = modesDelta.section('-', 0, 0);
538 removeModes = modesDelta.section('-', 1);
540 addModes = modesDelta;
544 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
545 if(currentModes.isEmpty())
546 removeModes = QString();
548 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
550 if(addModes.isEmpty() && removeModes.isEmpty())
553 if(!addModes.isEmpty())
554 addModes = '+' + addModes;
555 if(!removeModes.isEmpty())
556 removeModes = '-' + removeModes;
558 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
559 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
562 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
567 for(int i = 0; i < requestedModes.length(); i++) {
568 if(requestedModes[i] == '+') {
572 if(requestedModes[i] == '-') {
577 addModes += requestedModes[i];
579 removeModes += requestedModes[i];
584 QString addModesOld = _requestedUserModes.section('-', 0, 0);
585 QString removeModesOld = _requestedUserModes.section('-', 1);
587 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
588 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
589 addModes += addModesOld;
591 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
592 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
593 removeModes += removeModesOld;
595 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
598 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
599 QString persistentUserModes = Core::userModes(userId(), networkId());
601 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
602 QString requestedRemove = _requestedUserModes.section('-', 1);
604 QString persistentAdd, persistentRemove;
605 if(persistentUserModes.contains('-')) {
606 persistentAdd = persistentUserModes.section('-', 0, 0);
607 persistentRemove = persistentUserModes.section('-', 1);
609 persistentAdd = persistentUserModes;
612 // remove modes we didn't issue
613 if(requestedAdd.isEmpty())
614 addModes = QString();
616 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
618 if(requestedRemove.isEmpty())
619 removeModes = QString();
621 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
624 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
625 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
628 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
629 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
631 // update issued mode list
632 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
633 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
634 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
636 persistentAdd += addModes;
637 persistentRemove += removeModes;
638 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
641 void CoreNetwork::resetPersistentModes() {
642 _requestedUserModes = QString('-');
643 Core::setUserModes(userId(), networkId(), QString());
646 void CoreNetwork::setUseAutoReconnect(bool use) {
647 Network::setUseAutoReconnect(use);
649 _autoReconnectTimer.stop();
652 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
653 Network::setAutoReconnectInterval(interval);
654 _autoReconnectTimer.setInterval(interval * 1000);
657 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
658 Network::setAutoReconnectRetries(retries);
659 if(_autoReconnectCount != 0) {
660 if(unlimitedReconnectRetries())
661 _autoReconnectCount = -1;
663 _autoReconnectCount = autoReconnectRetries();
667 void CoreNetwork::doAutoReconnect() {
668 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
669 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
672 if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
673 _autoReconnectCount--; // -2 means we delay the next reconnect
677 void CoreNetwork::sendPing() {
678 uint now = QDateTime::currentDateTime().toTime_t();
679 if(_pingCount != 0) {
680 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
681 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
683 if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
684 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
685 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
686 // and unable to even handle a ping answer. So we ignore those misses.
687 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
691 userInputHandler()->handlePing(BufferInfo(), QString());
695 void CoreNetwork::enablePingTimeout(bool enable) {
697 disablePingTimeout();
700 if(networkConfig()->pingTimeoutEnabled())
705 void CoreNetwork::disablePingTimeout() {
710 void CoreNetwork::setPingInterval(int interval) {
711 _pingTimer.setInterval(interval * 1000);
714 /******** AutoWHO ********/
716 void CoreNetwork::startAutoWhoCycle() {
717 if(!_autoWhoQueue.isEmpty()) {
718 _autoWhoCycleTimer.stop();
721 _autoWhoQueue = channels();
724 void CoreNetwork::setAutoWhoDelay(int delay) {
725 _autoWhoTimer.setInterval(delay * 1000);
728 void CoreNetwork::setAutoWhoInterval(int interval) {
729 _autoWhoCycleTimer.setInterval(interval * 1000);
732 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
733 if(enabled && isConnected() && !_autoWhoTimer.isActive())
734 _autoWhoTimer.start();
736 _autoWhoTimer.stop();
737 _autoWhoCycleTimer.stop();
741 void CoreNetwork::sendAutoWho() {
742 // Don't send autowho if there are still some pending
743 if(_autoWhoPending.count())
746 while(!_autoWhoQueue.isEmpty()) {
747 QString chan = _autoWhoQueue.takeFirst();
748 IrcChannel *ircchan = ircChannel(chan);
749 if(!ircchan) continue;
750 if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
752 _autoWhoPending[chan]++;
753 putRawLine("WHO " + serverEncode(chan));
756 if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
757 // Timer was stopped, means a new cycle is due immediately
758 _autoWhoCycleTimer.start();
764 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
766 socket.ignoreSslErrors();
767 // TODO errorhandling
771 void CoreNetwork::fillBucketAndProcessQueue() {
772 if(_tokenBucket < _burstSize) {
776 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
777 writeToSocket(_msgQueue.takeFirst());
781 void CoreNetwork::writeToSocket(const QByteArray &data) {
783 socket.write("\r\n");
787 Network::Server CoreNetwork::usedServer() const {
788 if(_lastUsedServerIndex < serverList().count())
789 return serverList()[_lastUsedServerIndex];
791 if(!serverList().isEmpty())
792 return serverList()[0];
794 return Network::Server();
797 void CoreNetwork::requestConnect() const {
798 if(connectionState() != Disconnected) {
799 qWarning() << "Requesting connect while already being connected!";
802 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
805 void CoreNetwork::requestDisconnect() const {
806 if(connectionState() == Disconnected) {
807 qWarning() << "Requesting disconnect while not being connected!";
810 userInputHandler()->handleQuit(BufferInfo(), QString());
813 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
814 Network::Server currentServer = usedServer();
815 setNetworkInfo(info);
816 Core::updateNetwork(coreSession()->user(), info);
818 // the order of the servers might have changed,
819 // so we try to find the previously used server
820 _lastUsedServerIndex = 0;
821 for(int i = 0; i < serverList().count(); i++) {
822 Network::Server server = serverList()[i];
823 if(server.host == currentServer.host && server.port == currentServer.port) {
824 _lastUsedServerIndex = i;