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