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