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) : QObject(network),
40 _connectionState(Network::Disconnected),
42 _coreSession(session),
43 _ircServerHandler(new IrcServerHandler(this)),
44 _userInputHandler(new UserInputHandler(this)),
45 _ctcpHandler(new CtcpHandler(this)),
46 _autoReconnectCount(0)
48 _autoReconnectTimer.setSingleShot(true);
50 _previousConnectionAttemptFailed = false;
51 _lastUsedServerlistIndex = 0;
53 // TODO make autowho configurable (possibly per-network)
54 _autoWhoEnabled = true;
55 _autoWhoInterval = 90;
56 _autoWhoNickLimit = 0; // unlimited
59 _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
60 _autoWhoTimer.setSingleShot(false);
61 _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
62 _autoWhoCycleTimer.setSingleShot(false);
64 // TokenBucket to avaid sending too much at once
65 _messagesPerSecond = 1;
67 _tokenBucket = 5; // init with a full bucket
69 _tokenBucketTimer.start(_messagesPerSecond * 1000);
70 _tokenBucketTimer.setSingleShot(false);
72 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
73 foreach(QString chan, channels.keys()) {
74 _channelKeys[chan.toLower()] = channels[chan];
77 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
78 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
79 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
80 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
82 connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
83 connect(network, SIGNAL(useAutoReconnectSet(bool)), this, SLOT(autoReconnectSettingsChanged()));
84 connect(network, SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(autoReconnectSettingsChanged()));
85 connect(network, SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(autoReconnectSettingsChanged()));
88 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketEncrypted()));
89 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
91 connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
93 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
94 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
95 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
96 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
98 connect(_ircServerHandler, SIGNAL(nickChanged(const QString &, const QString &)),
99 this, SLOT(nickChanged(const QString &, const QString &)));
101 network->proxy()->attachSignal(this, SIGNAL(sslErrors(const QVariant &)));
104 NetworkConnection::~NetworkConnection() {
105 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
106 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
107 delete _ircServerHandler;
108 delete _userInputHandler;
112 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
113 _connectionState = state;
114 network()->setConnectionState(state);
115 emit connectionStateChanged(state);
118 QString NetworkConnection::serverDecode(const QByteArray &string) const {
119 return network()->decodeServerString(string);
122 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
123 if(!bufferName.isEmpty()) {
124 IrcChannel *channel = network()->ircChannel(bufferName);
125 if(channel) return channel->decodeString(string);
127 return network()->decodeString(string);
130 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
131 IrcUser *user = network()->ircUser(userNick);
132 if(user) return user->decodeString(string);
133 return network()->decodeString(string);
136 QByteArray NetworkConnection::serverEncode(const QString &string) const {
137 return network()->encodeServerString(string);
140 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
141 if(!bufferName.isEmpty()) {
142 IrcChannel *channel = network()->ircChannel(bufferName);
143 if(channel) return channel->encodeString(string);
145 return network()->encodeString(string);
148 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
149 IrcUser *user = network()->ircUser(userNick);
150 if(user) return user->encodeString(string);
151 return network()->encodeString(string);
154 void NetworkConnection::autoReconnectSettingsChanged() {
155 if(!network()->useAutoReconnect()) {
156 _autoReconnectTimer.stop();
157 _autoReconnectCount = 0;
159 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
160 if(_autoReconnectCount != 0) {
161 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
162 else _autoReconnectCount = network()->autoReconnectRetries();
167 void NetworkConnection::connectToIrc(bool reconnecting) {
168 if(!reconnecting && network()->useAutoReconnect() && _autoReconnectCount == 0) {
169 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
170 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
171 else _autoReconnectCount = network()->autoReconnectRetries();
173 QVariantList serverList = network()->serverList();
174 Identity *identity = coreSession()->identity(network()->identity());
175 if(!serverList.count()) {
176 qWarning() << "Server list empty, ignoring connect request!";
180 qWarning() << "Invalid identity configures, ignoring connect request!";
183 // use a random server?
184 if(network()->useRandomServer()) {
185 _lastUsedServerlistIndex = qrand() % serverList.size();
186 } else if(_previousConnectionAttemptFailed) {
187 // cycle to next server if previous connection attempt failed
188 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
189 if(++_lastUsedServerlistIndex == serverList.size()) {
190 _lastUsedServerlistIndex = 0;
193 _previousConnectionAttemptFailed = false;
195 QString host = serverList[_lastUsedServerlistIndex].toMap()["Host"].toString();
196 quint16 port = serverList[_lastUsedServerlistIndex].toMap()["Port"].toUInt();
197 displayStatusMsg(tr("Connecting to %1:%2...").arg(host).arg(port));
198 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(host).arg(port));
199 socket.connectToHost(host, port);
202 void NetworkConnection::networkInitialized(const QString ¤tServer) {
203 if(currentServer.isEmpty()) return;
205 if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
206 _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
211 // now we are initialized
212 setConnectionState(Network::Initialized);
213 network()->setConnected(true);
214 emit connected(networkId());
216 if(_autoWhoEnabled) {
217 _autoWhoCycleTimer.start();
218 _autoWhoTimer.start();
219 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
223 void NetworkConnection::sendPerform() {
224 BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
226 if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
227 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
230 foreach(QString line, network()->perform()) {
231 if(!line.isEmpty()) userInput(statusBuf, line);
234 // rejoin channels we've been in
235 QStringList channels, keys;
236 foreach(QString chan, persistentChannels()) {
237 QString key = channelKey(chan);
239 channels.prepend(chan); keys.prepend(key);
241 channels.append(chan);
244 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
245 if(!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString);
248 void NetworkConnection::disconnectFromIrc(bool requested) {
249 _autoReconnectTimer.stop();
250 _autoReconnectCount = 0;
251 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
252 if(socket.state() < QAbstractSocket::ConnectedState) {
253 setConnectionState(Network::Disconnected);
254 socketDisconnected();
255 } else socket.disconnectFromHost();
258 emit quitRequested(networkId());
262 void NetworkConnection::socketHasData() {
263 while(socket.canReadLine()) {
264 QByteArray s = socket.readLine().trimmed();
265 ircServerHandler()->handleServerMsg(s);
269 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
270 _previousConnectionAttemptFailed = true;
271 qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
272 emit connectionError(socket.errorString());
273 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
274 network()->emitConnectionError(socket.errorString());
275 if(socket.state() < QAbstractSocket::ConnectedState) {
276 setConnectionState(Network::Disconnected);
277 socketDisconnected();
279 // mark last connection attempt as failed
281 //qDebug() << "exiting...";
285 #ifndef QT_NO_OPENSSL
287 void NetworkConnection::sslErrors(const QList<QSslError> &sslErrors) {
288 socket.ignoreSslErrors();
289 /* TODO errorhandling
291 QVariantList errnums;
292 foreach(QSslError err, errors) errnums << err.error();
293 errmsg["SslErrors"] = errnums;
294 errmsg["SslCert"] = socket.peerCertificate().toPem();
295 errmsg["PeerAddress"] = socket.peerAddress().toString();
296 errmsg["PeerPort"] = socket.peerPort();
297 errmsg["PeerName"] = socket.peerName();
298 emit sslErrors(errmsg);
303 void NetworkConnection::socketEncrypted() {
304 //qDebug() << "encrypted!";
308 #endif // QT_NO_OPENSSL
310 void NetworkConnection::socketConnected() {
315 if(!network()->serverList()[_lastUsedServerlistIndex].toMap()["UseSSL"].toBool()) {
319 //qDebug() << "starting handshake";
320 socket.startClientEncryption();
324 void NetworkConnection::socketInitialized() {
325 //emit connected(networkId()); initialize first!
326 Identity *identity = coreSession()->identity(network()->identity());
328 qWarning() << "Identity invalid!";
332 QString passwd = network()->serverList()[_lastUsedServerlistIndex].toMap()["Password"].toString();
333 if(!passwd.isEmpty()) {
334 putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
336 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0]))); // FIXME: try more nicks if error occurs
337 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
340 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
341 Network::ConnectionState state;
342 switch(socketState) {
343 case QAbstractSocket::UnconnectedState:
344 state = Network::Disconnected;
346 case QAbstractSocket::HostLookupState:
347 case QAbstractSocket::ConnectingState:
348 state = Network::Connecting;
350 case QAbstractSocket::ConnectedState:
351 state = Network::Initializing;
353 case QAbstractSocket::ClosingState:
354 state = Network::Disconnecting;
357 state = Network::Disconnected;
359 setConnectionState(state);
362 void NetworkConnection::socketDisconnected() {
363 _autoWhoCycleTimer.stop();
364 _autoWhoTimer.stop();
365 _autoWhoQueue.clear();
366 _autoWhoInProgress.clear();
368 network()->setConnected(false);
369 emit disconnected(networkId());
370 if(_autoReconnectCount != 0) {
371 setConnectionState(Network::Reconnecting);
372 if(_autoReconnectCount == network()->autoReconnectRetries()) doAutoReconnect(); // first try is immediate
373 else _autoReconnectTimer.start();
377 void NetworkConnection::doAutoReconnect() {
378 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
379 qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
382 if(_autoReconnectCount > 0) _autoReconnectCount--;
386 // FIXME switch to BufferId
387 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
388 userInputHandler()->handleUserInput(buf, msg);
391 void NetworkConnection::putRawLine(QByteArray s) {
392 if(_tokenBucket > 0) {
399 void NetworkConnection::writeToSocket(QByteArray s) {
405 void NetworkConnection::fillBucketAndProcessQueue() {
406 if(_tokenBucket < _burstSize) {
410 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
411 writeToSocket(_msgQueue.takeFirst());
415 void NetworkConnection::putCmd(const QString &cmd, const QVariantList ¶ms, const QByteArray &prefix) {
417 if(!prefix.isEmpty())
418 msg += ":" + prefix + " ";
419 msg += cmd.toUpper().toAscii();
421 for(int i = 0; i < params.size() - 1; i++) {
422 msg += " " + params[i].toByteArray();
424 if(!params.isEmpty())
425 msg += " :" + params.last().toByteArray();
430 void NetworkConnection::sendAutoWho() {
431 while(!_autoWhoQueue.isEmpty()) {
432 QString chan = _autoWhoQueue.takeFirst();
433 IrcChannel *ircchan = network()->ircChannel(chan);
434 if(!ircchan) continue;
435 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
436 _autoWhoInProgress.insert(chan);
437 putRawLine("WHO " + serverEncode(chan));
438 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
439 // Timer was stopped, means a new cycle is due immediately
440 _autoWhoCycleTimer.start();
447 void NetworkConnection::startAutoWhoCycle() {
448 if(!_autoWhoQueue.isEmpty()) {
449 _autoWhoCycleTimer.stop();
452 _autoWhoQueue = network()->channels();
455 bool NetworkConnection::setAutoWhoDone(const QString &channel) {
456 return _autoWhoInProgress.remove(channel);
459 void NetworkConnection::setChannelJoined(const QString &channel) {
460 emit channelJoined(networkId(), channel, _channelKeys[channel.toLower()]);
461 _autoWhoQueue.prepend(channel); // prepend so this new chan is the first to be checked
464 void NetworkConnection::setChannelParted(const QString &channel) {
465 removeChannelKey(channel);
466 _autoWhoQueue.removeAll(channel);
467 _autoWhoInProgress.remove(channel);
468 emit channelParted(networkId(), channel);
471 void NetworkConnection::addChannelKey(const QString &channel, const QString &key) {
473 removeChannelKey(channel);
475 _channelKeys[channel.toLower()] = key;
479 void NetworkConnection::removeChannelKey(const QString &channel) {
480 _channelKeys.remove(channel.toLower());
483 void NetworkConnection::nickChanged(const QString &newNick, const QString &oldNick) {
484 emit nickChanged(networkId(), newNick, oldNick);
487 /* Exception classes for message handling */
488 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
490 _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
493 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
495 _msg = QString("Unknown Command: ") + cmd + params.join(" ");