617433f35871f03116a3448e460f83030fb499de
[quassel.git] / src / core / networkconnection.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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"
21
22 #include <QMetaObject>
23 #include <QMetaMethod>
24 #include <QDateTime>
25
26 #include "util.h"
27 #include "core.h"
28 #include "coresession.h"
29
30 #include "ircchannel.h"
31 #include "ircuser.h"
32 #include "identity.h"
33
34 #include "ircserverhandler.h"
35 #include "userinputhandler.h"
36 #include "ctcphandler.h"
37
38 NetworkConnection::NetworkConnection(Network *network, CoreSession *session)
39   : QObject(network),
40     _connectionState(Network::Disconnected),
41     _network(network),
42     _coreSession(session),
43     _ircServerHandler(new IrcServerHandler(this)),
44     _userInputHandler(new UserInputHandler(this)),
45     _ctcpHandler(new CtcpHandler(this)),
46     _autoReconnectCount(0),
47     _quitRequested(false),
48
49     _previousConnectionAttemptFailed(false),
50     _lastUsedServerlistIndex(0),
51
52     // TODO make autowho configurable (possibly per-network)
53     _autoWhoEnabled(true),
54     _autoWhoInterval(90),
55     _autoWhoNickLimit(0), // unlimited
56     _autoWhoDelay(3),
57
58     // TokenBucket to avaid sending too much at once
59     _messagesPerSecond(1),
60     _burstSize(5),
61     _tokenBucket(5) // init with a full bucket
62 {
63   _autoReconnectTimer.setSingleShot(true);
64   _socketCloseTimer.setSingleShot(true);
65   connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
66
67   _pingTimer.setInterval(60000);
68   connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
69
70   _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
71   _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
72   
73   _tokenBucketTimer.start(_messagesPerSecond * 1000);
74
75   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
76   foreach(QString chan, channels.keys()) {
77     _channelKeys[chan.toLower()] = channels[chan];
78   }
79
80   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
81   connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
82   connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
83   connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
84
85   connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
86   connect(network, SIGNAL(useAutoReconnectSet(bool)), this, SLOT(autoReconnectSettingsChanged()));
87   connect(network, SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(autoReconnectSettingsChanged()));
88   connect(network, SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(autoReconnectSettingsChanged()));
89
90 #ifndef QT_NO_OPENSSL
91   connect(&socket, SIGNAL(encrypted()), this, SLOT(socketEncrypted()));
92   connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
93 #endif
94   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
95
96   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
97   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
98   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
99   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
100
101   connect(_ircServerHandler, SIGNAL(nickChanged(const QString &, const QString &)),
102           this, SLOT(nickChanged(const QString &, const QString &)));
103
104   network->proxy()->attachSignal(this, SIGNAL(sslErrors(const QVariant &)));
105 }
106
107 NetworkConnection::~NetworkConnection() {
108   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
109     disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
110   disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
111   delete _ircServerHandler;
112   delete _userInputHandler;
113   delete _ctcpHandler;
114 }
115
116 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
117   _connectionState = state;
118   network()->setConnectionState(state);
119   emit connectionStateChanged(state);
120 }
121
122 QString NetworkConnection::serverDecode(const QByteArray &string) const {
123   return network()->decodeServerString(string);
124 }
125
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);
130   }
131   return network()->decodeString(string);
132 }
133
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);
138 }
139
140 QByteArray NetworkConnection::serverEncode(const QString &string) const {
141   return network()->encodeServerString(string);
142 }
143
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);
148   }
149   return network()->encodeString(string);
150 }
151
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);
156 }
157
158 void NetworkConnection::autoReconnectSettingsChanged() {
159   if(!network()->useAutoReconnect()) {
160     _autoReconnectTimer.stop();
161     _autoReconnectCount = 0;
162   } else {
163     _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
164     if(_autoReconnectCount != 0) {
165       if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
166       else _autoReconnectCount = network()->autoReconnectRetries();
167     }
168   }
169 }
170
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();
176   }
177   QVariantList serverList = network()->serverList();
178   Identity *identity = coreSession()->identity(network()->identity());
179   if(!serverList.count()) {
180     qWarning() << "Server list empty, ignoring connect request!";
181     return;
182   }
183   if(!identity) {
184     qWarning() << "Invalid identity configures, ignoring connect request!";
185     return;
186   }
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;
195     }
196   }
197   _previousConnectionAttemptFailed = false;
198
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);
204 }
205
206 void NetworkConnection::networkInitialized(const QString &currentServer) {
207   if(currentServer.isEmpty()) return;
208
209   if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
210     _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
211   }
212
213   sendPerform();
214
215   // now we are initialized
216   setConnectionState(Network::Initialized);
217   network()->setConnected(true);
218   emit connected(networkId());
219
220   _pingTimer.start();
221
222   if(_autoWhoEnabled) {
223     _autoWhoCycleTimer.start();
224     _autoWhoTimer.start();
225     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
226   }
227 }
228
229 void NetworkConnection::sendPerform() {
230   BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
231   // do auto identify
232   if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
233     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
234   }
235   // send perform list
236   foreach(QString line, network()->perform()) {
237     if(!line.isEmpty()) userInput(statusBuf, line);
238   }
239
240   // rejoin channels we've been in
241   QStringList channels, keys;
242   foreach(QString chan, persistentChannels()) {
243     QString key = channelKey(chan);
244     if(!key.isEmpty()) {
245       channels.prepend(chan); keys.prepend(key);
246     } else {
247       channels.append(chan);
248     }
249   }
250   QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
251   if(!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString);
252 }
253
254 void NetworkConnection::disconnectFromIrc(bool requested) {
255   _quitRequested = requested; // see socketDisconnected();
256   _autoReconnectTimer.stop();
257   _autoReconnectCount = 0; // prohibiting auto reconnect
258   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
259   if(socket.state() == QAbstractSocket::UnconnectedState) {
260     socketDisconnected();
261   } else if(socket.state() < QAbstractSocket::ConnectedState) {
262     socket.close();
263     // we might be in a state waiting for a timeout... we don't care... set a disconnected state
264     socketDisconnected();
265   } else {
266     _socketCloseTimer.start(10000); // the irc server has 10 seconds to close the socket
267   }
268 }
269
270 void NetworkConnection::socketHasData() {
271   while(socket.canReadLine()) {
272     QByteArray s = socket.readLine().trimmed();
273     ircServerHandler()->handleServerMsg(s);
274   }
275 }
276
277 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
278   _previousConnectionAttemptFailed = true;
279   qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
280   emit connectionError(socket.errorString());
281   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
282   network()->emitConnectionError(socket.errorString());
283   if(socket.state() < QAbstractSocket::ConnectedState) {
284     socketDisconnected();
285   }
286   // mark last connection attempt as failed
287   
288   //qDebug() << "exiting...";
289   //exit(1);
290 }
291
292 #ifndef QT_NO_OPENSSL
293
294 void NetworkConnection::sslErrors(const QList<QSslError> &sslErrors) {
295   Q_UNUSED(sslErrors)
296   socket.ignoreSslErrors();
297   /* TODO errorhandling
298   QVariantMap errmsg;
299   QVariantList errnums;
300   foreach(QSslError err, errors) errnums << err.error();
301   errmsg["SslErrors"] = errnums;
302   errmsg["SslCert"] = socket.peerCertificate().toPem();
303   errmsg["PeerAddress"] = socket.peerAddress().toString();
304   errmsg["PeerPort"] = socket.peerPort();
305   errmsg["PeerName"] = socket.peerName();
306   emit sslErrors(errmsg);
307   disconnectFromIrc();
308   */
309 }
310
311 void NetworkConnection::socketEncrypted() {
312   //qDebug() << "encrypted!";
313   socketInitialized();
314 }
315
316 #endif  // QT_NO_OPENSSL
317
318 void NetworkConnection::socketConnected() {
319 #ifdef QT_NO_OPENSSL
320   socketInitialized();
321   return;
322 #else
323   if(!network()->serverList()[_lastUsedServerlistIndex].toMap()["UseSSL"].toBool()) {
324     socketInitialized();
325     return;
326   }
327   //qDebug() << "starting handshake";
328   socket.startClientEncryption();
329 #endif
330 }
331
332 void NetworkConnection::socketInitialized() {
333   //emit connected(networkId());  initialize first!
334   Identity *identity = coreSession()->identity(network()->identity());
335   if(!identity) {
336     qWarning() << "Identity invalid!";
337     disconnectFromIrc();
338     return;
339   }
340   QString passwd = network()->serverList()[_lastUsedServerlistIndex].toMap()["Password"].toString();
341   if(!passwd.isEmpty()) {
342     putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
343   }
344   putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));  // FIXME: try more nicks if error occurs
345   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
346 }
347
348 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
349   Network::ConnectionState state;
350   switch(socketState) {
351     case QAbstractSocket::UnconnectedState:
352       state = Network::Disconnected;
353       break;
354     case QAbstractSocket::HostLookupState:
355     case QAbstractSocket::ConnectingState:
356       state = Network::Connecting;
357       break;
358     case QAbstractSocket::ConnectedState:
359       state = Network::Initializing;
360       break;
361     case QAbstractSocket::ClosingState:
362       state = Network::Disconnecting;
363       break;
364     default:
365       state = Network::Disconnected;
366   }
367   setConnectionState(state);
368 }
369
370 void NetworkConnection::socketCloseTimeout() {
371   socket.disconnectFromHost();
372 }
373
374 void NetworkConnection::socketDisconnected() {
375   _pingTimer.stop();
376   _autoWhoCycleTimer.stop();
377   _autoWhoTimer.stop();
378   _autoWhoQueue.clear();
379   _autoWhoInProgress.clear();
380
381   _socketCloseTimer.stop();
382   
383   network()->setConnected(false);
384   emit disconnected(networkId());
385   if(_quitRequested) {
386     setConnectionState(Network::Disconnected);
387     emit quitRequested(networkId());
388   } else if(_autoReconnectCount != 0) {
389     setConnectionState(Network::Reconnecting);
390     if(_autoReconnectCount == network()->autoReconnectRetries())
391       doAutoReconnect(); // first try is immediate
392     else
393       _autoReconnectTimer.start();
394   }
395 }
396
397 void NetworkConnection::doAutoReconnect() {
398   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
399     qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
400     return;
401   }
402   if(_autoReconnectCount > 0) _autoReconnectCount--;
403   connectToIrc(true);
404 }
405
406 // FIXME switch to BufferId
407 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
408   userInputHandler()->handleUserInput(buf, msg);
409 }
410
411 void NetworkConnection::putRawLine(QByteArray s) {
412   if(_tokenBucket > 0) {
413     // qDebug() << "putRawLine: " << s;
414     writeToSocket(s);
415   } else {
416     _msgQueue.append(s);
417   }
418 }
419
420 void NetworkConnection::writeToSocket(QByteArray s) {
421   s += "\r\n";
422   // qDebug() << "writeToSocket: " << s.size();
423   socket.write(s);
424   _tokenBucket--;
425 }
426
427 void NetworkConnection::fillBucketAndProcessQueue() {
428   if(_tokenBucket < _burstSize) {
429     _tokenBucket++;
430   }
431
432   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
433     writeToSocket(_msgQueue.takeFirst());
434   }
435 }
436
437 // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
438 int NetworkConnection::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params) {
439   //the server will pass our message that trunkated to 512 bytes including CRLF with the following format:
440   // ":prefix COMMAND param0 param1 :lastparam"
441   // where prefix = "nickname!user@host"
442   // that means that the last message can be as long as:
443   // 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)
444   IrcUser *me = network()->me();
445   int maxLen = 480 - cmd.toAscii().count(); // educated guess in case we don't know us (yet?)
446
447   if(me)
448     maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toAscii().count() - 6;
449
450   if(!params.isEmpty()) {
451     for(int i = 0; i < params.count() - 1; i++) {
452       maxLen -= (params[i].count() + 1);
453     }
454     maxLen -= 2; // " :" last param separator;
455     
456     if(params.last().count() > maxLen) {
457       return params.last().count() - maxLen;
458     } else {
459       return 0;
460     }
461   } else {
462     return 0;
463   }
464 }
465
466 void NetworkConnection::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix) {
467   QByteArray msg;
468   if(cmd == "PRIVMSG" && params.count() > 1) {
469     int overrun = lastParamOverrun(cmd, params);
470     if(overrun) {
471       QList<QByteArray> paramCopy1;
472       QList<QByteArray> paramCopy2;
473       for(int i = 0; i < params.count() - 1; i++) {
474         paramCopy1 << params[i];
475         paramCopy2 << params[i];
476       }
477
478       QByteArray lastPart = params.last();
479       QByteArray splitter(" .,-");
480       int maxSplitPos = params.last().count() - overrun;
481       int splitPos = -1;
482       for(int i = 0; i < splitter.size(); i++) {
483         splitPos = qMax(splitPos, lastPart.lastIndexOf(splitter[i], maxSplitPos));
484       }
485
486       if(splitPos == -1) {
487         splitPos = maxSplitPos;
488       }
489       
490       paramCopy1 << lastPart.left(splitPos);
491       paramCopy2 << lastPart.mid(splitPos);
492       putCmd(cmd, paramCopy1, prefix);
493       putCmd(cmd, paramCopy2, prefix);
494       return;
495     }
496   }
497      
498   if(!prefix.isEmpty())
499     msg += ":" + prefix + " ";
500   msg += cmd.toUpper().toAscii();
501
502   for(int i = 0; i < params.size() - 1; i++) {
503     msg += " " + params[i];
504   }
505   if(!params.isEmpty())
506     msg += " :" + params.last();
507
508   putRawLine(msg);
509 }
510
511 void NetworkConnection::sendPing() {
512   userInputHandler()->handlePing(BufferInfo(), QString());
513 }
514
515 void NetworkConnection::sendAutoWho() {
516   while(!_autoWhoQueue.isEmpty()) {
517     QString chan = _autoWhoQueue.takeFirst();
518     IrcChannel *ircchan = network()->ircChannel(chan);
519     if(!ircchan) continue;
520     if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
521     _autoWhoInProgress[chan]++;
522     putRawLine("WHO " + serverEncode(chan));
523     if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
524       // Timer was stopped, means a new cycle is due immediately
525       _autoWhoCycleTimer.start();
526       startAutoWhoCycle();
527     }
528     break;
529   }
530 }
531
532 void NetworkConnection::startAutoWhoCycle() {
533   if(!_autoWhoQueue.isEmpty()) {
534     _autoWhoCycleTimer.stop();
535     return;
536   }
537   _autoWhoQueue = network()->channels();
538 }
539
540 bool NetworkConnection::setAutoWhoDone(const QString &channel) {
541   if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0) return false;
542   _autoWhoInProgress[channel.toLower()]--;
543   return true;
544 }
545
546 void NetworkConnection::setChannelJoined(const QString &channel) {
547   emit channelJoined(networkId(), channel, _channelKeys[channel.toLower()]);
548   _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
549 }
550
551 void NetworkConnection::setChannelParted(const QString &channel) {
552   removeChannelKey(channel);
553   _autoWhoQueue.removeAll(channel.toLower());
554   _autoWhoInProgress.remove(channel.toLower());
555   emit channelParted(networkId(), channel);
556 }
557
558 void NetworkConnection::addChannelKey(const QString &channel, const QString &key) {
559   if(key.isEmpty()) {
560     removeChannelKey(channel);
561   } else {
562     _channelKeys[channel.toLower()] = key;
563   }
564 }
565
566 void NetworkConnection::removeChannelKey(const QString &channel) {
567   _channelKeys.remove(channel.toLower());
568 }
569
570 void NetworkConnection::nickChanged(const QString &newNick, const QString &oldNick) {
571   emit nickChanged(networkId(), newNick, oldNick);
572 }
573
574 /* Exception classes for message handling */
575 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
576   Q_UNUSED(prefix);
577   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
578 }
579
580 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
581   Q_UNUSED(prefix);
582   _msg = QString("Unknown Command: ") + cmd + params.join(" ");
583 }
584