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