Fixes #410 - away log (you'll find it in the views menu)
[quassel.git] / src / core / corenetwork.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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
21 #include "corenetwork.h"
22
23 #include "core.h"
24 #include "coresession.h"
25 #include "coreidentity.h"
26
27 #include "ircserverhandler.h"
28 #include "userinputhandler.h"
29 #include "ctcphandler.h"
30
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32   : Network(networkid, session),
33     _coreSession(session),
34     _ircServerHandler(new IrcServerHandler(this)),
35     _userInputHandler(new UserInputHandler(this)),
36     _ctcpHandler(new CtcpHandler(this)),
37     _autoReconnectCount(0),
38     _quitRequested(false),
39
40     _previousConnectionAttemptFailed(false),
41     _lastUsedServerIndex(0),
42
43     // TODO make autowho configurable (possibly per-network)
44     _autoWhoEnabled(true),
45     _autoWhoInterval(90),
46     _autoWhoNickLimit(0), // unlimited
47     _autoWhoDelay(3)
48 {
49   _autoReconnectTimer.setSingleShot(true);
50   _socketCloseTimer.setSingleShot(true);
51   connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
52
53   _pingTimer.setInterval(60000);
54   connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
55
56   _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
57   _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
58
59   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
60   foreach(QString chan, channels.keys()) {
61     _channelKeys[chan.toLower()] = channels[chan];
62   }
63
64   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
65   connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
66   connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
67   connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
68   connect(this, SIGNAL(connectRequested()), this, SLOT(connectToIrc()));
69
70
71   connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
72   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
73   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
74   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
75   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
76 #ifdef HAVE_SSL
77   connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
78   connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
79 #endif
80 }
81
82 CoreNetwork::~CoreNetwork() {
83   if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
84     disconnectFromIrc(false);      // clean up, but this does not count as requested disconnect!
85   else
86     socket.close();
87   disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
88   delete _ircServerHandler;
89   delete _userInputHandler;
90   delete _ctcpHandler;
91 }
92
93 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
94   if(!bufferName.isEmpty()) {
95     IrcChannel *channel = ircChannel(bufferName);
96     if(channel)
97       return channel->decodeString(string);
98   }
99   return decodeString(string);
100 }
101
102 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
103   IrcUser *user = ircUser(userNick);
104   if(user)
105     return user->decodeString(string);
106   return decodeString(string);
107 }
108
109 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
110   if(!bufferName.isEmpty()) {
111     IrcChannel *channel = ircChannel(bufferName);
112     if(channel)
113       return channel->encodeString(string);
114   }
115   return encodeString(string);
116 }
117
118 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
119   IrcUser *user = ircUser(userNick);
120   if(user)
121     return user->encodeString(string);
122   return encodeString(string);
123 }
124
125 void CoreNetwork::connectToIrc(bool reconnecting) {
126   if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
127     _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
128     if(unlimitedReconnectRetries())
129       _autoReconnectCount = -1;
130     else
131       _autoReconnectCount = autoReconnectRetries();
132   }
133   if(serverList().isEmpty()) {
134     qWarning() << "Server list empty, ignoring connect request!";
135     return;
136   }
137   CoreIdentity *identity = identityPtr();
138   if(!identity) {
139     qWarning() << "Invalid identity configures, ignoring connect request!";
140     return;
141   }
142   // use a random server?
143   if(useRandomServer()) {
144     _lastUsedServerIndex = qrand() % serverList().size();
145   } else if(_previousConnectionAttemptFailed) {
146     // cycle to next server if previous connection attempt failed
147     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
148     if(++_lastUsedServerIndex >= serverList().size()) {
149       _lastUsedServerIndex = 0;
150     }
151   }
152   _previousConnectionAttemptFailed = false;
153
154   Server server = usedServer();
155   displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
156   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
157
158   if(server.useProxy) {
159     QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
160     socket.setProxy(proxy);
161   } else {
162     socket.setProxy(QNetworkProxy::NoProxy);
163   }
164
165 #ifdef HAVE_SSL
166   socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
167   if(server.useSsl) {
168     CoreIdentity *identity = identityPtr();
169     if(identity) {
170       socket.setLocalCertificate(identity->sslCert());
171       socket.setPrivateKey(identity->sslKey());
172     }
173     socket.connectToHostEncrypted(server.host, server.port);
174   } else {
175     socket.connectToHost(server.host, server.port);
176   }
177 #else
178   socket.connectToHost(server.host, server.port);
179 #endif
180 }
181
182 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason) {
183   _quitRequested = requested; // see socketDisconnected();
184   _autoReconnectTimer.stop();
185   _autoReconnectCount = 0; // prohibiting auto reconnect
186   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
187   if(socket.state() == QAbstractSocket::UnconnectedState) {
188     socketDisconnected();
189   } else if(socket.state() < QAbstractSocket::ConnectedState || !requested) {
190     // we might be in a state waiting for a timeout...
191     // or (!requested) this is a core shutdown...
192     // in both cases we don't really care... set a disconnected state
193     socket.close();
194     socketDisconnected();
195   } else {
196     // quit gracefully if it's user requested quit
197     userInputHandler()->issueQuit(reason);
198     // the irc server has 10 seconds to close the socket
199     _socketCloseTimer.start(10000);
200   }
201 }
202
203 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
204   userInputHandler()->handleUserInput(buf, msg);
205 }
206
207 void CoreNetwork::putRawLine(QByteArray s) {
208   if(_tokenBucket > 0)
209     writeToSocket(s);
210   else
211     _msgQueue.append(s);
212 }
213
214 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix) {
215   QByteArray msg;
216
217   if(!prefix.isEmpty())
218     msg += ":" + prefix + " ";
219   msg += cmd.toUpper().toAscii();
220
221   for(int i = 0; i < params.size() - 1; i++) {
222     msg += " " + params[i];
223   }
224   if(!params.isEmpty())
225     msg += " :" + params.last();
226
227   putRawLine(msg);
228 }
229
230 void CoreNetwork::setChannelJoined(const QString &channel) {
231   _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
232
233   Core::setChannelPersistent(userId(), networkId(), channel, true);
234   Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
235 }
236
237 void CoreNetwork::setChannelParted(const QString &channel) {
238   removeChannelKey(channel);
239   _autoWhoQueue.removeAll(channel.toLower());
240   _autoWhoInProgress.remove(channel.toLower());
241
242   Core::setChannelPersistent(userId(), networkId(), channel, false);
243 }
244
245 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
246   if(key.isEmpty()) {
247     removeChannelKey(channel);
248   } else {
249     _channelKeys[channel.toLower()] = key;
250   }
251 }
252
253 void CoreNetwork::removeChannelKey(const QString &channel) {
254   _channelKeys.remove(channel.toLower());
255 }
256
257 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
258   if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
259     return false;
260   _autoWhoInProgress[channel.toLower()]--;
261   return true;
262 }
263
264 void CoreNetwork::setMyNick(const QString &mynick) {
265   Network::setMyNick(mynick);
266   if(connectionState() == Network::Initializing)
267     networkInitialized();
268 }
269
270 void CoreNetwork::socketHasData() {
271   while(socket.canReadLine()) {
272     QByteArray s = socket.readLine().trimmed();
273     ircServerHandler()->handleServerMsg(s);
274   }
275 }
276
277 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
278   if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
279     return;
280
281   _previousConnectionAttemptFailed = true;
282   qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
283   emit connectionError(socket.errorString());
284   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
285   emitConnectionError(socket.errorString());
286   if(socket.state() < QAbstractSocket::ConnectedState) {
287     socketDisconnected();
288   }
289 }
290
291 void CoreNetwork::socketInitialized() {
292   Server server = usedServer();
293 #ifdef HAVE_SSL
294   if(server.useSsl && !socket.isEncrypted())
295     return;
296 #endif
297
298   CoreIdentity *identity = identityPtr();
299   if(!identity) {
300     qCritical() << "Identity invalid!";
301     disconnectFromIrc();
302     return;
303   }
304
305   // TokenBucket to avoid sending too much at once
306   _messagesPerSecond = 1;
307   _burstSize = 5;
308   _tokenBucket = 5; // init with a full bucket
309   _tokenBucketTimer.start(_messagesPerSecond * 1000);
310
311   if(!server.password.isEmpty()) {
312     putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
313   }
314   putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
315   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
316 }
317
318 void CoreNetwork::socketDisconnected() {
319   _pingTimer.stop();
320   _autoWhoCycleTimer.stop();
321   _autoWhoTimer.stop();
322   _autoWhoQueue.clear();
323   _autoWhoInProgress.clear();
324
325   _socketCloseTimer.stop();
326
327   _tokenBucketTimer.stop();
328
329   IrcUser *me_ = me();
330   if(me_) {
331     foreach(QString channel, me_->channels())
332       emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, "", me_->hostmask());
333   }
334
335   setConnected(false);
336   emit disconnected(networkId());
337   if(_quitRequested) {
338     setConnectionState(Network::Disconnected);
339     Core::setNetworkConnected(userId(), networkId(), false);
340   } else if(_autoReconnectCount != 0) {
341     setConnectionState(Network::Reconnecting);
342     if(_autoReconnectCount == autoReconnectRetries())
343       doAutoReconnect(); // first try is immediate
344     else
345       _autoReconnectTimer.start();
346   }
347 }
348
349 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
350   Network::ConnectionState state;
351   switch(socketState) {
352     case QAbstractSocket::UnconnectedState:
353       state = Network::Disconnected;
354       break;
355     case QAbstractSocket::HostLookupState:
356     case QAbstractSocket::ConnectingState:
357       state = Network::Connecting;
358       break;
359     case QAbstractSocket::ConnectedState:
360       state = Network::Initializing;
361       break;
362     case QAbstractSocket::ClosingState:
363       state = Network::Disconnecting;
364       break;
365     default:
366       state = Network::Disconnected;
367   }
368   setConnectionState(state);
369 }
370
371 void CoreNetwork::networkInitialized() {
372   setConnectionState(Network::Initialized);
373   setConnected(true);
374   _quitRequested = false;
375
376   if(useAutoReconnect()) {
377     // reset counter
378     _autoReconnectCount = autoReconnectRetries();
379   }
380
381   sendPerform();
382
383   _pingTimer.start();
384
385   if(_autoWhoEnabled) {
386     _autoWhoCycleTimer.start();
387     _autoWhoTimer.start();
388     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
389   }
390
391   Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
392   Core::setNetworkConnected(userId(), networkId(), true);
393 }
394
395 void CoreNetwork::sendPerform() {
396   BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
397
398   // do auto identify
399   if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
400     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
401   }
402
403   // send perform list
404   foreach(QString line, perform()) {
405     if(!line.isEmpty()) userInput(statusBuf, line);
406   }
407
408   // rejoin channels we've been in
409   if(rejoinChannels()) {
410     QStringList channels, keys;
411     foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
412       QString key = channelKey(chan);
413       if(!key.isEmpty()) {
414         channels.prepend(chan);
415         keys.prepend(key);
416       } else {
417         channels.append(chan);
418       }
419     }
420     QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
421     if(!joinString.isEmpty())
422       userInputHandler()->handleJoin(statusBuf, joinString);
423   }
424 }
425
426 void CoreNetwork::setUseAutoReconnect(bool use) {
427   Network::setUseAutoReconnect(use);
428   if(!use)
429     _autoReconnectTimer.stop();
430 }
431
432 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
433   Network::setAutoReconnectInterval(interval);
434   _autoReconnectTimer.setInterval(interval * 1000);
435 }
436
437 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
438   Network::setAutoReconnectRetries(retries);
439   if(_autoReconnectCount != 0) {
440     if(unlimitedReconnectRetries())
441       _autoReconnectCount = -1;
442     else
443       _autoReconnectCount = autoReconnectRetries();
444   }
445 }
446
447 void CoreNetwork::doAutoReconnect() {
448   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
449     qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
450     return;
451   }
452   if(_autoReconnectCount > 0)
453     _autoReconnectCount--;
454   connectToIrc(true);
455 }
456
457 void CoreNetwork::sendPing() {
458   userInputHandler()->handlePing(BufferInfo(), QString());
459 }
460
461 void CoreNetwork::sendAutoWho() {
462   while(!_autoWhoQueue.isEmpty()) {
463     QString chan = _autoWhoQueue.takeFirst();
464     IrcChannel *ircchan = ircChannel(chan);
465     if(!ircchan) continue;
466     if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
467     _autoWhoInProgress[chan]++;
468     putRawLine("WHO " + serverEncode(chan));
469     if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
470       // Timer was stopped, means a new cycle is due immediately
471       _autoWhoCycleTimer.start();
472       startAutoWhoCycle();
473     }
474     break;
475   }
476 }
477
478 void CoreNetwork::startAutoWhoCycle() {
479   if(!_autoWhoQueue.isEmpty()) {
480     _autoWhoCycleTimer.stop();
481     return;
482   }
483   _autoWhoQueue = channels();
484 }
485
486 #ifdef HAVE_SSL
487 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
488   Q_UNUSED(sslErrors)
489   socket.ignoreSslErrors();
490   // TODO errorhandling
491 }
492 #endif  // HAVE_SSL
493
494 void CoreNetwork::fillBucketAndProcessQueue() {
495   if(_tokenBucket < _burstSize) {
496     _tokenBucket++;
497   }
498
499   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
500     writeToSocket(_msgQueue.takeFirst());
501   }
502 }
503
504 void CoreNetwork::writeToSocket(const QByteArray &data) {
505   socket.write(data);
506   socket.write("\r\n");
507   _tokenBucket--;
508 }
509
510 Network::Server CoreNetwork::usedServer() const {
511   if(_lastUsedServerIndex < serverList().count())
512     return serverList()[_lastUsedServerIndex];
513
514   if(!serverList().isEmpty())
515     return serverList()[0];
516
517   return Network::Server();
518 }
519
520 void CoreNetwork::requestConnect() const {
521   if(connectionState() != Disconnected) {
522     qWarning() << "Requesting connect while already being connected!";
523     return;
524   }
525   Network::requestConnect();
526 }
527
528 void CoreNetwork::requestDisconnect() const {
529   if(connectionState() == Disconnected) {
530     qWarning() << "Requesting disconnect while not being connected!";
531     return;
532   }
533   userInputHandler()->handleQuit(BufferInfo(), QString());
534 }
535
536 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
537   Network::Server currentServer = usedServer();
538   setNetworkInfo(info);
539   Core::updateNetwork(coreSession()->user(), info);
540
541   // the order of the servers might have changed,
542   // so we try to find the previously used server
543   _lastUsedServerIndex = 0;
544   for(int i = 0; i < serverList().count(); i++) {
545     Network::Server server = serverList()[i];
546     if(server.host == currentServer.host && server.port == currentServer.port) {
547       _lastUsedServerIndex = i;
548       break;
549     }
550   }
551 }