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") : reason));
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 _autoWhoInProgress.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 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
280 _autoWhoInProgress[channel.toLower()]--;
284 void CoreNetwork::setMyNick(const QString &mynick) {
285 Network::setMyNick(mynick);
286 if(connectionState() == Network::Initializing)
287 networkInitialized();
290 void CoreNetwork::socketHasData() {
291 while(socket.canReadLine()) {
292 QByteArray s = socket.readLine().trimmed();
293 ircServerHandler()->handleServerMsg(s);
297 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
298 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
301 _previousConnectionAttemptFailed = true;
302 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
303 emit connectionError(socket.errorString());
304 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
305 emitConnectionError(socket.errorString());
306 if(socket.state() < QAbstractSocket::ConnectedState) {
307 socketDisconnected();
311 void CoreNetwork::socketInitialized() {
312 Server server = usedServer();
314 if(server.useSsl && !socket.isEncrypted())
318 CoreIdentity *identity = identityPtr();
320 qCritical() << "Identity invalid!";
325 // TokenBucket to avoid sending too much at once
326 _messagesPerSecond = 1;
328 _tokenBucket = 5; // init with a full bucket
329 _tokenBucketTimer.start(_messagesPerSecond * 1000);
331 if(!server.password.isEmpty()) {
332 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
334 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
335 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
338 void CoreNetwork::socketDisconnected() {
339 disablePingTimeout();
341 _autoWhoCycleTimer.stop();
342 _autoWhoTimer.stop();
343 _autoWhoQueue.clear();
344 _autoWhoInProgress.clear();
346 _socketCloseTimer.stop();
348 _tokenBucketTimer.stop();
352 foreach(QString channel, me_->channels())
353 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
357 emit disconnected(networkId());
359 setConnectionState(Network::Disconnected);
360 Core::setNetworkConnected(userId(), networkId(), false);
361 } else if(_autoReconnectCount != 0) {
362 setConnectionState(Network::Reconnecting);
363 if(_autoReconnectCount == autoReconnectRetries())
364 doAutoReconnect(); // first try is immediate
366 _autoReconnectTimer.start();
370 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
371 Network::ConnectionState state;
372 switch(socketState) {
373 case QAbstractSocket::UnconnectedState:
374 state = Network::Disconnected;
376 case QAbstractSocket::HostLookupState:
377 case QAbstractSocket::ConnectingState:
378 state = Network::Connecting;
380 case QAbstractSocket::ConnectedState:
381 state = Network::Initializing;
383 case QAbstractSocket::ClosingState:
384 state = Network::Disconnecting;
387 state = Network::Disconnected;
389 setConnectionState(state);
392 void CoreNetwork::networkInitialized() {
393 setConnectionState(Network::Initialized);
395 _quitRequested = false;
397 if(useAutoReconnect()) {
399 _autoReconnectCount = autoReconnectRetries();
402 // restore away state
403 QString awayMsg = Core::awayMessage(userId(), networkId());
404 if(!awayMsg.isEmpty())
405 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
407 // restore old user modes if server default mode is set.
410 if(!me_->userModes().isEmpty()) {
413 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
414 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
422 if(_autoWhoEnabled) {
423 _autoWhoCycleTimer.start();
424 _autoWhoTimer.start();
425 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
428 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
429 Core::setNetworkConnected(userId(), networkId(), true);
432 void CoreNetwork::sendPerform() {
433 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
436 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
437 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
441 foreach(QString line, perform()) {
442 if(!line.isEmpty()) userInput(statusBuf, line);
445 // rejoin channels we've been in
446 if(rejoinChannels()) {
447 QStringList channels, keys;
448 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
449 QString key = channelKey(chan);
451 channels.prepend(chan);
454 channels.append(chan);
457 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
458 if(!joinString.isEmpty())
459 userInputHandler()->handleJoin(statusBuf, joinString);
463 void CoreNetwork::restoreUserModes() {
467 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
468 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
471 QString addModes = Core::userModes(userId(), networkId());
472 QString currentModes = me_->userModes();
474 removeModes = currentModes;
475 removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
476 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
478 removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
479 addModes = QString("%1 +%2").arg(me_->nick(), addModes);
480 userInputHandler()->handleMode(BufferInfo(), removeModes);
481 userInputHandler()->handleMode(BufferInfo(), addModes);
484 void CoreNetwork::setUseAutoReconnect(bool use) {
485 Network::setUseAutoReconnect(use);
487 _autoReconnectTimer.stop();
490 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
491 Network::setAutoReconnectInterval(interval);
492 _autoReconnectTimer.setInterval(interval * 1000);
495 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
496 Network::setAutoReconnectRetries(retries);
497 if(_autoReconnectCount != 0) {
498 if(unlimitedReconnectRetries())
499 _autoReconnectCount = -1;
501 _autoReconnectCount = autoReconnectRetries();
505 void CoreNetwork::doAutoReconnect() {
506 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
507 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
510 if(_autoReconnectCount > 0)
511 _autoReconnectCount--;
515 void CoreNetwork::sendPing() {
516 uint now = QDateTime::currentDateTime().toTime_t();
517 if(_lastPingTime != 0 && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
518 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
519 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
520 // and unable to even handle a ping answer. So we ignore those misses.
521 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingTimer.interval() / 1000), true /* withReconnect */);
524 userInputHandler()->handlePing(BufferInfo(), QString());
528 void CoreNetwork::enablePingTimeout() {
533 void CoreNetwork::disablePingTimeout() {
538 void CoreNetwork::sendAutoWho() {
539 while(!_autoWhoQueue.isEmpty()) {
540 QString chan = _autoWhoQueue.takeFirst();
541 IrcChannel *ircchan = ircChannel(chan);
542 if(!ircchan) continue;
543 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
544 _autoWhoInProgress[chan]++;
545 putRawLine("WHO " + serverEncode(chan));
546 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
547 // Timer was stopped, means a new cycle is due immediately
548 _autoWhoCycleTimer.start();
555 void CoreNetwork::startAutoWhoCycle() {
556 if(!_autoWhoQueue.isEmpty()) {
557 _autoWhoCycleTimer.stop();
560 _autoWhoQueue = channels();
564 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
566 socket.ignoreSslErrors();
567 // TODO errorhandling
571 void CoreNetwork::fillBucketAndProcessQueue() {
572 if(_tokenBucket < _burstSize) {
576 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
577 writeToSocket(_msgQueue.takeFirst());
581 void CoreNetwork::writeToSocket(const QByteArray &data) {
583 socket.write("\r\n");
587 Network::Server CoreNetwork::usedServer() const {
588 if(_lastUsedServerIndex < serverList().count())
589 return serverList()[_lastUsedServerIndex];
591 if(!serverList().isEmpty())
592 return serverList()[0];
594 return Network::Server();
597 void CoreNetwork::requestConnect() const {
598 if(connectionState() != Disconnected) {
599 qWarning() << "Requesting connect while already being connected!";
602 Network::requestConnect();
605 void CoreNetwork::requestDisconnect() const {
606 if(connectionState() == Disconnected) {
607 qWarning() << "Requesting disconnect while not being connected!";
610 userInputHandler()->handleQuit(BufferInfo(), QString());
613 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
614 Network::Server currentServer = usedServer();
615 setNetworkInfo(info);
616 Core::updateNetwork(coreSession()->user(), info);
618 // the order of the servers might have changed,
619 // so we try to find the previously used server
620 _lastUsedServerIndex = 0;
621 for(int i = 0; i < serverList().count(); i++) {
622 Network::Server server = serverList()[i];
623 if(server.host == currentServer.host && server.port == currentServer.port) {
624 _lastUsedServerIndex = i;