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),
47 // TODO make autowho configurable (possibly per-network)
48 _autoWhoEnabled(true),
50 _autoWhoNickLimit(0), // unlimited
53 _autoReconnectTimer.setSingleShot(true);
54 _socketCloseTimer.setSingleShot(true);
55 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
57 _pingTimer.setInterval(30000);
58 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
60 _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
61 _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
63 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
64 foreach(QString chan, channels.keys()) {
65 _channelKeys[chan.toLower()] = channels[chan];
68 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
69 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
70 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
71 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
72 connect(this, SIGNAL(connectRequested()), this, SLOT(connectToIrc()));
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();
200 awayMsg = me_->awayMessage();
201 Core::setAwayMessage(userId(), networkId(), awayMsg);
202 Core::setUserModes(userId(), networkId(), me_->userModes());
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());
279 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
280 QString chan = channel.toLower();
281 if(_autoWhoPending.value(chan, 0) <= 0)
283 if(--_autoWhoPending[chan] <= 0)
284 _autoWhoPending.remove(chan);
288 void CoreNetwork::setMyNick(const QString &mynick) {
289 Network::setMyNick(mynick);
290 if(connectionState() == Network::Initializing)
291 networkInitialized();
294 void CoreNetwork::socketHasData() {
295 while(socket.canReadLine()) {
296 QByteArray s = socket.readLine().trimmed();
297 ircServerHandler()->handleServerMsg(s);
301 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
302 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
305 _previousConnectionAttemptFailed = true;
306 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
307 emit connectionError(socket.errorString());
308 displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
309 emitConnectionError(socket.errorString());
310 if(socket.state() < QAbstractSocket::ConnectedState) {
311 socketDisconnected();
315 void CoreNetwork::socketInitialized() {
316 Server server = usedServer();
318 if(server.useSsl && !socket.isEncrypted())
322 CoreIdentity *identity = identityPtr();
324 qCritical() << "Identity invalid!";
329 // TokenBucket to avoid sending too much at once
330 _messagesPerSecond = 1;
332 _tokenBucket = 5; // init with a full bucket
333 _tokenBucketTimer.start(_messagesPerSecond * 1000);
335 if(!server.password.isEmpty()) {
336 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
339 if(identity->nicks().isEmpty()) {
341 qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
343 nick = identity->nicks()[0];
345 putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
346 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
349 void CoreNetwork::socketDisconnected() {
350 disablePingTimeout();
352 _autoWhoCycleTimer.stop();
353 _autoWhoTimer.stop();
354 _autoWhoQueue.clear();
355 _autoWhoPending.clear();
357 _socketCloseTimer.stop();
359 _tokenBucketTimer.stop();
363 foreach(QString channel, me_->channels())
364 displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
368 emit disconnected(networkId());
370 setConnectionState(Network::Disconnected);
371 Core::setNetworkConnected(userId(), networkId(), false);
372 } else if(_autoReconnectCount != 0) {
373 setConnectionState(Network::Reconnecting);
374 if(_autoReconnectCount == autoReconnectRetries())
375 doAutoReconnect(); // first try is immediate
377 _autoReconnectTimer.start();
381 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
382 Network::ConnectionState state;
383 switch(socketState) {
384 case QAbstractSocket::UnconnectedState:
385 state = Network::Disconnected;
387 case QAbstractSocket::HostLookupState:
388 case QAbstractSocket::ConnectingState:
389 state = Network::Connecting;
391 case QAbstractSocket::ConnectedState:
392 state = Network::Initializing;
394 case QAbstractSocket::ClosingState:
395 state = Network::Disconnecting;
398 state = Network::Disconnected;
400 setConnectionState(state);
403 void CoreNetwork::networkInitialized() {
404 setConnectionState(Network::Initialized);
406 _quitRequested = false;
408 if(useAutoReconnect()) {
410 _autoReconnectCount = autoReconnectRetries();
413 // restore away state
414 QString awayMsg = Core::awayMessage(userId(), networkId());
415 if(!awayMsg.isEmpty())
416 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
418 // restore old user modes if server default mode is set.
421 if(!me_->userModes().isEmpty()) {
424 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
425 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
433 if(_autoWhoEnabled) {
434 _autoWhoCycleTimer.start();
435 _autoWhoTimer.start();
436 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
439 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
440 Core::setNetworkConnected(userId(), networkId(), true);
443 void CoreNetwork::sendPerform() {
444 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
447 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
448 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
452 foreach(QString line, perform()) {
453 if(!line.isEmpty()) userInput(statusBuf, line);
456 // rejoin channels we've been in
457 if(rejoinChannels()) {
458 QStringList channels, keys;
459 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
460 QString key = channelKey(chan);
462 channels.prepend(chan);
465 channels.append(chan);
468 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
469 if(!joinString.isEmpty())
470 userInputHandler()->handleJoin(statusBuf, joinString);
474 void CoreNetwork::restoreUserModes() {
478 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
479 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
482 QString addModes = Core::userModes(userId(), networkId());
483 QString currentModes = me_->userModes();
485 removeModes = currentModes;
486 removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
487 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
489 removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
490 addModes = QString("%1 +%2").arg(me_->nick(), addModes);
491 userInputHandler()->handleMode(BufferInfo(), removeModes);
492 userInputHandler()->handleMode(BufferInfo(), addModes);
495 void CoreNetwork::setUseAutoReconnect(bool use) {
496 Network::setUseAutoReconnect(use);
498 _autoReconnectTimer.stop();
501 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
502 Network::setAutoReconnectInterval(interval);
503 _autoReconnectTimer.setInterval(interval * 1000);
506 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
507 Network::setAutoReconnectRetries(retries);
508 if(_autoReconnectCount != 0) {
509 if(unlimitedReconnectRetries())
510 _autoReconnectCount = -1;
512 _autoReconnectCount = autoReconnectRetries();
516 void CoreNetwork::doAutoReconnect() {
517 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
518 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
521 if(_autoReconnectCount > 0)
522 _autoReconnectCount--;
526 void CoreNetwork::sendPing() {
527 uint now = QDateTime::currentDateTime().toTime_t();
528 if(_pingCount >= _maxPingCount && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
529 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
530 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
531 // and unable to even handle a ping answer. So we ignore those misses.
532 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_maxPingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
536 userInputHandler()->handlePing(BufferInfo(), QString());
540 void CoreNetwork::enablePingTimeout() {
545 void CoreNetwork::disablePingTimeout() {
550 void CoreNetwork::sendAutoWho() {
551 // Don't send autowho if there are still some pending
552 if(_autoWhoPending.count())
555 while(!_autoWhoQueue.isEmpty()) {
556 QString chan = _autoWhoQueue.takeFirst();
557 IrcChannel *ircchan = ircChannel(chan);
558 if(!ircchan) continue;
559 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
560 _autoWhoPending[chan]++;
561 putRawLine("WHO " + serverEncode(chan));
562 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
563 // Timer was stopped, means a new cycle is due immediately
564 _autoWhoCycleTimer.start();
571 void CoreNetwork::startAutoWhoCycle() {
572 if(!_autoWhoQueue.isEmpty()) {
573 _autoWhoCycleTimer.stop();
576 _autoWhoQueue = channels();
580 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
582 socket.ignoreSslErrors();
583 // TODO errorhandling
587 void CoreNetwork::fillBucketAndProcessQueue() {
588 if(_tokenBucket < _burstSize) {
592 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
593 writeToSocket(_msgQueue.takeFirst());
597 void CoreNetwork::writeToSocket(const QByteArray &data) {
599 socket.write("\r\n");
603 Network::Server CoreNetwork::usedServer() const {
604 if(_lastUsedServerIndex < serverList().count())
605 return serverList()[_lastUsedServerIndex];
607 if(!serverList().isEmpty())
608 return serverList()[0];
610 return Network::Server();
613 void CoreNetwork::requestConnect() const {
614 if(connectionState() != Disconnected) {
615 qWarning() << "Requesting connect while already being connected!";
618 Network::requestConnect();
621 void CoreNetwork::requestDisconnect() const {
622 if(connectionState() == Disconnected) {
623 qWarning() << "Requesting disconnect while not being connected!";
626 userInputHandler()->handleQuit(BufferInfo(), QString());
629 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
630 Network::Server currentServer = usedServer();
631 setNetworkInfo(info);
632 Core::updateNetwork(coreSession()->user(), info);
634 // the order of the servers might have changed,
635 // so we try to find the previously used server
636 _lastUsedServerIndex = 0;
637 for(int i = 0; i < serverList().count(); i++) {
638 Network::Server server = serverList()[i];
639 if(server.host == currentServer.host && server.port == currentServer.port) {
640 _lastUsedServerIndex = i;