1 /***************************************************************************
2 * Copyright (C) 2005-08 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 ***************************************************************************/
20 #include "networkconnection.h"
22 #include <QMetaObject>
23 #include <QMetaMethod>
28 #include "coresession.h"
30 #include "ircchannel.h"
35 #include "ircserverhandler.h"
36 #include "userinputhandler.h"
37 #include "ctcphandler.h"
39 NetworkConnection::NetworkConnection(Network *network, CoreSession *session)
41 _connectionState(Network::Disconnected),
43 _coreSession(session),
44 _ircServerHandler(new IrcServerHandler(this)),
45 _userInputHandler(new UserInputHandler(this)),
46 _ctcpHandler(new CtcpHandler(this)),
47 _autoReconnectCount(0),
48 _quitRequested(false),
50 _previousConnectionAttemptFailed(false),
51 _lastUsedServerlistIndex(0),
53 // TODO make autowho configurable (possibly per-network)
54 _autoWhoEnabled(true),
56 _autoWhoNickLimit(0), // unlimited
59 // TokenBucket to avaid sending too much at once
60 _messagesPerSecond(1),
62 _tokenBucket(5) // init with a full bucket
64 _autoReconnectTimer.setSingleShot(true);
65 _socketCloseTimer.setSingleShot(true);
66 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
68 _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
69 _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
71 _tokenBucketTimer.start(_messagesPerSecond * 1000);
73 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
74 foreach(QString chan, channels.keys()) {
75 _channelKeys[chan.toLower()] = channels[chan];
78 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
79 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
80 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
81 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
83 connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
84 connect(network, SIGNAL(useAutoReconnectSet(bool)), this, SLOT(autoReconnectSettingsChanged()));
85 connect(network, SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(autoReconnectSettingsChanged()));
86 connect(network, SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(autoReconnectSettingsChanged()));
90 QFile certFile(quasselDir().absolutePath() + "/quasselClientCert.pem");
91 certFile.open(QIODevice::ReadOnly);
92 QSslCertificate cert(&certFile);
95 certFile.open(QIODevice::ReadOnly);
96 QSslKey key(&certFile, QSsl::Rsa);
99 if ( !cert.isNull() && cert.isValid() &&
101 socket.setLocalCertificate(cert);
102 socket.setPrivateKey(key);
106 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketEncrypted()));
107 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
109 connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
111 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
112 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
113 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
114 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
116 connect(_ircServerHandler, SIGNAL(nickChanged(const QString &, const QString &)),
117 this, SLOT(nickChanged(const QString &, const QString &)));
119 network->proxy()->attachSignal(this, SIGNAL(sslErrors(const QVariant &)));
122 NetworkConnection::~NetworkConnection() {
123 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
124 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
125 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
126 delete _ircServerHandler;
127 delete _userInputHandler;
131 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
132 _connectionState = state;
133 network()->setConnectionState(state);
134 emit connectionStateChanged(state);
137 QString NetworkConnection::serverDecode(const QByteArray &string) const {
138 return network()->decodeServerString(string);
141 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
142 if(!bufferName.isEmpty()) {
143 IrcChannel *channel = network()->ircChannel(bufferName);
144 if(channel) return channel->decodeString(string);
146 return network()->decodeString(string);
149 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
150 IrcUser *user = network()->ircUser(userNick);
151 if(user) return user->decodeString(string);
152 return network()->decodeString(string);
155 QByteArray NetworkConnection::serverEncode(const QString &string) const {
156 return network()->encodeServerString(string);
159 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
160 if(!bufferName.isEmpty()) {
161 IrcChannel *channel = network()->ircChannel(bufferName);
162 if(channel) return channel->encodeString(string);
164 return network()->encodeString(string);
167 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
168 IrcUser *user = network()->ircUser(userNick);
169 if(user) return user->encodeString(string);
170 return network()->encodeString(string);
173 void NetworkConnection::autoReconnectSettingsChanged() {
174 if(!network()->useAutoReconnect()) {
175 _autoReconnectTimer.stop();
176 _autoReconnectCount = 0;
178 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
179 if(_autoReconnectCount != 0) {
180 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
181 else _autoReconnectCount = network()->autoReconnectRetries();
186 void NetworkConnection::connectToIrc(bool reconnecting) {
187 if(!reconnecting && network()->useAutoReconnect() && _autoReconnectCount == 0) {
188 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
189 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
190 else _autoReconnectCount = network()->autoReconnectRetries();
192 QVariantList serverList = network()->serverList();
193 Identity *identity = coreSession()->identity(network()->identity());
194 if(!serverList.count()) {
195 qWarning() << "Server list empty, ignoring connect request!";
199 qWarning() << "Invalid identity configures, ignoring connect request!";
202 // use a random server?
203 if(network()->useRandomServer()) {
204 _lastUsedServerlistIndex = qrand() % serverList.size();
205 } else if(_previousConnectionAttemptFailed) {
206 // cycle to next server if previous connection attempt failed
207 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
208 if(++_lastUsedServerlistIndex == serverList.size()) {
209 _lastUsedServerlistIndex = 0;
212 _previousConnectionAttemptFailed = false;
214 QString host = serverList[_lastUsedServerlistIndex].toMap()["Host"].toString();
215 quint16 port = serverList[_lastUsedServerlistIndex].toMap()["Port"].toUInt();
216 displayStatusMsg(tr("Connecting to %1:%2...").arg(host).arg(port));
217 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(host).arg(port));
218 socket.connectToHost(host, port);
221 void NetworkConnection::networkInitialized(const QString ¤tServer) {
222 if(currentServer.isEmpty()) return;
224 if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
225 _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
230 // now we are initialized
231 setConnectionState(Network::Initialized);
232 network()->setConnected(true);
233 emit connected(networkId());
235 if(_autoWhoEnabled) {
236 _autoWhoCycleTimer.start();
237 _autoWhoTimer.start();
238 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
242 void NetworkConnection::sendPerform() {
243 BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
245 if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
246 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
249 foreach(QString line, network()->perform()) {
250 if(!line.isEmpty()) userInput(statusBuf, line);
253 // rejoin channels we've been in
254 QStringList channels, keys;
255 foreach(QString chan, persistentChannels()) {
256 QString key = channelKey(chan);
258 channels.prepend(chan); keys.prepend(key);
260 channels.append(chan);
263 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
264 if(!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString);
267 void NetworkConnection::disconnectFromIrc(bool requested) {
268 _autoReconnectTimer.stop();
269 _autoReconnectCount = 0;
270 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
271 if(socket.state() < QAbstractSocket::ConnectedState) {
272 setConnectionState(Network::Disconnected);
273 socketDisconnected();
275 _socketCloseTimer.start(10000); // the irc server has 10 seconds to close the socket
278 // this flag triggers quitRequested() once the socket is closed
279 // it is needed to determine whether or not the connection needs to be
280 // in the automatic session restore.
281 _quitRequested = requested;
284 void NetworkConnection::socketHasData() {
285 while(socket.canReadLine()) {
286 QByteArray s = socket.readLine().trimmed();
287 ircServerHandler()->handleServerMsg(s);
291 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
292 _previousConnectionAttemptFailed = true;
293 qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
294 emit connectionError(socket.errorString());
295 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
296 network()->emitConnectionError(socket.errorString());
297 if(socket.state() < QAbstractSocket::ConnectedState) {
298 setConnectionState(Network::Disconnected);
299 socketDisconnected();
301 // mark last connection attempt as failed
303 //qDebug() << "exiting...";
307 #ifndef QT_NO_OPENSSL
309 void NetworkConnection::sslErrors(const QList<QSslError> &sslErrors) {
311 socket.ignoreSslErrors();
312 /* TODO errorhandling
314 QVariantList errnums;
315 foreach(QSslError err, errors) errnums << err.error();
316 errmsg["SslErrors"] = errnums;
317 errmsg["SslCert"] = socket.peerCertificate().toPem();
318 errmsg["PeerAddress"] = socket.peerAddress().toString();
319 errmsg["PeerPort"] = socket.peerPort();
320 errmsg["PeerName"] = socket.peerName();
321 emit sslErrors(errmsg);
326 void NetworkConnection::socketEncrypted() {
327 //qDebug() << "encrypted!";
331 #endif // QT_NO_OPENSSL
333 void NetworkConnection::socketConnected() {
338 if(!network()->serverList()[_lastUsedServerlistIndex].toMap()["UseSSL"].toBool()) {
342 //qDebug() << "starting handshake";
343 socket.startClientEncryption();
347 void NetworkConnection::socketInitialized() {
348 //emit connected(networkId()); initialize first!
349 Identity *identity = coreSession()->identity(network()->identity());
351 qWarning() << "Identity invalid!";
355 QString passwd = network()->serverList()[_lastUsedServerlistIndex].toMap()["Password"].toString();
356 if(!passwd.isEmpty()) {
357 putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
359 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0]))); // FIXME: try more nicks if error occurs
360 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
363 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
364 Network::ConnectionState state;
365 switch(socketState) {
366 case QAbstractSocket::UnconnectedState:
367 state = Network::Disconnected;
369 case QAbstractSocket::HostLookupState:
370 case QAbstractSocket::ConnectingState:
371 state = Network::Connecting;
373 case QAbstractSocket::ConnectedState:
374 state = Network::Initializing;
376 case QAbstractSocket::ClosingState:
377 state = Network::Disconnecting;
380 state = Network::Disconnected;
382 setConnectionState(state);
385 void NetworkConnection::socketCloseTimeout() {
386 socket.disconnectFromHost();
389 void NetworkConnection::socketDisconnected() {
390 _autoWhoCycleTimer.stop();
391 _autoWhoTimer.stop();
392 _autoWhoQueue.clear();
393 _autoWhoInProgress.clear();
395 _socketCloseTimer.stop();
397 network()->setConnected(false);
398 emit disconnected(networkId());
399 if(_autoReconnectCount != 0) {
400 setConnectionState(Network::Reconnecting);
401 if(_autoReconnectCount == network()->autoReconnectRetries()) doAutoReconnect(); // first try is immediate
402 else _autoReconnectTimer.start();
403 } else if(_quitRequested) {
404 emit quitRequested(networkId());
408 void NetworkConnection::doAutoReconnect() {
409 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
410 qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
413 if(_autoReconnectCount > 0) _autoReconnectCount--;
417 // FIXME switch to BufferId
418 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
419 userInputHandler()->handleUserInput(buf, msg);
422 void NetworkConnection::putRawLine(QByteArray s) {
423 if(_tokenBucket > 0) {
430 void NetworkConnection::writeToSocket(QByteArray s) {
436 void NetworkConnection::fillBucketAndProcessQueue() {
437 if(_tokenBucket < _burstSize) {
441 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
442 writeToSocket(_msgQueue.takeFirst());
446 void NetworkConnection::putCmd(const QString &cmd, const QVariantList ¶ms, const QByteArray &prefix) {
448 if(!prefix.isEmpty())
449 msg += ":" + prefix + " ";
450 msg += cmd.toUpper().toAscii();
452 for(int i = 0; i < params.size() - 1; i++) {
453 msg += " " + params[i].toByteArray();
455 if(!params.isEmpty())
456 msg += " :" + params.last().toByteArray();
461 void NetworkConnection::sendAutoWho() {
462 while(!_autoWhoQueue.isEmpty()) {
463 QString chan = _autoWhoQueue.takeFirst();
464 IrcChannel *ircchan = network()->ircChannel(chan);
465 if(!ircchan) continue;
466 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
467 _autoWhoInProgress[chan]++;
468 putRawLine("WHO " + serverEncode(chan));
469 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
470 // Timer was stopped, means a new cycle is due immediately
471 _autoWhoCycleTimer.start();
478 void NetworkConnection::startAutoWhoCycle() {
479 if(!_autoWhoQueue.isEmpty()) {
480 _autoWhoCycleTimer.stop();
483 _autoWhoQueue = network()->channels();
486 bool NetworkConnection::setAutoWhoDone(const QString &channel) {
487 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0) return false;
488 _autoWhoInProgress[channel.toLower()]--;
492 void NetworkConnection::setChannelJoined(const QString &channel) {
493 emit channelJoined(networkId(), channel, _channelKeys[channel.toLower()]);
494 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
497 void NetworkConnection::setChannelParted(const QString &channel) {
498 removeChannelKey(channel);
499 _autoWhoQueue.removeAll(channel.toLower());
500 _autoWhoInProgress.remove(channel.toLower());
501 emit channelParted(networkId(), channel);
504 void NetworkConnection::addChannelKey(const QString &channel, const QString &key) {
506 removeChannelKey(channel);
508 _channelKeys[channel.toLower()] = key;
512 void NetworkConnection::removeChannelKey(const QString &channel) {
513 _channelKeys.remove(channel.toLower());
516 void NetworkConnection::nickChanged(const QString &newNick, const QString &oldNick) {
517 emit nickChanged(networkId(), newNick, oldNick);
520 /* Exception classes for message handling */
521 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
523 _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
526 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
528 _msg = QString("Unknown Command: ") + cmd + params.join(" ");