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