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 coreSession()->eventManager()->sendEvent(new NetworkDataEvent(EventManager::NetworkIncoming, this, s));
336 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
337 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
340 _previousConnectionAttemptFailed = true;
341 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
342 emit connectionError(socket.errorString());
343 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
344 emitConnectionError(socket.errorString());
345 if(socket.state() < QAbstractSocket::ConnectedState) {
346 socketDisconnected();
350 void CoreNetwork::socketInitialized() {
351 Server server = usedServer();
353 if(server.useSsl && !socket.isEncrypted())
357 CoreIdentity *identity = identityPtr();
359 qCritical() << "Identity invalid!";
364 // TokenBucket to avoid sending too much at once
365 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
367 _tokenBucket = _burstSize; // init with a full bucket
368 _tokenBucketTimer.start(_messageDelay);
370 if(networkInfo().useSasl) {
371 putRawLine(serverEncode(QString("CAP REQ :sasl")));
373 if(!server.password.isEmpty()) {
374 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
377 if(identity->nicks().isEmpty()) {
379 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
381 nick = identity->nicks()[0];
383 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
384 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
387 void CoreNetwork::socketDisconnected() {
388 disablePingTimeout();
391 _autoWhoCycleTimer.stop();
392 _autoWhoTimer.stop();
393 _autoWhoQueue.clear();
394 _autoWhoPending.clear();
396 _socketCloseTimer.stop();
398 _tokenBucketTimer.stop();
402 foreach(QString channel, me_->channels())
403 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
407 emit disconnected(networkId());
409 _quitRequested = false;
410 setConnectionState(Network::Disconnected);
411 Core::setNetworkConnected(userId(), networkId(), false);
412 } else if(_autoReconnectCount != 0) {
413 setConnectionState(Network::Reconnecting);
414 if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
415 doAutoReconnect(); // first try is immediate
417 _autoReconnectTimer.start();
421 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
422 Network::ConnectionState state;
423 switch(socketState) {
424 case QAbstractSocket::UnconnectedState:
425 state = Network::Disconnected;
427 case QAbstractSocket::HostLookupState:
428 case QAbstractSocket::ConnectingState:
429 state = Network::Connecting;
431 case QAbstractSocket::ConnectedState:
432 state = Network::Initializing;
434 case QAbstractSocket::ClosingState:
435 state = Network::Disconnecting;
438 state = Network::Disconnected;
440 setConnectionState(state);
443 void CoreNetwork::networkInitialized() {
444 setConnectionState(Network::Initialized);
446 _quitRequested = false;
448 if(useAutoReconnect()) {
450 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
453 // restore away state
454 QString awayMsg = Core::awayMessage(userId(), networkId());
455 if(!awayMsg.isEmpty())
456 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
462 if(networkConfig()->autoWhoEnabled()) {
463 _autoWhoCycleTimer.start();
464 _autoWhoTimer.start();
465 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
468 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
469 Core::setNetworkConnected(userId(), networkId(), true);
472 void CoreNetwork::sendPerform() {
473 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
476 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
477 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
480 // restore old user modes if server default mode is set.
483 if(!me_->userModes().isEmpty()) {
486 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
487 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
492 foreach(QString line, perform()) {
493 if(!line.isEmpty()) userInput(statusBuf, line);
496 // rejoin channels we've been in
497 if(rejoinChannels()) {
498 QStringList channels, keys;
499 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
500 QString key = channelKey(chan);
502 channels.prepend(chan);
505 channels.append(chan);
508 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
509 if(!joinString.isEmpty())
510 userInputHandler()->handleJoin(statusBuf, joinString);
514 void CoreNetwork::restoreUserModes() {
518 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
519 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
521 QString modesDelta = Core::userModes(userId(), networkId());
522 QString currentModes = me_->userModes();
524 QString addModes, removeModes;
525 if(modesDelta.contains('-')) {
526 addModes = modesDelta.section('-', 0, 0);
527 removeModes = modesDelta.section('-', 1);
529 addModes = modesDelta;
533 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
534 if(currentModes.isEmpty())
535 removeModes = QString();
537 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
539 if(addModes.isEmpty() && removeModes.isEmpty())
542 if(!addModes.isEmpty())
543 addModes = '+' + addModes;
544 if(!removeModes.isEmpty())
545 removeModes = '-' + removeModes;
547 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
548 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
551 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
556 for(int i = 0; i < requestedModes.length(); i++) {
557 if(requestedModes[i] == '+') {
561 if(requestedModes[i] == '-') {
566 addModes += requestedModes[i];
568 removeModes += requestedModes[i];
573 QString addModesOld = _requestedUserModes.section('-', 0, 0);
574 QString removeModesOld = _requestedUserModes.section('-', 1);
576 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
577 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
578 addModes += addModesOld;
580 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
581 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
582 removeModes += removeModesOld;
584 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
587 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
588 QString persistentUserModes = Core::userModes(userId(), networkId());
590 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
591 QString requestedRemove = _requestedUserModes.section('-', 1);
593 QString persistentAdd, persistentRemove;
594 if(persistentUserModes.contains('-')) {
595 persistentAdd = persistentUserModes.section('-', 0, 0);
596 persistentRemove = persistentUserModes.section('-', 1);
598 persistentAdd = persistentUserModes;
601 // remove modes we didn't issue
602 if(requestedAdd.isEmpty())
603 addModes = QString();
605 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
607 if(requestedRemove.isEmpty())
608 removeModes = QString();
610 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
613 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
614 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
617 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
618 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
620 // update issued mode list
621 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
622 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
623 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
625 persistentAdd += addModes;
626 persistentRemove += removeModes;
627 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
630 void CoreNetwork::resetPersistentModes() {
631 _requestedUserModes = QString('-');
632 Core::setUserModes(userId(), networkId(), QString());
635 void CoreNetwork::setUseAutoReconnect(bool use) {
636 Network::setUseAutoReconnect(use);
638 _autoReconnectTimer.stop();
641 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
642 Network::setAutoReconnectInterval(interval);
643 _autoReconnectTimer.setInterval(interval * 1000);
646 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
647 Network::setAutoReconnectRetries(retries);
648 if(_autoReconnectCount != 0) {
649 if(unlimitedReconnectRetries())
650 _autoReconnectCount = -1;
652 _autoReconnectCount = autoReconnectRetries();
656 void CoreNetwork::doAutoReconnect() {
657 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
658 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
661 if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
662 _autoReconnectCount--; // -2 means we delay the next reconnect
666 void CoreNetwork::sendPing() {
667 uint now = QDateTime::currentDateTime().toTime_t();
668 if(_pingCount != 0) {
669 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
670 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
672 if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
673 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
674 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
675 // and unable to even handle a ping answer. So we ignore those misses.
676 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
680 userInputHandler()->handlePing(BufferInfo(), QString());
684 void CoreNetwork::enablePingTimeout(bool enable) {
686 disablePingTimeout();
689 if(networkConfig()->pingTimeoutEnabled())
694 void CoreNetwork::disablePingTimeout() {
699 void CoreNetwork::setPingInterval(int interval) {
700 _pingTimer.setInterval(interval * 1000);
703 /******** AutoWHO ********/
705 void CoreNetwork::startAutoWhoCycle() {
706 if(!_autoWhoQueue.isEmpty()) {
707 _autoWhoCycleTimer.stop();
710 _autoWhoQueue = channels();
713 void CoreNetwork::setAutoWhoDelay(int delay) {
714 _autoWhoTimer.setInterval(delay * 1000);
717 void CoreNetwork::setAutoWhoInterval(int interval) {
718 _autoWhoCycleTimer.setInterval(interval * 1000);
721 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
722 if(enabled && isConnected() && !_autoWhoTimer.isActive())
723 _autoWhoTimer.start();
725 _autoWhoTimer.stop();
726 _autoWhoCycleTimer.stop();
730 void CoreNetwork::sendAutoWho() {
731 // Don't send autowho if there are still some pending
732 if(_autoWhoPending.count())
735 while(!_autoWhoQueue.isEmpty()) {
736 QString chan = _autoWhoQueue.takeFirst();
737 IrcChannel *ircchan = ircChannel(chan);
738 if(!ircchan) continue;
739 if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
741 _autoWhoPending[chan]++;
742 putRawLine("WHO " + serverEncode(chan));
745 if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
746 // Timer was stopped, means a new cycle is due immediately
747 _autoWhoCycleTimer.start();
753 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
755 socket.ignoreSslErrors();
756 // TODO errorhandling
760 void CoreNetwork::fillBucketAndProcessQueue() {
761 if(_tokenBucket < _burstSize) {
765 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
766 writeToSocket(_msgQueue.takeFirst());
770 void CoreNetwork::writeToSocket(const QByteArray &data) {
772 socket.write("\r\n");
776 Network::Server CoreNetwork::usedServer() const {
777 if(_lastUsedServerIndex < serverList().count())
778 return serverList()[_lastUsedServerIndex];
780 if(!serverList().isEmpty())
781 return serverList()[0];
783 return Network::Server();
786 void CoreNetwork::requestConnect() const {
787 if(connectionState() != Disconnected) {
788 qWarning() << "Requesting connect while already being connected!";
791 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
794 void CoreNetwork::requestDisconnect() const {
795 if(connectionState() == Disconnected) {
796 qWarning() << "Requesting disconnect while not being connected!";
799 userInputHandler()->handleQuit(BufferInfo(), QString());
802 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
803 Network::Server currentServer = usedServer();
804 setNetworkInfo(info);
805 Core::updateNetwork(coreSession()->user(), info);
807 // the order of the servers might have changed,
808 // so we try to find the previously used server
809 _lastUsedServerIndex = 0;
810 for(int i = 0; i < serverList().count(); i++) {
811 Network::Server server = serverList()[i];
812 if(server.host == currentServer.host && server.port == currentServer.port) {
813 _lastUsedServerIndex = i;