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"
23 #include "ctcphandler.h"
25 #include "coreidentity.h"
26 #include "corenetworkconfig.h"
27 #include "coresession.h"
28 #include "coreuserinputhandler.h"
29 #include "ircserverhandler.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 _ircServerHandler(new IrcServerHandler(this)),
37 _userInputHandler(new CoreUserInputHandler(this)),
38 _ctcpHandler(new CtcpHandler(this)),
39 _autoReconnectCount(0),
40 _quitRequested(false),
42 _previousConnectionAttemptFailed(false),
43 _lastUsedServerIndex(0),
47 _requestedUserModes('-')
49 _autoReconnectTimer.setSingleShot(true);
50 _socketCloseTimer.setSingleShot(true);
51 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
53 setPingInterval(networkConfig()->pingInterval());
54 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
56 setAutoWhoDelay(networkConfig()->autoWhoDelay());
57 setAutoWhoInterval(networkConfig()->autoWhoInterval());
59 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
60 foreach(QString chan, channels.keys()) {
61 _channelKeys[chan.toLower()] = channels[chan];
64 connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
65 connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
66 connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
67 connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
68 connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
70 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
71 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
72 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
73 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
75 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
76 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
77 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
78 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
79 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
81 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
82 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
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 _ircServerHandler;
91 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 QByteArray key = cipherKey(target);
288 CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
290 if(channel->cipher()->setKey(key))
291 return channel->cipher();
293 CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
294 if(user && user->cipher()->setKey(key))
295 return user->cipher();
300 QByteArray CoreNetwork::cipherKey(const QString &recipient) const {
301 return _cipherKeys.value(recipient.toLower(), QByteArray());
304 void CoreNetwork::setCipherKey(const QString &recipient, const QByteArray &key) {
306 _cipherKeys[recipient.toLower()] = key;
308 _cipherKeys.remove(recipient.toLower());
310 #endif /* HAVE_QCA2 */
312 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
313 QString chan = channel.toLower();
314 if(_autoWhoPending.value(chan, 0) <= 0)
316 if(--_autoWhoPending[chan] <= 0)
317 _autoWhoPending.remove(chan);
321 void CoreNetwork::setMyNick(const QString &mynick) {
322 Network::setMyNick(mynick);
323 if(connectionState() == Network::Initializing)
324 networkInitialized();
327 void CoreNetwork::socketHasData() {
328 while(socket.canReadLine()) {
329 QByteArray s = socket.readLine().trimmed();
330 ircServerHandler()->handleServerMsg(s); // FIXME remove with events
332 NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
333 #if QT_VERSION >= 0x040700
334 event->setTimestamp(QDateTime::currentDateTimeUtc());
336 event->setTimestamp(QDateTime::currentDateTime().toUTC());
338 coreSession()->eventManager()->sendEvent(event);
342 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
343 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
346 _previousConnectionAttemptFailed = true;
347 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
348 emit connectionError(socket.errorString());
349 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
350 emitConnectionError(socket.errorString());
351 if(socket.state() < QAbstractSocket::ConnectedState) {
352 socketDisconnected();
356 void CoreNetwork::socketInitialized() {
357 Server server = usedServer();
359 if(server.useSsl && !socket.isEncrypted())
363 CoreIdentity *identity = identityPtr();
365 qCritical() << "Identity invalid!";
370 // TokenBucket to avoid sending too much at once
371 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
373 _tokenBucket = _burstSize; // init with a full bucket
374 _tokenBucketTimer.start(_messageDelay);
376 if(networkInfo().useSasl) {
377 putRawLine(serverEncode(QString("CAP REQ :sasl")));
379 if(!server.password.isEmpty()) {
380 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
383 if(identity->nicks().isEmpty()) {
385 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
387 nick = identity->nicks()[0];
389 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
390 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
393 void CoreNetwork::socketDisconnected() {
394 disablePingTimeout();
397 _autoWhoCycleTimer.stop();
398 _autoWhoTimer.stop();
399 _autoWhoQueue.clear();
400 _autoWhoPending.clear();
402 _socketCloseTimer.stop();
404 _tokenBucketTimer.stop();
408 foreach(QString channel, me_->channels())
409 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
413 emit disconnected(networkId());
415 _quitRequested = false;
416 setConnectionState(Network::Disconnected);
417 Core::setNetworkConnected(userId(), networkId(), false);
418 } else if(_autoReconnectCount != 0) {
419 setConnectionState(Network::Reconnecting);
420 if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
421 doAutoReconnect(); // first try is immediate
423 _autoReconnectTimer.start();
427 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
428 Network::ConnectionState state;
429 switch(socketState) {
430 case QAbstractSocket::UnconnectedState:
431 state = Network::Disconnected;
433 case QAbstractSocket::HostLookupState:
434 case QAbstractSocket::ConnectingState:
435 state = Network::Connecting;
437 case QAbstractSocket::ConnectedState:
438 state = Network::Initializing;
440 case QAbstractSocket::ClosingState:
441 state = Network::Disconnecting;
444 state = Network::Disconnected;
446 setConnectionState(state);
449 void CoreNetwork::networkInitialized() {
450 setConnectionState(Network::Initialized);
452 _quitRequested = false;
454 if(useAutoReconnect()) {
456 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
459 // restore away state
460 QString awayMsg = Core::awayMessage(userId(), networkId());
461 if(!awayMsg.isEmpty())
462 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
468 if(networkConfig()->autoWhoEnabled()) {
469 _autoWhoCycleTimer.start();
470 _autoWhoTimer.start();
471 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
474 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
475 Core::setNetworkConnected(userId(), networkId(), true);
478 void CoreNetwork::sendPerform() {
479 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
482 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
483 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
486 // restore old user modes if server default mode is set.
489 if(!me_->userModes().isEmpty()) {
492 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
493 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
498 foreach(QString line, perform()) {
499 if(!line.isEmpty()) userInput(statusBuf, line);
502 // rejoin channels we've been in
503 if(rejoinChannels()) {
504 QStringList channels, keys;
505 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
506 QString key = channelKey(chan);
508 channels.prepend(chan);
511 channels.append(chan);
514 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
515 if(!joinString.isEmpty())
516 userInputHandler()->handleJoin(statusBuf, joinString);
520 void CoreNetwork::restoreUserModes() {
524 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
525 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
527 QString modesDelta = Core::userModes(userId(), networkId());
528 QString currentModes = me_->userModes();
530 QString addModes, removeModes;
531 if(modesDelta.contains('-')) {
532 addModes = modesDelta.section('-', 0, 0);
533 removeModes = modesDelta.section('-', 1);
535 addModes = modesDelta;
539 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
540 if(currentModes.isEmpty())
541 removeModes = QString();
543 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
545 if(addModes.isEmpty() && removeModes.isEmpty())
548 if(!addModes.isEmpty())
549 addModes = '+' + addModes;
550 if(!removeModes.isEmpty())
551 removeModes = '-' + removeModes;
553 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
554 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
557 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
562 for(int i = 0; i < requestedModes.length(); i++) {
563 if(requestedModes[i] == '+') {
567 if(requestedModes[i] == '-') {
572 addModes += requestedModes[i];
574 removeModes += requestedModes[i];
579 QString addModesOld = _requestedUserModes.section('-', 0, 0);
580 QString removeModesOld = _requestedUserModes.section('-', 1);
582 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
583 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
584 addModes += addModesOld;
586 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
587 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
588 removeModes += removeModesOld;
590 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
593 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
594 QString persistentUserModes = Core::userModes(userId(), networkId());
596 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
597 QString requestedRemove = _requestedUserModes.section('-', 1);
599 QString persistentAdd, persistentRemove;
600 if(persistentUserModes.contains('-')) {
601 persistentAdd = persistentUserModes.section('-', 0, 0);
602 persistentRemove = persistentUserModes.section('-', 1);
604 persistentAdd = persistentUserModes;
607 // remove modes we didn't issue
608 if(requestedAdd.isEmpty())
609 addModes = QString();
611 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
613 if(requestedRemove.isEmpty())
614 removeModes = QString();
616 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
619 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
620 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
623 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
624 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
626 // update issued mode list
627 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
628 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
629 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
631 persistentAdd += addModes;
632 persistentRemove += removeModes;
633 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
636 void CoreNetwork::resetPersistentModes() {
637 _requestedUserModes = QString('-');
638 Core::setUserModes(userId(), networkId(), QString());
641 void CoreNetwork::setUseAutoReconnect(bool use) {
642 Network::setUseAutoReconnect(use);
644 _autoReconnectTimer.stop();
647 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
648 Network::setAutoReconnectInterval(interval);
649 _autoReconnectTimer.setInterval(interval * 1000);
652 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
653 Network::setAutoReconnectRetries(retries);
654 if(_autoReconnectCount != 0) {
655 if(unlimitedReconnectRetries())
656 _autoReconnectCount = -1;
658 _autoReconnectCount = autoReconnectRetries();
662 void CoreNetwork::doAutoReconnect() {
663 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
664 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
667 if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
668 _autoReconnectCount--; // -2 means we delay the next reconnect
672 void CoreNetwork::sendPing() {
673 uint now = QDateTime::currentDateTime().toTime_t();
674 if(_pingCount != 0) {
675 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
676 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
678 if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
679 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
680 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
681 // and unable to even handle a ping answer. So we ignore those misses.
682 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
686 userInputHandler()->handlePing(BufferInfo(), QString());
690 void CoreNetwork::enablePingTimeout(bool enable) {
692 disablePingTimeout();
695 if(networkConfig()->pingTimeoutEnabled())
700 void CoreNetwork::disablePingTimeout() {
705 void CoreNetwork::setPingInterval(int interval) {
706 _pingTimer.setInterval(interval * 1000);
709 /******** AutoWHO ********/
711 void CoreNetwork::startAutoWhoCycle() {
712 if(!_autoWhoQueue.isEmpty()) {
713 _autoWhoCycleTimer.stop();
716 _autoWhoQueue = channels();
719 void CoreNetwork::setAutoWhoDelay(int delay) {
720 _autoWhoTimer.setInterval(delay * 1000);
723 void CoreNetwork::setAutoWhoInterval(int interval) {
724 _autoWhoCycleTimer.setInterval(interval * 1000);
727 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
728 if(enabled && isConnected() && !_autoWhoTimer.isActive())
729 _autoWhoTimer.start();
731 _autoWhoTimer.stop();
732 _autoWhoCycleTimer.stop();
736 void CoreNetwork::sendAutoWho() {
737 // Don't send autowho if there are still some pending
738 if(_autoWhoPending.count())
741 while(!_autoWhoQueue.isEmpty()) {
742 QString chan = _autoWhoQueue.takeFirst();
743 IrcChannel *ircchan = ircChannel(chan);
744 if(!ircchan) continue;
745 if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
747 _autoWhoPending[chan]++;
748 putRawLine("WHO " + serverEncode(chan));
751 if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
752 // Timer was stopped, means a new cycle is due immediately
753 _autoWhoCycleTimer.start();
759 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
761 socket.ignoreSslErrors();
762 // TODO errorhandling
766 void CoreNetwork::fillBucketAndProcessQueue() {
767 if(_tokenBucket < _burstSize) {
771 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
772 writeToSocket(_msgQueue.takeFirst());
776 void CoreNetwork::writeToSocket(const QByteArray &data) {
778 socket.write("\r\n");
782 Network::Server CoreNetwork::usedServer() const {
783 if(_lastUsedServerIndex < serverList().count())
784 return serverList()[_lastUsedServerIndex];
786 if(!serverList().isEmpty())
787 return serverList()[0];
789 return Network::Server();
792 void CoreNetwork::requestConnect() const {
793 if(connectionState() != Disconnected) {
794 qWarning() << "Requesting connect while already being connected!";
797 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
800 void CoreNetwork::requestDisconnect() const {
801 if(connectionState() == Disconnected) {
802 qWarning() << "Requesting disconnect while not being connected!";
805 userInputHandler()->handleQuit(BufferInfo(), QString());
808 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
809 Network::Server currentServer = usedServer();
810 setNetworkInfo(info);
811 Core::updateNetwork(coreSession()->user(), info);
813 // the order of the servers might have changed,
814 // so we try to find the previously used server
815 _lastUsedServerIndex = 0;
816 for(int i = 0; i < serverList().count(); i++) {
817 Network::Server server = serverList()[i];
818 if(server.host == currentServer.host && server.port == currentServer.port) {
819 _lastUsedServerIndex = i;