saner amount for cached ids (postgres only)
[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   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   QString nick;
337   if(identity->nicks().isEmpty()) {
338     nick = "quassel";
339     qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
340   } else {
341     nick = identity->nicks()[0];
342   }
343   putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
344   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
345 }
346
347 void CoreNetwork::socketDisconnected() {
348   disablePingTimeout();
349
350   _autoWhoCycleTimer.stop();
351   _autoWhoTimer.stop();
352   _autoWhoQueue.clear();
353   _autoWhoPending.clear();
354
355   _socketCloseTimer.stop();
356
357   _tokenBucketTimer.stop();
358
359   IrcUser *me_ = me();
360   if(me_) {
361     foreach(QString channel, me_->channels())
362       displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
363   }
364
365   setConnected(false);
366   emit disconnected(networkId());
367   if(_quitRequested) {
368     setConnectionState(Network::Disconnected);
369     Core::setNetworkConnected(userId(), networkId(), false);
370   } else if(_autoReconnectCount != 0) {
371     setConnectionState(Network::Reconnecting);
372     if(_autoReconnectCount == autoReconnectRetries())
373       doAutoReconnect(); // first try is immediate
374     else
375       _autoReconnectTimer.start();
376   }
377 }
378
379 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
380   Network::ConnectionState state;
381   switch(socketState) {
382     case QAbstractSocket::UnconnectedState:
383       state = Network::Disconnected;
384       break;
385     case QAbstractSocket::HostLookupState:
386     case QAbstractSocket::ConnectingState:
387       state = Network::Connecting;
388       break;
389     case QAbstractSocket::ConnectedState:
390       state = Network::Initializing;
391       break;
392     case QAbstractSocket::ClosingState:
393       state = Network::Disconnecting;
394       break;
395     default:
396       state = Network::Disconnected;
397   }
398   setConnectionState(state);
399 }
400
401 void CoreNetwork::networkInitialized() {
402   setConnectionState(Network::Initialized);
403   setConnected(true);
404   _quitRequested = false;
405
406   if(useAutoReconnect()) {
407     // reset counter
408     _autoReconnectCount = autoReconnectRetries();
409   }
410
411   // restore away state
412   QString awayMsg = Core::awayMessage(userId(), networkId());
413   if(!awayMsg.isEmpty())
414     userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
415
416   // restore old user modes if server default mode is set.
417   IrcUser *me_ = me();
418   if(me_) {
419     if(!me_->userModes().isEmpty()) {
420       restoreUserModes();
421     } else {
422       connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
423       connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
424     }
425   }
426
427   sendPerform();
428
429   enablePingTimeout();
430
431   if(_autoWhoEnabled) {
432     _autoWhoCycleTimer.start();
433     _autoWhoTimer.start();
434     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
435   }
436
437   Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
438   Core::setNetworkConnected(userId(), networkId(), true);
439 }
440
441 void CoreNetwork::sendPerform() {
442   BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
443
444   // do auto identify
445   if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
446     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
447   }
448
449   // send perform list
450   foreach(QString line, perform()) {
451     if(!line.isEmpty()) userInput(statusBuf, line);
452   }
453
454   // rejoin channels we've been in
455   if(rejoinChannels()) {
456     QStringList channels, keys;
457     foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
458       QString key = channelKey(chan);
459       if(!key.isEmpty()) {
460         channels.prepend(chan);
461         keys.prepend(key);
462       } else {
463         channels.append(chan);
464       }
465     }
466     QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
467     if(!joinString.isEmpty())
468       userInputHandler()->handleJoin(statusBuf, joinString);
469   }
470 }
471
472 void CoreNetwork::restoreUserModes() {
473   IrcUser *me_ = me();
474   Q_ASSERT(me_);
475
476   disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
477   disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
478
479   QString removeModes;
480   QString addModes = Core::userModes(userId(), networkId());
481   QString currentModes = me_->userModes();
482
483   removeModes = currentModes;
484   removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
485   addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
486
487   removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
488   addModes = QString("%1 +%2").arg(me_->nick(), addModes);
489   userInputHandler()->handleMode(BufferInfo(), removeModes);
490   userInputHandler()->handleMode(BufferInfo(), addModes);
491 }
492
493 void CoreNetwork::setUseAutoReconnect(bool use) {
494   Network::setUseAutoReconnect(use);
495   if(!use)
496     _autoReconnectTimer.stop();
497 }
498
499 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
500   Network::setAutoReconnectInterval(interval);
501   _autoReconnectTimer.setInterval(interval * 1000);
502 }
503
504 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
505   Network::setAutoReconnectRetries(retries);
506   if(_autoReconnectCount != 0) {
507     if(unlimitedReconnectRetries())
508       _autoReconnectCount = -1;
509     else
510       _autoReconnectCount = autoReconnectRetries();
511   }
512 }
513
514 void CoreNetwork::doAutoReconnect() {
515   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
516     qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
517     return;
518   }
519   if(_autoReconnectCount > 0)
520     _autoReconnectCount--;
521   connectToIrc(true);
522 }
523
524 void CoreNetwork::sendPing() {
525   uint now = QDateTime::currentDateTime().toTime_t();
526   if(_lastPingTime != 0 && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
527     // the second check compares the actual elapsed time since the last ping and the pingTimer interval
528     // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
529     // and unable to even handle a ping answer. So we ignore those misses.
530     disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingTimer.interval() / 1000), true /* withReconnect */);
531   } else {
532     _lastPingTime = now;
533     userInputHandler()->handlePing(BufferInfo(), QString());
534   }
535 }
536
537 void CoreNetwork::enablePingTimeout() {
538   resetPingTimeout();
539   _pingTimer.start();
540 }
541
542 void CoreNetwork::disablePingTimeout() {
543   _pingTimer.stop();
544   resetPingTimeout();
545 }
546
547 void CoreNetwork::sendAutoWho() {
548   // Don't send autowho if there are still some pending
549   if(_autoWhoPending.count())
550     return;
551
552   while(!_autoWhoQueue.isEmpty()) {
553     QString chan = _autoWhoQueue.takeFirst();
554     IrcChannel *ircchan = ircChannel(chan);
555     if(!ircchan) continue;
556     if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
557     _autoWhoPending[chan]++;
558     putRawLine("WHO " + serverEncode(chan));
559     if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
560       // Timer was stopped, means a new cycle is due immediately
561       _autoWhoCycleTimer.start();
562       startAutoWhoCycle();
563     }
564     break;
565   }
566 }
567
568 void CoreNetwork::startAutoWhoCycle() {
569   if(!_autoWhoQueue.isEmpty()) {
570     _autoWhoCycleTimer.stop();
571     return;
572   }
573   _autoWhoQueue = channels();
574 }
575
576 #ifdef HAVE_SSL
577 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
578   Q_UNUSED(sslErrors)
579   socket.ignoreSslErrors();
580   // TODO errorhandling
581 }
582 #endif  // HAVE_SSL
583
584 void CoreNetwork::fillBucketAndProcessQueue() {
585   if(_tokenBucket < _burstSize) {
586     _tokenBucket++;
587   }
588
589   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
590     writeToSocket(_msgQueue.takeFirst());
591   }
592 }
593
594 void CoreNetwork::writeToSocket(const QByteArray &data) {
595   socket.write(data);
596   socket.write("\r\n");
597   _tokenBucket--;
598 }
599
600 Network::Server CoreNetwork::usedServer() const {
601   if(_lastUsedServerIndex < serverList().count())
602     return serverList()[_lastUsedServerIndex];
603
604   if(!serverList().isEmpty())
605     return serverList()[0];
606
607   return Network::Server();
608 }
609
610 void CoreNetwork::requestConnect() const {
611   if(connectionState() != Disconnected) {
612     qWarning() << "Requesting connect while already being connected!";
613     return;
614   }
615   Network::requestConnect();
616 }
617
618 void CoreNetwork::requestDisconnect() const {
619   if(connectionState() == Disconnected) {
620     qWarning() << "Requesting disconnect while not being connected!";
621     return;
622   }
623   userInputHandler()->handleQuit(BufferInfo(), QString());
624 }
625
626 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
627   Network::Server currentServer = usedServer();
628   setNetworkInfo(info);
629   Core::updateNetwork(coreSession()->user(), info);
630
631   // the order of the servers might have changed,
632   // so we try to find the previously used server
633   _lastUsedServerIndex = 0;
634   for(int i = 0; i < serverList().count(); i++) {
635     Network::Server server = serverList()[i];
636     if(server.host == currentServer.host && server.port == currentServer.port) {
637       _lastUsedServerIndex = i;
638       break;
639     }
640   }
641 }