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 // should be 510 (2 bytes are added when writing to the socket)
70 // maxMsgSize is 510 minus the hostmask which will be added by the server
73 _tokenBucketTimer.start(_messagesPerSecond * 1000);
74 _tokenBucketTimer.setSingleShot(false);
76 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
77 foreach(QString chan, channels.keys()) {
78 _channelKeys[chan.toLower()] = channels[chan];
81 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
82 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
83 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
84 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
86 connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
87 connect(network, SIGNAL(useAutoReconnectSet(bool)), this, SLOT(autoReconnectSettingsChanged()));
88 connect(network, SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(autoReconnectSettingsChanged()));
89 connect(network, SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(autoReconnectSettingsChanged()));
92 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketEncrypted()));
93 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
95 connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
97 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
98 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
99 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
100 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
102 connect(_ircServerHandler, SIGNAL(nickChanged(const QString &, const QString &)),
103 this, SLOT(nickChanged(const QString &, const QString &)));
105 network->proxy()->attachSignal(this, SIGNAL(sslErrors(const QVariant &)));
108 NetworkConnection::~NetworkConnection() {
109 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
110 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
111 delete _ircServerHandler;
112 delete _userInputHandler;
116 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
117 _connectionState = state;
118 network()->setConnectionState(state);
119 emit connectionStateChanged(state);
122 QString NetworkConnection::serverDecode(const QByteArray &string) const {
123 return network()->decodeServerString(string);
126 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
127 if(!bufferName.isEmpty()) {
128 IrcChannel *channel = network()->ircChannel(bufferName);
129 if(channel) return channel->decodeString(string);
131 return network()->decodeString(string);
134 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
135 IrcUser *user = network()->ircUser(userNick);
136 if(user) return user->decodeString(string);
137 return network()->decodeString(string);
140 QByteArray NetworkConnection::serverEncode(const QString &string) const {
141 return network()->encodeServerString(string);
144 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
145 if(!bufferName.isEmpty()) {
146 IrcChannel *channel = network()->ircChannel(bufferName);
147 if(channel) return channel->encodeString(string);
149 return network()->encodeString(string);
152 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
153 IrcUser *user = network()->ircUser(userNick);
154 if(user) return user->encodeString(string);
155 return network()->encodeString(string);
158 void NetworkConnection::autoReconnectSettingsChanged() {
159 if(!network()->useAutoReconnect()) {
160 _autoReconnectTimer.stop();
161 _autoReconnectCount = 0;
163 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
164 if(_autoReconnectCount != 0) {
165 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
166 else _autoReconnectCount = network()->autoReconnectRetries();
171 void NetworkConnection::connectToIrc(bool reconnecting) {
172 if(!reconnecting && network()->useAutoReconnect() && _autoReconnectCount == 0) {
173 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
174 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
175 else _autoReconnectCount = network()->autoReconnectRetries();
177 QVariantList serverList = network()->serverList();
178 Identity *identity = coreSession()->identity(network()->identity());
179 if(!serverList.count()) {
180 qWarning() << "Server list empty, ignoring connect request!";
184 qWarning() << "Invalid identity configures, ignoring connect request!";
187 // use a random server?
188 if(network()->useRandomServer()) {
189 _lastUsedServerlistIndex = qrand() % serverList.size();
190 } else if(_previousConnectionAttemptFailed) {
191 // cycle to next server if previous connection attempt failed
192 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
193 if(++_lastUsedServerlistIndex == serverList.size()) {
194 _lastUsedServerlistIndex = 0;
197 _previousConnectionAttemptFailed = false;
199 QString host = serverList[_lastUsedServerlistIndex].toMap()["Host"].toString();
200 quint16 port = serverList[_lastUsedServerlistIndex].toMap()["Port"].toUInt();
201 displayStatusMsg(tr("Connecting to %1:%2...").arg(host).arg(port));
202 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(host).arg(port));
203 socket.connectToHost(host, port);
206 void NetworkConnection::networkInitialized(const QString ¤tServer) {
207 if(currentServer.isEmpty()) return;
209 if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
210 _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
215 // now we are initialized
216 setConnectionState(Network::Initialized);
217 network()->setConnected(true);
218 emit connected(networkId());
220 if(_autoWhoEnabled) {
221 _autoWhoCycleTimer.start();
222 _autoWhoTimer.start();
223 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
227 void NetworkConnection::sendPerform() {
228 BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
230 if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
231 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
234 foreach(QString line, network()->perform()) {
235 if(!line.isEmpty()) userInput(statusBuf, line);
238 // rejoin channels we've been in
239 QStringList channels, keys;
240 foreach(QString chan, persistentChannels()) {
241 QString key = channelKey(chan);
243 channels.prepend(chan); keys.prepend(key);
245 channels.append(chan);
248 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
249 if(!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString);
252 void NetworkConnection::disconnectFromIrc(bool requested) {
253 _autoReconnectTimer.stop();
254 _autoReconnectCount = 0;
255 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
256 if(socket.state() < QAbstractSocket::ConnectedState) {
257 setConnectionState(Network::Disconnected);
258 socketDisconnected();
259 } else socket.disconnectFromHost();
262 emit quitRequested(networkId());
266 void NetworkConnection::socketHasData() {
267 while(socket.canReadLine()) {
268 QByteArray s = socket.readLine().trimmed();
269 ircServerHandler()->handleServerMsg(s);
273 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
274 _previousConnectionAttemptFailed = true;
275 qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
276 emit connectionError(socket.errorString());
277 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
278 network()->emitConnectionError(socket.errorString());
279 if(socket.state() < QAbstractSocket::ConnectedState) {
280 setConnectionState(Network::Disconnected);
281 socketDisconnected();
283 // mark last connection attempt as failed
285 //qDebug() << "exiting...";
289 #ifndef QT_NO_OPENSSL
291 void NetworkConnection::sslErrors(const QList<QSslError> &sslErrors) {
293 socket.ignoreSslErrors();
294 /* TODO errorhandling
296 QVariantList errnums;
297 foreach(QSslError err, errors) errnums << err.error();
298 errmsg["SslErrors"] = errnums;
299 errmsg["SslCert"] = socket.peerCertificate().toPem();
300 errmsg["PeerAddress"] = socket.peerAddress().toString();
301 errmsg["PeerPort"] = socket.peerPort();
302 errmsg["PeerName"] = socket.peerName();
303 emit sslErrors(errmsg);
308 void NetworkConnection::socketEncrypted() {
309 //qDebug() << "encrypted!";
313 #endif // QT_NO_OPENSSL
315 void NetworkConnection::socketConnected() {
320 if(!network()->serverList()[_lastUsedServerlistIndex].toMap()["UseSSL"].toBool()) {
324 //qDebug() << "starting handshake";
325 socket.startClientEncryption();
329 void NetworkConnection::socketInitialized() {
330 //emit connected(networkId()); initialize first!
331 Identity *identity = coreSession()->identity(network()->identity());
333 qWarning() << "Identity invalid!";
337 QString passwd = network()->serverList()[_lastUsedServerlistIndex].toMap()["Password"].toString();
338 if(!passwd.isEmpty()) {
339 putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
341 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0]))); // FIXME: try more nicks if error occurs
342 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
345 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
346 Network::ConnectionState state;
347 switch(socketState) {
348 case QAbstractSocket::UnconnectedState:
349 state = Network::Disconnected;
351 case QAbstractSocket::HostLookupState:
352 case QAbstractSocket::ConnectingState:
353 state = Network::Connecting;
355 case QAbstractSocket::ConnectedState:
356 state = Network::Initializing;
358 case QAbstractSocket::ClosingState:
359 state = Network::Disconnecting;
362 state = Network::Disconnected;
364 setConnectionState(state);
367 void NetworkConnection::socketDisconnected() {
368 _autoWhoCycleTimer.stop();
369 _autoWhoTimer.stop();
370 _autoWhoQueue.clear();
371 _autoWhoInProgress.clear();
373 network()->setConnected(false);
374 emit disconnected(networkId());
375 if(_autoReconnectCount != 0) {
376 setConnectionState(Network::Reconnecting);
377 if(_autoReconnectCount == network()->autoReconnectRetries()) doAutoReconnect(); // first try is immediate
378 else _autoReconnectTimer.start();
382 void NetworkConnection::doAutoReconnect() {
383 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
384 qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
387 if(_autoReconnectCount > 0) _autoReconnectCount--;
391 // FIXME switch to BufferId
392 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
393 userInputHandler()->handleUserInput(buf, msg);
396 void NetworkConnection::putRawLine(QByteArray s) {
397 if(_tokenBucket > 0) {
398 // qDebug() << "putRawLine: " << s;
405 void NetworkConnection::writeToSocket(QByteArray s) {
407 // qDebug() << "writeToSocket: " << s.size();
412 void NetworkConnection::fillBucketAndProcessQueue() {
413 if(_tokenBucket < _burstSize) {
417 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
418 writeToSocket(_msgQueue.takeFirst());
422 void NetworkConnection::putCmd(const QString &cmd, const QVariantList ¶ms, const QByteArray &prefix) {
424 if(!prefix.isEmpty())
425 msg += ":" + prefix + " ";
426 msg += cmd.toUpper().toAscii();
428 for(int i = 0; i < params.size() - 1; i++) {
429 msg += " " + params[i].toByteArray();
431 if(!params.isEmpty())
432 msg += " :" + params.last().toByteArray();
434 if(cmd == "PRIVMSG" && params.count() > 1) {
435 QByteArray msghead = "PRIVMSG " + params[0].toByteArray() + " :";
437 while (msg.size() > _maxMsgSize) {
438 QByteArray splitter(" .,-");
439 int splitPosition = 0;
440 for(int i = 0; i < splitter.size(); i++) {
441 splitPosition = qMax(splitPosition, msg.lastIndexOf(splitter[i], _maxMsgSize));
443 if(splitPosition < 300) {
444 splitPosition = _maxMsgSize;
446 putRawLine(msg.left(splitPosition));
447 msg = msghead + msg.mid(splitPosition);
454 void NetworkConnection::sendAutoWho() {
455 while(!_autoWhoQueue.isEmpty()) {
456 QString chan = _autoWhoQueue.takeFirst();
457 IrcChannel *ircchan = network()->ircChannel(chan);
458 if(!ircchan) continue;
459 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
460 _autoWhoInProgress[chan]++;
461 putRawLine("WHO " + serverEncode(chan));
462 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
463 // Timer was stopped, means a new cycle is due immediately
464 _autoWhoCycleTimer.start();
471 void NetworkConnection::startAutoWhoCycle() {
472 if(!_autoWhoQueue.isEmpty()) {
473 _autoWhoCycleTimer.stop();
476 _autoWhoQueue = network()->channels();
479 bool NetworkConnection::setAutoWhoDone(const QString &channel) {
480 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0) return false;
481 _autoWhoInProgress[channel.toLower()]--;
485 void NetworkConnection::setChannelJoined(const QString &channel) {
486 emit channelJoined(networkId(), channel, _channelKeys[channel.toLower()]);
487 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
490 void NetworkConnection::setChannelParted(const QString &channel) {
491 removeChannelKey(channel);
492 _autoWhoQueue.removeAll(channel.toLower());
493 _autoWhoInProgress.remove(channel.toLower());
494 emit channelParted(networkId(), channel);
497 void NetworkConnection::addChannelKey(const QString &channel, const QString &key) {
499 removeChannelKey(channel);
501 _channelKeys[channel.toLower()] = key;
505 void NetworkConnection::removeChannelKey(const QString &channel) {
506 _channelKeys.remove(channel.toLower());
509 void NetworkConnection::nickChanged(const QString &newNick, const QString &oldNick) {
510 emit nickChanged(networkId(), newNick, oldNick);
513 /* Exception classes for message handling */
514 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
516 _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
519 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
521 _msg = QString("Unknown Command: ") + cmd + params.join(" ");