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