Quassel now uses proper default messages for part, quit, kick and away (/away toggles...
[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     // TODO: 
65     // should be 510 (2 bytes are added when writing to the socket)
66     // maxMsgSize is 510 minus the hostmask which will be added by the server
67     _maxMsgSize(450)
68 {
69   _autoReconnectTimer.setSingleShot(true);
70   _socketCloseTimer.setSingleShot(true);
71   connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
72   
73   _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
74   _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
75   
76   _tokenBucketTimer.start(_messagesPerSecond * 1000);
77
78   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
79   foreach(QString chan, channels.keys()) {
80     _channelKeys[chan.toLower()] = channels[chan];
81   }
82
83   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
84   connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
85   connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
86   connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
87
88   connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
89   connect(network, SIGNAL(useAutoReconnectSet(bool)), this, SLOT(autoReconnectSettingsChanged()));
90   connect(network, SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(autoReconnectSettingsChanged()));
91   connect(network, SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(autoReconnectSettingsChanged()));
92
93 #ifndef QT_NO_OPENSSL
94   connect(&socket, SIGNAL(encrypted()), this, SLOT(socketEncrypted()));
95   connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
96 #endif
97   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
98
99   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
100   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
101   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
102   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
103
104   connect(_ircServerHandler, SIGNAL(nickChanged(const QString &, const QString &)),
105           this, SLOT(nickChanged(const QString &, const QString &)));
106
107   network->proxy()->attachSignal(this, SIGNAL(sslErrors(const QVariant &)));
108 }
109
110 NetworkConnection::~NetworkConnection() {
111   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
112     disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
113   disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
114   delete _ircServerHandler;
115   delete _userInputHandler;
116   delete _ctcpHandler;
117 }
118
119 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
120   _connectionState = state;
121   network()->setConnectionState(state);
122   emit connectionStateChanged(state);
123 }
124
125 QString NetworkConnection::serverDecode(const QByteArray &string) const {
126   return network()->decodeServerString(string);
127 }
128
129 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
130   if(!bufferName.isEmpty()) {
131     IrcChannel *channel = network()->ircChannel(bufferName);
132     if(channel) return channel->decodeString(string);
133   }
134   return network()->decodeString(string);
135 }
136
137 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
138   IrcUser *user = network()->ircUser(userNick);
139   if(user) return user->decodeString(string);
140   return network()->decodeString(string);
141 }
142
143 QByteArray NetworkConnection::serverEncode(const QString &string) const {
144   return network()->encodeServerString(string);
145 }
146
147 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
148   if(!bufferName.isEmpty()) {
149     IrcChannel *channel = network()->ircChannel(bufferName);
150     if(channel) return channel->encodeString(string);
151   }
152   return network()->encodeString(string);
153 }
154
155 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
156   IrcUser *user = network()->ircUser(userNick);
157   if(user) return user->encodeString(string);
158   return network()->encodeString(string);
159 }
160
161 void NetworkConnection::autoReconnectSettingsChanged() {
162   if(!network()->useAutoReconnect()) {
163     _autoReconnectTimer.stop();
164     _autoReconnectCount = 0;
165   } else {
166     _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
167     if(_autoReconnectCount != 0) {
168       if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
169       else _autoReconnectCount = network()->autoReconnectRetries();
170     }
171   }
172 }
173
174 void NetworkConnection::connectToIrc(bool reconnecting) {
175   if(!reconnecting && network()->useAutoReconnect() && _autoReconnectCount == 0) {
176     _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
177     if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
178     else _autoReconnectCount = network()->autoReconnectRetries();
179   }
180   QVariantList serverList = network()->serverList();
181   Identity *identity = coreSession()->identity(network()->identity());
182   if(!serverList.count()) {
183     qWarning() << "Server list empty, ignoring connect request!";
184     return;
185   }
186   if(!identity) {
187     qWarning() << "Invalid identity configures, ignoring connect request!";
188     return;
189   }
190   // use a random server?
191   if(network()->useRandomServer()) {
192     _lastUsedServerlistIndex = qrand() % serverList.size();
193   } else if(_previousConnectionAttemptFailed) {
194     // cycle to next server if previous connection attempt failed
195     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
196     if(++_lastUsedServerlistIndex == serverList.size()) {
197       _lastUsedServerlistIndex = 0;
198     }
199   }
200   _previousConnectionAttemptFailed = false;
201
202   QString host = serverList[_lastUsedServerlistIndex].toMap()["Host"].toString();
203   quint16 port = serverList[_lastUsedServerlistIndex].toMap()["Port"].toUInt();
204   displayStatusMsg(tr("Connecting to %1:%2...").arg(host).arg(port));
205   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(host).arg(port));
206   socket.connectToHost(host, port);
207 }
208
209 void NetworkConnection::networkInitialized(const QString &currentServer) {
210   if(currentServer.isEmpty()) return;
211
212   if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
213     _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
214   }
215
216   sendPerform();
217
218   // now we are initialized
219   setConnectionState(Network::Initialized);
220   network()->setConnected(true);
221   emit connected(networkId());
222
223   if(_autoWhoEnabled) {
224     _autoWhoCycleTimer.start();
225     _autoWhoTimer.start();
226     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
227   }
228 }
229
230 void NetworkConnection::sendPerform() {
231   BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
232   // do auto identify
233   if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
234     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
235   }
236   // send perform list
237   foreach(QString line, network()->perform()) {
238     if(!line.isEmpty()) userInput(statusBuf, line);
239   }
240
241   // rejoin channels we've been in
242   QStringList channels, keys;
243   foreach(QString chan, persistentChannels()) {
244     QString key = channelKey(chan);
245     if(!key.isEmpty()) {
246       channels.prepend(chan); keys.prepend(key);
247     } else {
248       channels.append(chan);
249     }
250   }
251   QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
252   if(!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString);
253 }
254
255 void NetworkConnection::disconnectFromIrc(bool requested) {
256   _autoReconnectTimer.stop();
257   _autoReconnectCount = 0;
258   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
259   if(socket.state() < QAbstractSocket::ConnectedState) {
260     setConnectionState(Network::Disconnected);
261     socketDisconnected();
262   } else {
263     _socketCloseTimer.start(10000); // the irc server has 10 seconds to close the socket
264   }
265
266   // this flag triggers quitRequested() once the socket is closed
267   // it is needed to determine whether or not the connection needs to be
268   // in the automatic session restore.
269   _quitRequested = requested;
270 }
271
272 void NetworkConnection::socketHasData() {
273   while(socket.canReadLine()) {
274     QByteArray s = socket.readLine().trimmed();
275     ircServerHandler()->handleServerMsg(s);
276   }
277 }
278
279 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
280   _previousConnectionAttemptFailed = true;
281   qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
282   emit connectionError(socket.errorString());
283   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
284   network()->emitConnectionError(socket.errorString());
285   if(socket.state() < QAbstractSocket::ConnectedState) {
286     setConnectionState(Network::Disconnected);
287     socketDisconnected();
288   }
289   // mark last connection attempt as failed
290   
291   //qDebug() << "exiting...";
292   //exit(1);
293 }
294
295 #ifndef QT_NO_OPENSSL
296
297 void NetworkConnection::sslErrors(const QList<QSslError> &sslErrors) {
298   Q_UNUSED(sslErrors)
299   socket.ignoreSslErrors();
300   /* TODO errorhandling
301   QVariantMap errmsg;
302   QVariantList errnums;
303   foreach(QSslError err, errors) errnums << err.error();
304   errmsg["SslErrors"] = errnums;
305   errmsg["SslCert"] = socket.peerCertificate().toPem();
306   errmsg["PeerAddress"] = socket.peerAddress().toString();
307   errmsg["PeerPort"] = socket.peerPort();
308   errmsg["PeerName"] = socket.peerName();
309   emit sslErrors(errmsg);
310   disconnectFromIrc();
311   */
312 }
313
314 void NetworkConnection::socketEncrypted() {
315   //qDebug() << "encrypted!";
316   socketInitialized();
317 }
318
319 #endif  // QT_NO_OPENSSL
320
321 void NetworkConnection::socketConnected() {
322 #ifdef QT_NO_OPENSSL
323   socketInitialized();
324   return;
325 #else
326   if(!network()->serverList()[_lastUsedServerlistIndex].toMap()["UseSSL"].toBool()) {
327     socketInitialized();
328     return;
329   }
330   //qDebug() << "starting handshake";
331   socket.startClientEncryption();
332 #endif
333 }
334
335 void NetworkConnection::socketInitialized() {
336   //emit connected(networkId());  initialize first!
337   Identity *identity = coreSession()->identity(network()->identity());
338   if(!identity) {
339     qWarning() << "Identity invalid!";
340     disconnectFromIrc();
341     return;
342   }
343   QString passwd = network()->serverList()[_lastUsedServerlistIndex].toMap()["Password"].toString();
344   if(!passwd.isEmpty()) {
345     putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
346   }
347   putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));  // FIXME: try more nicks if error occurs
348   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
349 }
350
351 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
352   Network::ConnectionState state;
353   switch(socketState) {
354     case QAbstractSocket::UnconnectedState:
355       state = Network::Disconnected;
356       break;
357     case QAbstractSocket::HostLookupState:
358     case QAbstractSocket::ConnectingState:
359       state = Network::Connecting;
360       break;
361     case QAbstractSocket::ConnectedState:
362       state = Network::Initializing;
363       break;
364     case QAbstractSocket::ClosingState:
365       state = Network::Disconnecting;
366       break;
367     default:
368       state = Network::Disconnected;
369   }
370   setConnectionState(state);
371 }
372
373 void NetworkConnection::socketCloseTimeout() {
374   socket.disconnectFromHost();
375 }
376
377 void NetworkConnection::socketDisconnected() {
378   _autoWhoCycleTimer.stop();
379   _autoWhoTimer.stop();
380   _autoWhoQueue.clear();
381   _autoWhoInProgress.clear();
382
383   _socketCloseTimer.stop();
384   
385   network()->setConnected(false);
386   emit disconnected(networkId());
387   if(_autoReconnectCount != 0) {
388     setConnectionState(Network::Reconnecting);
389     if(_autoReconnectCount == network()->autoReconnectRetries()) doAutoReconnect(); // first try is immediate
390     else _autoReconnectTimer.start();
391   } else if(_quitRequested) {
392     emit quitRequested(networkId());
393   }
394 }
395
396 void NetworkConnection::doAutoReconnect() {
397   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
398     qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
399     return;
400   }
401   if(_autoReconnectCount > 0) _autoReconnectCount--;
402   connectToIrc(true);
403 }
404
405 // FIXME switch to BufferId
406 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
407   userInputHandler()->handleUserInput(buf, msg);
408 }
409
410 void NetworkConnection::putRawLine(QByteArray s) {
411   if(_tokenBucket > 0) {
412     // qDebug() << "putRawLine: " << s;
413     writeToSocket(s);
414   } else {
415     _msgQueue.append(s);
416   }
417 }
418
419 void NetworkConnection::writeToSocket(QByteArray s) {
420   s += "\r\n";
421   // qDebug() << "writeToSocket: " << s.size();
422   socket.write(s);
423   _tokenBucket--;
424 }
425
426 void NetworkConnection::fillBucketAndProcessQueue() {
427   if(_tokenBucket < _burstSize) {
428     _tokenBucket++;
429   }
430
431   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
432     writeToSocket(_msgQueue.takeFirst());
433   }
434 }
435
436 void NetworkConnection::putCmd(const QString &cmd, const QVariantList &params, const QByteArray &prefix) {
437   QByteArray msg;
438   if(!prefix.isEmpty())
439     msg += ":" + prefix + " ";
440   msg += cmd.toUpper().toAscii();
441
442   for(int i = 0; i < params.size() - 1; i++) {
443     msg += " " + params[i].toByteArray();
444   }
445   if(!params.isEmpty())
446     msg += " :" + params.last().toByteArray();
447
448   if(cmd == "PRIVMSG" && params.count() > 1) {
449     QByteArray msghead = "PRIVMSG " + params[0].toByteArray() + " :";
450
451     while (msg.size() > _maxMsgSize) {
452       QByteArray splitter(" .,-");
453       int splitPosition = 0;
454       for(int i = 0; i < splitter.size(); i++) {
455         splitPosition = qMax(splitPosition, msg.lastIndexOf(splitter[i], _maxMsgSize));
456       }
457       if(splitPosition < 300) {
458         splitPosition = _maxMsgSize;
459       }
460       putRawLine(msg.left(splitPosition)); 
461       msg = msghead + msg.mid(splitPosition);
462     }
463   }
464
465   putRawLine(msg);
466 }
467
468 void NetworkConnection::sendAutoWho() {
469   while(!_autoWhoQueue.isEmpty()) {
470     QString chan = _autoWhoQueue.takeFirst();
471     IrcChannel *ircchan = network()->ircChannel(chan);
472     if(!ircchan) continue;
473     if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
474     _autoWhoInProgress[chan]++;
475     putRawLine("WHO " + serverEncode(chan));
476     if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
477       // Timer was stopped, means a new cycle is due immediately
478       _autoWhoCycleTimer.start();
479       startAutoWhoCycle();
480     }
481     break;
482   }
483 }
484
485 void NetworkConnection::startAutoWhoCycle() {
486   if(!_autoWhoQueue.isEmpty()) {
487     _autoWhoCycleTimer.stop();
488     return;
489   }
490   _autoWhoQueue = network()->channels();
491 }
492
493 bool NetworkConnection::setAutoWhoDone(const QString &channel) {
494   if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0) return false;
495   _autoWhoInProgress[channel.toLower()]--;
496   return true;
497 }
498
499 void NetworkConnection::setChannelJoined(const QString &channel) {
500   emit channelJoined(networkId(), channel, _channelKeys[channel.toLower()]);
501   _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
502 }
503
504 void NetworkConnection::setChannelParted(const QString &channel) {
505   removeChannelKey(channel);
506   _autoWhoQueue.removeAll(channel.toLower());
507   _autoWhoInProgress.remove(channel.toLower());
508   emit channelParted(networkId(), channel);
509 }
510
511 void NetworkConnection::addChannelKey(const QString &channel, const QString &key) {
512   if(key.isEmpty()) {
513     removeChannelKey(channel);
514   } else {
515     _channelKeys[channel.toLower()] = key;
516   }
517 }
518
519 void NetworkConnection::removeChannelKey(const QString &channel) {
520   _channelKeys.remove(channel.toLower());
521 }
522
523 void NetworkConnection::nickChanged(const QString &newNick, const QString &oldNick) {
524   emit nickChanged(networkId(), newNick, oldNick);
525 }
526
527 /* Exception classes for message handling */
528 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
529   Q_UNUSED(prefix);
530   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
531 }
532
533 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
534   Q_UNUSED(prefix);
535   _msg = QString("Unknown Command: ") + cmd + params.join(" ");
536 }
537