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"
27 #include "ircserverhandler.h"
28 #include "userinputhandler.h"
29 #include "ctcphandler.h"
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32 : Network(networkid, session),
33 _coreSession(session),
34 _ircServerHandler(new IrcServerHandler(this)),
35 _userInputHandler(new UserInputHandler(this)),
36 _ctcpHandler(new CtcpHandler(this)),
37 _autoReconnectCount(0),
38 _quitRequested(false),
40 _previousConnectionAttemptFailed(false),
41 _lastUsedServerIndex(0),
45 // TODO make autowho configurable (possibly per-network)
46 _autoWhoEnabled(true),
48 _autoWhoNickLimit(0), // unlimited
51 _autoReconnectTimer.setSingleShot(true);
52 _socketCloseTimer.setSingleShot(true);
53 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
55 _pingTimer.setInterval(30000);
56 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
58 _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
59 _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
61 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
62 foreach(QString chan, channels.keys()) {
63 _channelKeys[chan.toLower()] = channels[chan];
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()));
70 connect(this, SIGNAL(connectRequested()), this, SLOT(connectToIrc()));
73 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
74 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
75 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
76 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
77 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
79 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
80 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
84 CoreNetwork::~CoreNetwork() {
85 if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
86 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
87 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
88 delete _ircServerHandler;
89 delete _userInputHandler;
93 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
94 if(!bufferName.isEmpty()) {
95 IrcChannel *channel = ircChannel(bufferName);
97 return channel->decodeString(string);
99 return decodeString(string);
102 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
103 IrcUser *user = ircUser(userNick);
105 return user->decodeString(string);
106 return decodeString(string);
109 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
110 if(!bufferName.isEmpty()) {
111 IrcChannel *channel = ircChannel(bufferName);
113 return channel->encodeString(string);
115 return encodeString(string);
118 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
119 IrcUser *user = ircUser(userNick);
121 return user->encodeString(string);
122 return encodeString(string);
125 void CoreNetwork::connectToIrc(bool reconnecting) {
126 if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
127 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
128 if(unlimitedReconnectRetries())
129 _autoReconnectCount = -1;
131 _autoReconnectCount = autoReconnectRetries();
133 if(serverList().isEmpty()) {
134 qWarning() << "Server list empty, ignoring connect request!";
137 CoreIdentity *identity = identityPtr();
139 qWarning() << "Invalid identity configures, ignoring connect request!";
143 // cleaning up old quit reason
146 // use a random server?
147 if(useRandomServer()) {
148 _lastUsedServerIndex = qrand() % serverList().size();
149 } else if(_previousConnectionAttemptFailed) {
150 // cycle to next server if previous connection attempt failed
151 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
152 if(++_lastUsedServerIndex >= serverList().size()) {
153 _lastUsedServerIndex = 0;
156 _previousConnectionAttemptFailed = false;
158 Server server = usedServer();
159 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
160 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
162 if(server.useProxy) {
163 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
164 socket.setProxy(proxy);
166 socket.setProxy(QNetworkProxy::NoProxy);
170 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
172 CoreIdentity *identity = identityPtr();
174 socket.setLocalCertificate(identity->sslCert());
175 socket.setPrivateKey(identity->sslKey());
177 socket.connectToHostEncrypted(server.host, server.port);
179 socket.connectToHost(server.host, server.port);
182 socket.connectToHost(server.host, server.port);
186 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) {
187 _quitRequested = requested; // see socketDisconnected();
189 _autoReconnectTimer.stop();
190 _autoReconnectCount = 0; // prohibiting auto reconnect
192 disablePingTimeout();
198 awayMsg = me_->awayMessage();
199 Core::setAwayMessage(userId(), networkId(), awayMsg);
200 Core::setUserModes(userId(), networkId(), me_->userModes());
203 if(reason.isEmpty() && identityPtr())
204 _quitReason = identityPtr()->quitReason();
206 _quitReason = reason;
208 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
209 switch(socket.state()) {
210 case QAbstractSocket::ConnectedState:
211 userInputHandler()->issueQuit(_quitReason);
212 if(requested || withReconnect) {
213 // the irc server has 10 seconds to close the socket
214 _socketCloseTimer.start(10000);
219 socketDisconnected();
223 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
224 userInputHandler()->handleUserInput(buf, msg);
227 void CoreNetwork::putRawLine(QByteArray s) {
234 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
237 if(!prefix.isEmpty())
238 msg += ":" + prefix + " ";
239 msg += cmd.toUpper().toAscii();
241 for(int i = 0; i < params.size() - 1; i++) {
242 msg += " " + params[i];
244 if(!params.isEmpty())
245 msg += " :" + params.last();
250 void CoreNetwork::setChannelJoined(const QString &channel) {
251 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
253 Core::setChannelPersistent(userId(), networkId(), channel, true);
254 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
257 void CoreNetwork::setChannelParted(const QString &channel) {
258 removeChannelKey(channel);
259 _autoWhoQueue.removeAll(channel.toLower());
260 _autoWhoPending.remove(channel.toLower());
262 Core::setChannelPersistent(userId(), networkId(), channel, false);
265 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
267 removeChannelKey(channel);
269 _channelKeys[channel.toLower()] = key;
273 void CoreNetwork::removeChannelKey(const QString &channel) {
274 _channelKeys.remove(channel.toLower());
277 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
278 QString chan = channel.toLower();
279 if(_autoWhoPending.value(chan, 0) <= 0)
281 if(--_autoWhoPending[chan] <= 0)
282 _autoWhoPending.remove(chan);
286 void CoreNetwork::setMyNick(const QString &mynick) {
287 Network::setMyNick(mynick);
288 if(connectionState() == Network::Initializing)
289 networkInitialized();
292 void CoreNetwork::socketHasData() {
293 while(socket.canReadLine()) {
294 QByteArray s = socket.readLine().trimmed();
295 ircServerHandler()->handleServerMsg(s);
299 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
300 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
303 _previousConnectionAttemptFailed = true;
304 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
305 emit connectionError(socket.errorString());
306 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
307 emitConnectionError(socket.errorString());
308 if(socket.state() < QAbstractSocket::ConnectedState) {
309 socketDisconnected();
313 void CoreNetwork::socketInitialized() {
314 Server server = usedServer();
316 if(server.useSsl && !socket.isEncrypted())
320 CoreIdentity *identity = identityPtr();
322 qCritical() << "Identity invalid!";
327 // TokenBucket to avoid sending too much at once
328 _messagesPerSecond = 1;
330 _tokenBucket = 5; // init with a full bucket
331 _tokenBucketTimer.start(_messagesPerSecond * 1000);
333 if(!server.password.isEmpty()) {
334 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
337 if(identity->nicks().isEmpty()) {
339 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
341 nick = identity->nicks()[0];
343 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
344 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
347 void CoreNetwork::socketDisconnected() {
348 disablePingTimeout();
350 _autoWhoCycleTimer.stop();
351 _autoWhoTimer.stop();
352 _autoWhoQueue.clear();
353 _autoWhoPending.clear();
355 _socketCloseTimer.stop();
357 _tokenBucketTimer.stop();
361 foreach(QString channel, me_->channels())
362 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
366 emit disconnected(networkId());
368 setConnectionState(Network::Disconnected);
369 Core::setNetworkConnected(userId(), networkId(), false);
370 } else if(_autoReconnectCount != 0) {
371 setConnectionState(Network::Reconnecting);
372 if(_autoReconnectCount == autoReconnectRetries())
373 doAutoReconnect(); // first try is immediate
375 _autoReconnectTimer.start();
379 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
380 Network::ConnectionState state;
381 switch(socketState) {
382 case QAbstractSocket::UnconnectedState:
383 state = Network::Disconnected;
385 case QAbstractSocket::HostLookupState:
386 case QAbstractSocket::ConnectingState:
387 state = Network::Connecting;
389 case QAbstractSocket::ConnectedState:
390 state = Network::Initializing;
392 case QAbstractSocket::ClosingState:
393 state = Network::Disconnecting;
396 state = Network::Disconnected;
398 setConnectionState(state);
401 void CoreNetwork::networkInitialized() {
402 setConnectionState(Network::Initialized);
404 _quitRequested = false;
406 if(useAutoReconnect()) {
408 _autoReconnectCount = autoReconnectRetries();
411 // restore away state
412 QString awayMsg = Core::awayMessage(userId(), networkId());
413 if(!awayMsg.isEmpty())
414 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
416 // restore old user modes if server default mode is set.
419 if(!me_->userModes().isEmpty()) {
422 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
423 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
431 if(_autoWhoEnabled) {
432 _autoWhoCycleTimer.start();
433 _autoWhoTimer.start();
434 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
437 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
438 Core::setNetworkConnected(userId(), networkId(), true);
441 void CoreNetwork::sendPerform() {
442 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
445 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
446 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
450 foreach(QString line, perform()) {
451 if(!line.isEmpty()) userInput(statusBuf, line);
454 // rejoin channels we've been in
455 if(rejoinChannels()) {
456 QStringList channels, keys;
457 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
458 QString key = channelKey(chan);
460 channels.prepend(chan);
463 channels.append(chan);
466 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
467 if(!joinString.isEmpty())
468 userInputHandler()->handleJoin(statusBuf, joinString);
472 void CoreNetwork::restoreUserModes() {
476 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
477 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
480 QString addModes = Core::userModes(userId(), networkId());
481 QString currentModes = me_->userModes();
483 removeModes = currentModes;
484 removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
485 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
487 removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
488 addModes = QString("%1 +%2").arg(me_->nick(), addModes);
489 userInputHandler()->handleMode(BufferInfo(), removeModes);
490 userInputHandler()->handleMode(BufferInfo(), addModes);
493 void CoreNetwork::setUseAutoReconnect(bool use) {
494 Network::setUseAutoReconnect(use);
496 _autoReconnectTimer.stop();
499 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
500 Network::setAutoReconnectInterval(interval);
501 _autoReconnectTimer.setInterval(interval * 1000);
504 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
505 Network::setAutoReconnectRetries(retries);
506 if(_autoReconnectCount != 0) {
507 if(unlimitedReconnectRetries())
508 _autoReconnectCount = -1;
510 _autoReconnectCount = autoReconnectRetries();
514 void CoreNetwork::doAutoReconnect() {
515 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
516 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
519 if(_autoReconnectCount > 0)
520 _autoReconnectCount--;
524 void CoreNetwork::sendPing() {
525 uint now = QDateTime::currentDateTime().toTime_t();
526 if(_lastPingTime != 0 && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
527 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
528 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
529 // and unable to even handle a ping answer. So we ignore those misses.
530 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingTimer.interval() / 1000), true /* withReconnect */);
533 userInputHandler()->handlePing(BufferInfo(), QString());
537 void CoreNetwork::enablePingTimeout() {
542 void CoreNetwork::disablePingTimeout() {
547 void CoreNetwork::sendAutoWho() {
548 // Don't send autowho if there are still some pending
549 if(_autoWhoPending.count())
552 while(!_autoWhoQueue.isEmpty()) {
553 QString chan = _autoWhoQueue.takeFirst();
554 IrcChannel *ircchan = ircChannel(chan);
555 if(!ircchan) continue;
556 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
557 _autoWhoPending[chan]++;
558 putRawLine("WHO " + serverEncode(chan));
559 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
560 // Timer was stopped, means a new cycle is due immediately
561 _autoWhoCycleTimer.start();
568 void CoreNetwork::startAutoWhoCycle() {
569 if(!_autoWhoQueue.isEmpty()) {
570 _autoWhoCycleTimer.stop();
573 _autoWhoQueue = channels();
577 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
579 socket.ignoreSslErrors();
580 // TODO errorhandling
584 void CoreNetwork::fillBucketAndProcessQueue() {
585 if(_tokenBucket < _burstSize) {
589 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
590 writeToSocket(_msgQueue.takeFirst());
594 void CoreNetwork::writeToSocket(const QByteArray &data) {
596 socket.write("\r\n");
600 Network::Server CoreNetwork::usedServer() const {
601 if(_lastUsedServerIndex < serverList().count())
602 return serverList()[_lastUsedServerIndex];
604 if(!serverList().isEmpty())
605 return serverList()[0];
607 return Network::Server();
610 void CoreNetwork::requestConnect() const {
611 if(connectionState() != Disconnected) {
612 qWarning() << "Requesting connect while already being connected!";
615 Network::requestConnect();
618 void CoreNetwork::requestDisconnect() const {
619 if(connectionState() == Disconnected) {
620 qWarning() << "Requesting disconnect while not being connected!";
623 userInputHandler()->handleQuit(BufferInfo(), QString());
626 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
627 Network::Server currentServer = usedServer();
628 setNetworkInfo(info);
629 Core::updateNetwork(coreSession()->user(), info);
631 // the order of the servers might have changed,
632 // so we try to find the previously used server
633 _lastUsedServerIndex = 0;
634 for(int i = 0; i < serverList().count(); i++) {
635 Network::Server server = serverList()[i];
636 if(server.host == currentServer.host && server.port == currentServer.port) {
637 _lastUsedServerIndex = i;