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 emit 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)));
336 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
337 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
340 void CoreNetwork::socketDisconnected() {
341 disablePingTimeout();
343 _autoWhoCycleTimer.stop();
344 _autoWhoTimer.stop();
345 _autoWhoQueue.clear();
346 _autoWhoPending.clear();
348 _socketCloseTimer.stop();
350 _tokenBucketTimer.stop();
354 foreach(QString channel, me_->channels())
355 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
359 emit disconnected(networkId());
361 setConnectionState(Network::Disconnected);
362 Core::setNetworkConnected(userId(), networkId(), false);
363 } else if(_autoReconnectCount != 0) {
364 setConnectionState(Network::Reconnecting);
365 if(_autoReconnectCount == autoReconnectRetries())
366 doAutoReconnect(); // first try is immediate
368 _autoReconnectTimer.start();
372 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
373 Network::ConnectionState state;
374 switch(socketState) {
375 case QAbstractSocket::UnconnectedState:
376 state = Network::Disconnected;
378 case QAbstractSocket::HostLookupState:
379 case QAbstractSocket::ConnectingState:
380 state = Network::Connecting;
382 case QAbstractSocket::ConnectedState:
383 state = Network::Initializing;
385 case QAbstractSocket::ClosingState:
386 state = Network::Disconnecting;
389 state = Network::Disconnected;
391 setConnectionState(state);
394 void CoreNetwork::networkInitialized() {
395 setConnectionState(Network::Initialized);
397 _quitRequested = false;
399 if(useAutoReconnect()) {
401 _autoReconnectCount = autoReconnectRetries();
404 // restore away state
405 QString awayMsg = Core::awayMessage(userId(), networkId());
406 if(!awayMsg.isEmpty())
407 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
409 // restore old user modes if server default mode is set.
412 if(!me_->userModes().isEmpty()) {
415 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
416 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
424 if(_autoWhoEnabled) {
425 _autoWhoCycleTimer.start();
426 _autoWhoTimer.start();
427 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
430 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
431 Core::setNetworkConnected(userId(), networkId(), true);
434 void CoreNetwork::sendPerform() {
435 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
438 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
439 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
443 foreach(QString line, perform()) {
444 if(!line.isEmpty()) userInput(statusBuf, line);
447 // rejoin channels we've been in
448 if(rejoinChannels()) {
449 QStringList channels, keys;
450 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
451 QString key = channelKey(chan);
453 channels.prepend(chan);
456 channels.append(chan);
459 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
460 if(!joinString.isEmpty())
461 userInputHandler()->handleJoin(statusBuf, joinString);
465 void CoreNetwork::restoreUserModes() {
469 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
470 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
473 QString addModes = Core::userModes(userId(), networkId());
474 QString currentModes = me_->userModes();
476 removeModes = currentModes;
477 removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
478 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
480 removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
481 addModes = QString("%1 +%2").arg(me_->nick(), addModes);
482 userInputHandler()->handleMode(BufferInfo(), removeModes);
483 userInputHandler()->handleMode(BufferInfo(), addModes);
486 void CoreNetwork::setUseAutoReconnect(bool use) {
487 Network::setUseAutoReconnect(use);
489 _autoReconnectTimer.stop();
492 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
493 Network::setAutoReconnectInterval(interval);
494 _autoReconnectTimer.setInterval(interval * 1000);
497 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
498 Network::setAutoReconnectRetries(retries);
499 if(_autoReconnectCount != 0) {
500 if(unlimitedReconnectRetries())
501 _autoReconnectCount = -1;
503 _autoReconnectCount = autoReconnectRetries();
507 void CoreNetwork::doAutoReconnect() {
508 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
509 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
512 if(_autoReconnectCount > 0)
513 _autoReconnectCount--;
517 void CoreNetwork::sendPing() {
518 uint now = QDateTime::currentDateTime().toTime_t();
519 if(_lastPingTime != 0 && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
520 // the second check compares the actual elapsed time since the last ping and the pingTimer interval
521 // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
522 // and unable to even handle a ping answer. So we ignore those misses.
523 disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingTimer.interval() / 1000), true /* withReconnect */);
526 userInputHandler()->handlePing(BufferInfo(), QString());
530 void CoreNetwork::enablePingTimeout() {
535 void CoreNetwork::disablePingTimeout() {
540 void CoreNetwork::sendAutoWho() {
541 // Don't send autowho if there are still some pending
542 if(_autoWhoPending.count())
545 while(!_autoWhoQueue.isEmpty()) {
546 QString chan = _autoWhoQueue.takeFirst();
547 IrcChannel *ircchan = ircChannel(chan);
548 if(!ircchan) continue;
549 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
550 _autoWhoPending[chan]++;
551 putRawLine("WHO " + serverEncode(chan));
552 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
553 // Timer was stopped, means a new cycle is due immediately
554 _autoWhoCycleTimer.start();
561 void CoreNetwork::startAutoWhoCycle() {
562 if(!_autoWhoQueue.isEmpty()) {
563 _autoWhoCycleTimer.stop();
566 _autoWhoQueue = channels();
570 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
572 socket.ignoreSslErrors();
573 // TODO errorhandling
577 void CoreNetwork::fillBucketAndProcessQueue() {
578 if(_tokenBucket < _burstSize) {
582 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
583 writeToSocket(_msgQueue.takeFirst());
587 void CoreNetwork::writeToSocket(const QByteArray &data) {
589 socket.write("\r\n");
593 Network::Server CoreNetwork::usedServer() const {
594 if(_lastUsedServerIndex < serverList().count())
595 return serverList()[_lastUsedServerIndex];
597 if(!serverList().isEmpty())
598 return serverList()[0];
600 return Network::Server();
603 void CoreNetwork::requestConnect() const {
604 if(connectionState() != Disconnected) {
605 qWarning() << "Requesting connect while already being connected!";
608 Network::requestConnect();
611 void CoreNetwork::requestDisconnect() const {
612 if(connectionState() == Disconnected) {
613 qWarning() << "Requesting disconnect while not being connected!";
616 userInputHandler()->handleQuit(BufferInfo(), QString());
619 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
620 Network::Server currentServer = usedServer();
621 setNetworkInfo(info);
622 Core::updateNetwork(coreSession()->user(), info);
624 // the order of the servers might have changed,
625 // so we try to find the previously used server
626 _lastUsedServerIndex = 0;
627 for(int i = 0; i < serverList().count(); i++) {
628 Network::Server server = serverList()[i];
629 if(server.host == currentServer.host && server.port == currentServer.port) {
630 _lastUsedServerIndex = i;