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