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()));
89 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketEncrypted()));
90 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
92 connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
94 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
95 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
96 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
97 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
99 connect(_ircServerHandler, SIGNAL(nickChanged(const QString &, const QString &)),
100 this, SLOT(nickChanged(const QString &, const QString &)));
102 network->proxy()->attachSignal(this, SIGNAL(sslErrors(const QVariant &)));
105 NetworkConnection::~NetworkConnection() {
106 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
107 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
108 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
109 delete _ircServerHandler;
110 delete _userInputHandler;
114 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
115 _connectionState = state;
116 network()->setConnectionState(state);
117 emit connectionStateChanged(state);
120 QString NetworkConnection::serverDecode(const QByteArray &string) const {
121 return network()->decodeServerString(string);
124 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
125 if(!bufferName.isEmpty()) {
126 IrcChannel *channel = network()->ircChannel(bufferName);
127 if(channel) return channel->decodeString(string);
129 return network()->decodeString(string);
132 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
133 IrcUser *user = network()->ircUser(userNick);
134 if(user) return user->decodeString(string);
135 return network()->decodeString(string);
138 QByteArray NetworkConnection::serverEncode(const QString &string) const {
139 return network()->encodeServerString(string);
142 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
143 if(!bufferName.isEmpty()) {
144 IrcChannel *channel = network()->ircChannel(bufferName);
145 if(channel) return channel->encodeString(string);
147 return network()->encodeString(string);
150 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
151 IrcUser *user = network()->ircUser(userNick);
152 if(user) return user->encodeString(string);
153 return network()->encodeString(string);
156 void NetworkConnection::autoReconnectSettingsChanged() {
157 if(!network()->useAutoReconnect()) {
158 _autoReconnectTimer.stop();
159 _autoReconnectCount = 0;
161 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
162 if(_autoReconnectCount != 0) {
163 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
164 else _autoReconnectCount = network()->autoReconnectRetries();
169 void NetworkConnection::connectToIrc(bool reconnecting) {
170 if(!reconnecting && network()->useAutoReconnect() && _autoReconnectCount == 0) {
171 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
172 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
173 else _autoReconnectCount = network()->autoReconnectRetries();
175 QVariantList serverList = network()->serverList();
176 Identity *identity = coreSession()->identity(network()->identity());
177 if(!serverList.count()) {
178 qWarning() << "Server list empty, ignoring connect request!";
182 qWarning() << "Invalid identity configures, ignoring connect request!";
185 // use a random server?
186 if(network()->useRandomServer()) {
187 _lastUsedServerlistIndex = qrand() % serverList.size();
188 } else if(_previousConnectionAttemptFailed) {
189 // cycle to next server if previous connection attempt failed
190 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
191 if(++_lastUsedServerlistIndex == serverList.size()) {
192 _lastUsedServerlistIndex = 0;
195 _previousConnectionAttemptFailed = false;
197 QString host = serverList[_lastUsedServerlistIndex].toMap()["Host"].toString();
198 quint16 port = serverList[_lastUsedServerlistIndex].toMap()["Port"].toUInt();
199 displayStatusMsg(tr("Connecting to %1:%2...").arg(host).arg(port));
200 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(host).arg(port));
201 socket.connectToHost(host, port);
204 void NetworkConnection::networkInitialized(const QString ¤tServer) {
205 if(currentServer.isEmpty()) return;
207 if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
208 _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
213 // now we are initialized
214 setConnectionState(Network::Initialized);
215 network()->setConnected(true);
216 emit connected(networkId());
218 if(_autoWhoEnabled) {
219 _autoWhoCycleTimer.start();
220 _autoWhoTimer.start();
221 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
225 void NetworkConnection::sendPerform() {
226 BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
228 if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
229 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
232 foreach(QString line, network()->perform()) {
233 if(!line.isEmpty()) userInput(statusBuf, line);
236 // rejoin channels we've been in
237 QStringList channels, keys;
238 foreach(QString chan, persistentChannels()) {
239 QString key = channelKey(chan);
241 channels.prepend(chan); keys.prepend(key);
243 channels.append(chan);
246 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
247 if(!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString);
250 void NetworkConnection::disconnectFromIrc(bool requested) {
251 _autoReconnectTimer.stop();
252 _autoReconnectCount = 0;
253 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
254 if(socket.state() < QAbstractSocket::ConnectedState) {
255 setConnectionState(Network::Disconnected);
256 socketDisconnected();
258 _socketCloseTimer.start(10000); // the irc server has 10 seconds to close the socket
261 // this flag triggers quitRequested() once the socket is closed
262 // it is needed to determine whether or not the connection needs to be
263 // in the automatic session restore.
264 _quitRequested = requested;
267 void NetworkConnection::socketHasData() {
268 while(socket.canReadLine()) {
269 QByteArray s = socket.readLine().trimmed();
270 ircServerHandler()->handleServerMsg(s);
274 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
275 _previousConnectionAttemptFailed = true;
276 qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
277 emit connectionError(socket.errorString());
278 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
279 network()->emitConnectionError(socket.errorString());
280 if(socket.state() < QAbstractSocket::ConnectedState) {
281 setConnectionState(Network::Disconnected);
282 socketDisconnected();
284 // mark last connection attempt as failed
286 //qDebug() << "exiting...";
290 #ifndef QT_NO_OPENSSL
292 void NetworkConnection::sslErrors(const QList<QSslError> &sslErrors) {
294 socket.ignoreSslErrors();
295 /* TODO errorhandling
297 QVariantList errnums;
298 foreach(QSslError err, errors) errnums << err.error();
299 errmsg["SslErrors"] = errnums;
300 errmsg["SslCert"] = socket.peerCertificate().toPem();
301 errmsg["PeerAddress"] = socket.peerAddress().toString();
302 errmsg["PeerPort"] = socket.peerPort();
303 errmsg["PeerName"] = socket.peerName();
304 emit sslErrors(errmsg);
309 void NetworkConnection::socketEncrypted() {
310 //qDebug() << "encrypted!";
314 #endif // QT_NO_OPENSSL
316 void NetworkConnection::socketConnected() {
321 if(!network()->serverList()[_lastUsedServerlistIndex].toMap()["UseSSL"].toBool()) {
325 //qDebug() << "starting handshake";
326 socket.startClientEncryption();
330 void NetworkConnection::socketInitialized() {
331 //emit connected(networkId()); initialize first!
332 Identity *identity = coreSession()->identity(network()->identity());
334 qWarning() << "Identity invalid!";
338 QString passwd = network()->serverList()[_lastUsedServerlistIndex].toMap()["Password"].toString();
339 if(!passwd.isEmpty()) {
340 putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
342 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0]))); // FIXME: try more nicks if error occurs
343 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
346 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
347 Network::ConnectionState state;
348 switch(socketState) {
349 case QAbstractSocket::UnconnectedState:
350 state = Network::Disconnected;
352 case QAbstractSocket::HostLookupState:
353 case QAbstractSocket::ConnectingState:
354 state = Network::Connecting;
356 case QAbstractSocket::ConnectedState:
357 state = Network::Initializing;
359 case QAbstractSocket::ClosingState:
360 state = Network::Disconnecting;
363 state = Network::Disconnected;
365 setConnectionState(state);
368 void NetworkConnection::socketCloseTimeout() {
369 socket.disconnectFromHost();
372 void NetworkConnection::socketDisconnected() {
373 _autoWhoCycleTimer.stop();
374 _autoWhoTimer.stop();
375 _autoWhoQueue.clear();
376 _autoWhoInProgress.clear();
378 _socketCloseTimer.stop();
380 network()->setConnected(false);
381 emit disconnected(networkId());
382 if(_autoReconnectCount != 0) {
383 setConnectionState(Network::Reconnecting);
384 if(_autoReconnectCount == network()->autoReconnectRetries()) doAutoReconnect(); // first try is immediate
385 else _autoReconnectTimer.start();
386 } else if(_quitRequested) {
387 emit quitRequested(networkId());
391 void NetworkConnection::doAutoReconnect() {
392 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
393 qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
396 if(_autoReconnectCount > 0) _autoReconnectCount--;
400 // FIXME switch to BufferId
401 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
402 userInputHandler()->handleUserInput(buf, msg);
405 void NetworkConnection::putRawLine(QByteArray s) {
406 if(_tokenBucket > 0) {
407 // qDebug() << "putRawLine: " << s;
414 void NetworkConnection::writeToSocket(QByteArray s) {
416 // qDebug() << "writeToSocket: " << s.size();
421 void NetworkConnection::fillBucketAndProcessQueue() {
422 if(_tokenBucket < _burstSize) {
426 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
427 writeToSocket(_msgQueue.takeFirst());
431 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
432 int NetworkConnection::lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms) {
433 //the server will pass our message that trunkated to 512 bytes including CRLF with the following format:
434 // ":prefix COMMAND param0 param1 :lastparam"
435 // where prefix = "nickname!user@host"
436 // that means that the last message can be as long as:
437 // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
438 IrcUser *me = network()->me();
439 int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
442 maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
444 if(!params.isEmpty()) {
445 for(int i = 0; i < params.count() - 1; i++) {
446 maxLen -= (params[i].count() + 1);
448 maxLen -= 2; // " :" last param separator;
450 if(params.last().count() > maxLen) {
451 return params.last().count() - maxLen;
460 void NetworkConnection::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
462 if(cmd == "PRIVMSG" && params.count() > 1) {
463 int overrun = lastParamOverrun(cmd, params);
465 QList<QByteArray> paramCopy1;
466 QList<QByteArray> paramCopy2;
467 for(int i = 0; i < params.count() - 1; i++) {
468 paramCopy1 << params[i];
469 paramCopy2 << params[i];
472 QByteArray lastPart = params.last();
473 QByteArray splitter(" .,-");
474 int maxSplitPos = params.last().count() - overrun;
476 for(int i = 0; i < splitter.size(); i++) {
477 splitPos = qMax(splitPos, lastPart.lastIndexOf(splitter[i], maxSplitPos));
481 splitPos = maxSplitPos;
484 paramCopy1 << lastPart.left(splitPos);
485 paramCopy2 << lastPart.mid(splitPos);
486 putCmd(cmd, paramCopy1, prefix);
487 putCmd(cmd, paramCopy2, prefix);
492 if(!prefix.isEmpty())
493 msg += ":" + prefix + " ";
494 msg += cmd.toUpper().toAscii();
496 for(int i = 0; i < params.size() - 1; i++) {
497 msg += " " + params[i];
499 if(!params.isEmpty())
500 msg += " :" + params.last();
505 void NetworkConnection::sendAutoWho() {
506 while(!_autoWhoQueue.isEmpty()) {
507 QString chan = _autoWhoQueue.takeFirst();
508 IrcChannel *ircchan = network()->ircChannel(chan);
509 if(!ircchan) continue;
510 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
511 _autoWhoInProgress[chan]++;
512 putRawLine("WHO " + serverEncode(chan));
513 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
514 // Timer was stopped, means a new cycle is due immediately
515 _autoWhoCycleTimer.start();
522 void NetworkConnection::startAutoWhoCycle() {
523 if(!_autoWhoQueue.isEmpty()) {
524 _autoWhoCycleTimer.stop();
527 _autoWhoQueue = network()->channels();
530 bool NetworkConnection::setAutoWhoDone(const QString &channel) {
531 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0) return false;
532 _autoWhoInProgress[channel.toLower()]--;
536 void NetworkConnection::setChannelJoined(const QString &channel) {
537 emit channelJoined(networkId(), channel, _channelKeys[channel.toLower()]);
538 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
541 void NetworkConnection::setChannelParted(const QString &channel) {
542 removeChannelKey(channel);
543 _autoWhoQueue.removeAll(channel.toLower());
544 _autoWhoInProgress.remove(channel.toLower());
545 emit channelParted(networkId(), channel);
548 void NetworkConnection::addChannelKey(const QString &channel, const QString &key) {
550 removeChannelKey(channel);
552 _channelKeys[channel.toLower()] = key;
556 void NetworkConnection::removeChannelKey(const QString &channel) {
557 _channelKeys.remove(channel.toLower());
560 void NetworkConnection::nickChanged(const QString &newNick, const QString &oldNick) {
561 emit nickChanged(networkId(), newNick, oldNick);
564 /* Exception classes for message handling */
565 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
567 _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
570 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
572 _msg = QString("Unknown Command: ") + cmd + params.join(" ");