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 "coresession.h"
25 #include "coreidentity.h"
26 #include "corenetworkconfig.h"
28 #include "ircserverhandler.h"
29 #include "coreuserinputhandler.h"
30 #include "ctcphandler.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),
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);
203 Core::setUserModes(userId(), networkId(), me_->userModes());
206 if(reason.isEmpty() && identityPtr())
207 _quitReason = identityPtr()->quitReason();
209 _quitReason = reason;
211 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
212 switch(socket.state()) {
213 case QAbstractSocket::ConnectedState:
214 userInputHandler()->issueQuit(_quitReason);
215 if(requested || withReconnect) {
216 // the irc server has 10 seconds to close the socket
217 _socketCloseTimer.start(10000);
222 socketDisconnected();
226 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
227 userInputHandler()->handleUserInput(buf, msg);
230 void CoreNetwork::putRawLine(QByteArray s) {
237 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
240 if(!prefix.isEmpty())
241 msg += ":" + prefix + " ";
242 msg += cmd.toUpper().toAscii();
244 for(int i = 0; i < params.size() - 1; i++) {
245 msg += " " + params[i];
247 if(!params.isEmpty())
248 msg += " :" + params.last();
253 void CoreNetwork::setChannelJoined(const QString &channel) {
254 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
256 Core::setChannelPersistent(userId(), networkId(), channel, true);
257 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
260 void CoreNetwork::setChannelParted(const QString &channel) {
261 removeChannelKey(channel);
262 _autoWhoQueue.removeAll(channel.toLower());
263 _autoWhoPending.remove(channel.toLower());
265 Core::setChannelPersistent(userId(), networkId(), channel, false);
268 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
270 removeChannelKey(channel);
272 _channelKeys[channel.toLower()] = key;
276 void CoreNetwork::removeChannelKey(const QString &channel) {
277 _channelKeys.remove(channel.toLower());
280 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
281 QString chan = channel.toLower();
282 if(_autoWhoPending.value(chan, 0) <= 0)
284 if(--_autoWhoPending[chan] <= 0)
285 _autoWhoPending.remove(chan);
289 void CoreNetwork::setMyNick(const QString &mynick) {
290 Network::setMyNick(mynick);
291 if(connectionState() == Network::Initializing)
292 networkInitialized();
295 void CoreNetwork::socketHasData() {
296 while(socket.canReadLine()) {
297 QByteArray s = socket.readLine().trimmed();
298 ircServerHandler()->handleServerMsg(s);
302 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
303 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
306 _previousConnectionAttemptFailed = true;
307 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
308 emit connectionError(socket.errorString());
309 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
310 emitConnectionError(socket.errorString());
311 if(socket.state() < QAbstractSocket::ConnectedState) {
312 socketDisconnected();
316 void CoreNetwork::socketInitialized() {
317 Server server = usedServer();
319 if(server.useSsl && !socket.isEncrypted())
323 CoreIdentity *identity = identityPtr();
325 qCritical() << "Identity invalid!";
330 // TokenBucket to avoid sending too much at once
331 _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
333 _tokenBucket = _burstSize; // init with a full bucket
334 _tokenBucketTimer.start(_messageDelay);
336 if(networkInfo().useSasl) {
337 putRawLine(serverEncode(QString("CAP REQ :sasl")));
339 if(!server.password.isEmpty()) {
340 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
343 if(identity->nicks().isEmpty()) {
345 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
347 nick = identity->nicks()[0];
349 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
350 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
353 void CoreNetwork::socketDisconnected() {
354 disablePingTimeout();
357 _autoWhoCycleTimer.stop();
358 _autoWhoTimer.stop();
359 _autoWhoQueue.clear();
360 _autoWhoPending.clear();
362 _socketCloseTimer.stop();
364 _tokenBucketTimer.stop();
368 foreach(QString channel, me_->channels())
369 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
373 emit disconnected(networkId());
375 _quitRequested = false;
376 setConnectionState(Network::Disconnected);
377 Core::setNetworkConnected(userId(), networkId(), false);
378 } else if(_autoReconnectCount != 0) {
379 setConnectionState(Network::Reconnecting);
380 if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
381 doAutoReconnect(); // first try is immediate
383 _autoReconnectTimer.start();
387 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
388 Network::ConnectionState state;
389 switch(socketState) {
390 case QAbstractSocket::UnconnectedState:
391 state = Network::Disconnected;
393 case QAbstractSocket::HostLookupState:
394 case QAbstractSocket::ConnectingState:
395 state = Network::Connecting;
397 case QAbstractSocket::ConnectedState:
398 state = Network::Initializing;
400 case QAbstractSocket::ClosingState:
401 state = Network::Disconnecting;
404 state = Network::Disconnected;
406 setConnectionState(state);
409 void CoreNetwork::networkInitialized() {
410 setConnectionState(Network::Initialized);
412 _quitRequested = false;
414 if(useAutoReconnect()) {
416 _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
419 // restore away state
420 QString awayMsg = Core::awayMessage(userId(), networkId());
421 if(!awayMsg.isEmpty())
422 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
424 // restore old user modes if server default mode is set.
427 if(!me_->userModes().isEmpty()) {
430 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
431 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
439 if(networkConfig()->autoWhoEnabled()) {
440 _autoWhoCycleTimer.start();
441 _autoWhoTimer.start();
442 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
445 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
446 Core::setNetworkConnected(userId(), networkId(), true);
449 void CoreNetwork::sendPerform() {
450 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
453 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
454 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
458 foreach(QString line, perform()) {
459 if(!line.isEmpty()) userInput(statusBuf, line);
462 // rejoin channels we've been in
463 if(rejoinChannels()) {
464 QStringList channels, keys;
465 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
466 QString key = channelKey(chan);
468 channels.prepend(chan);
471 channels.append(chan);
474 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
475 if(!joinString.isEmpty())
476 userInputHandler()->handleJoin(statusBuf, joinString);
480 void CoreNetwork::restoreUserModes() {
484 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
485 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
488 QString addModes = Core::userModes(userId(), networkId());
489 QString currentModes = me_->userModes();
491 removeModes = currentModes;
492 removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
493 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
495 removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
496 addModes = QString("%1 +%2").arg(me_->nick(), addModes);
497 userInputHandler()->handleMode(BufferInfo(), removeModes);
498 userInputHandler()->handleMode(BufferInfo(), addModes);
501 void CoreNetwork::setUseAutoReconnect(bool use) {
502 Network::setUseAutoReconnect(use);
504 _autoReconnectTimer.stop();
507 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
508 Network::setAutoReconnectInterval(interval);
509 _autoReconnectTimer.setInterval(interval * 1000);
512 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
513 Network::setAutoReconnectRetries(retries);
514 if(_autoReconnectCount != 0) {
515 if(unlimitedReconnectRetries())
516 _autoReconnectCount = -1;
518 _autoReconnectCount = autoReconnectRetries();
522 void CoreNetwork::doAutoReconnect() {
523 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
524 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
527 if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
528 _autoReconnectCount--; // -2 means we delay the next reconnect
532 void CoreNetwork::sendPing() {
533 uint now = QDateTime::currentDateTime().toTime_t();
534 if(_pingCount != 0) {
535 qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
536 << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
538 if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
539 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
540 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
541 // and unable to even handle a ping answer. So we ignore those misses.
542 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
546 userInputHandler()->handlePing(BufferInfo(), QString());
550 void CoreNetwork::enablePingTimeout(bool enable) {
552 disablePingTimeout();
555 if(networkConfig()->pingTimeoutEnabled())
560 void CoreNetwork::disablePingTimeout() {
565 void CoreNetwork::setPingInterval(int interval) {
566 _pingTimer.setInterval(interval * 1000);
569 /******** AutoWHO ********/
571 void CoreNetwork::startAutoWhoCycle() {
572 if(!_autoWhoQueue.isEmpty()) {
573 _autoWhoCycleTimer.stop();
576 _autoWhoQueue = channels();
579 void CoreNetwork::setAutoWhoDelay(int delay) {
580 _autoWhoTimer.setInterval(delay * 1000);
583 void CoreNetwork::setAutoWhoInterval(int interval) {
584 _autoWhoCycleTimer.setInterval(interval * 1000);
587 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
588 if(enabled && isConnected() && !_autoWhoTimer.isActive())
589 _autoWhoTimer.start();
591 _autoWhoTimer.stop();
592 _autoWhoCycleTimer.stop();
596 void CoreNetwork::sendAutoWho() {
597 // Don't send autowho if there are still some pending
598 if(_autoWhoPending.count())
601 while(!_autoWhoQueue.isEmpty()) {
602 QString chan = _autoWhoQueue.takeFirst();
603 IrcChannel *ircchan = ircChannel(chan);
604 if(!ircchan) continue;
605 if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
607 _autoWhoPending[chan]++;
608 putRawLine("WHO " + serverEncode(chan));
611 if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
612 // Timer was stopped, means a new cycle is due immediately
613 _autoWhoCycleTimer.start();
619 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
621 socket.ignoreSslErrors();
622 // TODO errorhandling
626 void CoreNetwork::fillBucketAndProcessQueue() {
627 if(_tokenBucket < _burstSize) {
631 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
632 writeToSocket(_msgQueue.takeFirst());
636 void CoreNetwork::writeToSocket(const QByteArray &data) {
638 socket.write("\r\n");
642 Network::Server CoreNetwork::usedServer() const {
643 if(_lastUsedServerIndex < serverList().count())
644 return serverList()[_lastUsedServerIndex];
646 if(!serverList().isEmpty())
647 return serverList()[0];
649 return Network::Server();
652 void CoreNetwork::requestConnect() const {
653 if(connectionState() != Disconnected) {
654 qWarning() << "Requesting connect while already being connected!";
657 QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
660 void CoreNetwork::requestDisconnect() const {
661 if(connectionState() == Disconnected) {
662 qWarning() << "Requesting disconnect while not being connected!";
665 userInputHandler()->handleQuit(BufferInfo(), QString());
668 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
669 Network::Server currentServer = usedServer();
670 setNetworkInfo(info);
671 Core::updateNetwork(coreSession()->user(), info);
673 // the order of the servers might have changed,
674 // so we try to find the previously used server
675 _lastUsedServerIndex = 0;
676 for(int i = 0; i < serverList().count(); i++) {
677 Network::Server server = serverList()[i];
678 if(server.host == currentServer.host && server.port == currentServer.port) {
679 _lastUsedServerIndex = i;