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