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)), Qt::BlockingQueuedConnection);
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 Server server = usedServer();
360 if(server.useSsl && !socket.isEncrypted())
364 CoreIdentity *identity = identityPtr();
366 qCritical() << "Identity invalid!";
371 emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
373 // TokenBucket to avoid sending too much at once
374 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
376 _tokenBucket = _burstSize; // init with a full bucket
377 _tokenBucketTimer.start(_messageDelay);
379 if(networkInfo().useSasl) {
380 putRawLine(serverEncode(QString("CAP REQ :sasl")));
382 if(!server.password.isEmpty()) {
383 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
386 if(identity->nicks().isEmpty()) {
388 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
390 nick = identity->nicks()[0];
392 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
393 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
396 void CoreNetwork::socketDisconnected() {
397 disablePingTimeout();
400 _autoWhoCycleTimer.stop();
401 _autoWhoTimer.stop();
402 _autoWhoQueue.clear();
403 _autoWhoPending.clear();
405 _socketCloseTimer.stop();
407 _tokenBucketTimer.stop();
411 foreach(QString channel, me_->channels())
412 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
416 emit disconnected(networkId());
417 emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
419 _quitRequested = false;
420 setConnectionState(Network::Disconnected);
421 Core::setNetworkConnected(userId(), networkId(), false);
422 } else if(_autoReconnectCount != 0) {
423 setConnectionState(Network::Reconnecting);
424 if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
425 doAutoReconnect(); // first try is immediate
427 _autoReconnectTimer.start();
431 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
432 Network::ConnectionState state;
433 switch(socketState) {
434 case QAbstractSocket::UnconnectedState:
435 state = Network::Disconnected;
437 case QAbstractSocket::HostLookupState:
438 case QAbstractSocket::ConnectingState:
439 state = Network::Connecting;
441 case QAbstractSocket::ConnectedState:
442 state = Network::Initializing;
444 case QAbstractSocket::ClosingState:
445 state = Network::Disconnecting;
448 state = Network::Disconnected;
450 setConnectionState(state);
453 void CoreNetwork::networkInitialized() {
454 setConnectionState(Network::Initialized);
456 _quitRequested = false;
458 if(useAutoReconnect()) {
460 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
463 // restore away state
464 QString awayMsg = Core::awayMessage(userId(), networkId());
465 if(!awayMsg.isEmpty())
466 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
472 if(networkConfig()->autoWhoEnabled()) {
473 _autoWhoCycleTimer.start();
474 _autoWhoTimer.start();
475 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
478 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
479 Core::setNetworkConnected(userId(), networkId(), true);
482 void CoreNetwork::sendPerform() {
483 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
486 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
487 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
490 // restore old user modes if server default mode is set.
493 if(!me_->userModes().isEmpty()) {
496 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
497 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
502 foreach(QString line, perform()) {
503 if(!line.isEmpty()) userInput(statusBuf, line);
506 // rejoin channels we've been in
507 if(rejoinChannels()) {
508 QStringList channels, keys;
509 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
510 QString key = channelKey(chan);
512 channels.prepend(chan);
515 channels.append(chan);
518 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
519 if(!joinString.isEmpty())
520 userInputHandler()->handleJoin(statusBuf, joinString);
524 void CoreNetwork::restoreUserModes() {
528 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
529 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
531 QString modesDelta = Core::userModes(userId(), networkId());
532 QString currentModes = me_->userModes();
534 QString addModes, removeModes;
535 if(modesDelta.contains('-')) {
536 addModes = modesDelta.section('-', 0, 0);
537 removeModes = modesDelta.section('-', 1);
539 addModes = modesDelta;
543 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
544 if(currentModes.isEmpty())
545 removeModes = QString();
547 removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
549 if(addModes.isEmpty() && removeModes.isEmpty())
552 if(!addModes.isEmpty())
553 addModes = '+' + addModes;
554 if(!removeModes.isEmpty())
555 removeModes = '-' + removeModes;
557 // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
558 putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
561 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
566 for(int i = 0; i < requestedModes.length(); i++) {
567 if(requestedModes[i] == '+') {
571 if(requestedModes[i] == '-') {
576 addModes += requestedModes[i];
578 removeModes += requestedModes[i];
583 QString addModesOld = _requestedUserModes.section('-', 0, 0);
584 QString removeModesOld = _requestedUserModes.section('-', 1);
586 addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
587 addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
588 addModes += addModesOld;
590 removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
591 removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
592 removeModes += removeModesOld;
594 _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
597 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
598 QString persistentUserModes = Core::userModes(userId(), networkId());
600 QString requestedAdd = _requestedUserModes.section('-', 0, 0);
601 QString requestedRemove = _requestedUserModes.section('-', 1);
603 QString persistentAdd, persistentRemove;
604 if(persistentUserModes.contains('-')) {
605 persistentAdd = persistentUserModes.section('-', 0, 0);
606 persistentRemove = persistentUserModes.section('-', 1);
608 persistentAdd = persistentUserModes;
611 // remove modes we didn't issue
612 if(requestedAdd.isEmpty())
613 addModes = QString();
615 addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
617 if(requestedRemove.isEmpty())
618 removeModes = QString();
620 removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
623 persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
624 persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
627 persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
628 persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
630 // update issued mode list
631 requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
632 requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
633 _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
635 persistentAdd += addModes;
636 persistentRemove += removeModes;
637 Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
640 void CoreNetwork::resetPersistentModes() {
641 _requestedUserModes = QString('-');
642 Core::setUserModes(userId(), networkId(), QString());
645 void CoreNetwork::setUseAutoReconnect(bool use) {
646 Network::setUseAutoReconnect(use);
648 _autoReconnectTimer.stop();
651 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
652 Network::setAutoReconnectInterval(interval);
653 _autoReconnectTimer.setInterval(interval * 1000);
656 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
657 Network::setAutoReconnectRetries(retries);
658 if(_autoReconnectCount != 0) {
659 if(unlimitedReconnectRetries())
660 _autoReconnectCount = -1;
662 _autoReconnectCount = autoReconnectRetries();
666 void CoreNetwork::doAutoReconnect() {
667 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
668 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
671 if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
672 _autoReconnectCount--; // -2 means we delay the next reconnect
676 void CoreNetwork::sendPing() {
677 uint now = QDateTime::currentDateTime().toTime_t();
678 if(_pingCount != 0) {
679 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
680 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
682 if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
683 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
684 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
685 // and unable to even handle a ping answer. So we ignore those misses.
686 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
690 userInputHandler()->handlePing(BufferInfo(), QString());
694 void CoreNetwork::enablePingTimeout(bool enable) {
696 disablePingTimeout();
699 if(networkConfig()->pingTimeoutEnabled())
704 void CoreNetwork::disablePingTimeout() {
709 void CoreNetwork::setPingInterval(int interval) {
710 _pingTimer.setInterval(interval * 1000);
713 /******** AutoWHO ********/
715 void CoreNetwork::startAutoWhoCycle() {
716 if(!_autoWhoQueue.isEmpty()) {
717 _autoWhoCycleTimer.stop();
720 _autoWhoQueue = channels();
723 void CoreNetwork::setAutoWhoDelay(int delay) {
724 _autoWhoTimer.setInterval(delay * 1000);
727 void CoreNetwork::setAutoWhoInterval(int interval) {
728 _autoWhoCycleTimer.setInterval(interval * 1000);
731 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
732 if(enabled && isConnected() && !_autoWhoTimer.isActive())
733 _autoWhoTimer.start();
735 _autoWhoTimer.stop();
736 _autoWhoCycleTimer.stop();
740 void CoreNetwork::sendAutoWho() {
741 // Don't send autowho if there are still some pending
742 if(_autoWhoPending.count())
745 while(!_autoWhoQueue.isEmpty()) {
746 QString chan = _autoWhoQueue.takeFirst();
747 IrcChannel *ircchan = ircChannel(chan);
748 if(!ircchan) continue;
749 if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
751 _autoWhoPending[chan]++;
752 putRawLine("WHO " + serverEncode(chan));
755 if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
756 // Timer was stopped, means a new cycle is due immediately
757 _autoWhoCycleTimer.start();
763 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
765 socket.ignoreSslErrors();
766 // TODO errorhandling
770 void CoreNetwork::fillBucketAndProcessQueue() {
771 if(_tokenBucket < _burstSize) {
775 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
776 writeToSocket(_msgQueue.takeFirst());
780 void CoreNetwork::writeToSocket(const QByteArray &data) {
782 socket.write("\r\n");
786 Network::Server CoreNetwork::usedServer() const {
787 if(_lastUsedServerIndex < serverList().count())
788 return serverList()[_lastUsedServerIndex];
790 if(!serverList().isEmpty())
791 return serverList()[0];
793 return Network::Server();
796 void CoreNetwork::requestConnect() const {
797 if(connectionState() != Disconnected) {
798 qWarning() << "Requesting connect while already being connected!";
801 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
804 void CoreNetwork::requestDisconnect() const {
805 if(connectionState() == Disconnected) {
806 qWarning() << "Requesting disconnect while not being connected!";
809 userInputHandler()->handleQuit(BufferInfo(), QString());
812 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
813 Network::Server currentServer = usedServer();
814 setNetworkInfo(info);
815 Core::updateNetwork(coreSession()->user(), info);
817 // the order of the servers might have changed,
818 // so we try to find the previously used server
819 _lastUsedServerIndex = 0;
820 for(int i = 0; i < serverList().count(); i++) {
821 Network::Server server = serverList()[i];
822 if(server.host == currentServer.host && server.port == currentServer.port) {
823 _lastUsedServerIndex = i;