3d20faf4b6c783f590d6c43020d923d14d586c02
[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 "coreidentity.h"
25 #include "corenetworkconfig.h"
26 #include "coresession.h"
27 #include "coreuserinputhandler.h"
28 #include "networkevent.h"
29
30 INIT_SYNCABLE_OBJECT(CoreNetwork)
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32   : Network(networkid, session),
33     _coreSession(session),
34     _userInputHandler(new CoreUserInputHandler(this)),
35     _autoReconnectCount(0),
36     _quitRequested(false),
37
38     _previousConnectionAttemptFailed(false),
39     _lastUsedServerIndex(0),
40
41     _lastPingTime(0),
42     _pingCount(0),
43    _requestedUserModes('-')
44 {
45   _autoReconnectTimer.setSingleShot(true);
46   _socketCloseTimer.setSingleShot(true);
47   connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
48
49   setPingInterval(networkConfig()->pingInterval());
50   connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
51
52   setAutoWhoDelay(networkConfig()->autoWhoDelay());
53   setAutoWhoInterval(networkConfig()->autoWhoInterval());
54
55   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
56   foreach(QString chan, channels.keys()) {
57     _channelKeys[chan.toLower()] = channels[chan];
58   }
59
60   connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
61   connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
62   connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
63   connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
64   connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
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
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   connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
81
82   if(Quassel::isOptionSet("oidentd")) {
83     connect(this, SIGNAL(socketInitialized(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)));
84     connect(this, SIGNAL(socketDisconnected(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*,QHostAddress,quint16,QHostAddress,quint16)));
85   }
86 }
87
88 CoreNetwork::~CoreNetwork() {
89   if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
90     disconnectFromIrc(false);      // clean up, but this does not count as requested disconnect!
91   disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
92   delete _userInputHandler;
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   }
204
205   if(reason.isEmpty() && identityPtr())
206     _quitReason = identityPtr()->quitReason();
207   else
208     _quitReason = reason;
209
210   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
211   switch(socket.state()) {
212   case QAbstractSocket::ConnectedState:
213     userInputHandler()->issueQuit(_quitReason);
214     if(requested || withReconnect) {
215       // the irc server has 10 seconds to close the socket
216       _socketCloseTimer.start(10000);
217       break;
218     }
219   default:
220     socket.close();
221     socketDisconnected();
222   }
223 }
224
225 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
226   userInputHandler()->handleUserInput(buf, msg);
227 }
228
229 void CoreNetwork::putRawLine(QByteArray s) {
230   if(_tokenBucket > 0)
231     writeToSocket(s);
232   else
233     _msgQueue.append(s);
234 }
235
236 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix) {
237   QByteArray msg;
238
239   if(!prefix.isEmpty())
240     msg += ":" + prefix + " ";
241   msg += cmd.toUpper().toAscii();
242
243   for(int i = 0; i < params.size() - 1; i++) {
244     msg += " " + params[i];
245   }
246   if(!params.isEmpty())
247     msg += " :" + params.last();
248
249   putRawLine(msg);
250 }
251
252 void CoreNetwork::setChannelJoined(const QString &channel) {
253   _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
254
255   Core::setChannelPersistent(userId(), networkId(), channel, true);
256   Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
257 }
258
259 void CoreNetwork::setChannelParted(const QString &channel) {
260   removeChannelKey(channel);
261   _autoWhoQueue.removeAll(channel.toLower());
262   _autoWhoPending.remove(channel.toLower());
263
264   Core::setChannelPersistent(userId(), networkId(), channel, false);
265 }
266
267 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
268   if(key.isEmpty()) {
269     removeChannelKey(channel);
270   } else {
271     _channelKeys[channel.toLower()] = key;
272   }
273 }
274
275 void CoreNetwork::removeChannelKey(const QString &channel) {
276   _channelKeys.remove(channel.toLower());
277 }
278
279 #ifdef HAVE_QCA2
280 Cipher *CoreNetwork::cipher(const QString &target) const {
281   if(target.isEmpty())
282     return 0;
283
284   if(!Cipher::neededFeaturesAvailable())
285     return 0;
286
287   QByteArray key = cipherKey(target);
288   if(key.isEmpty())
289     return 0;
290
291   CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
292   if(channel) {
293     if(channel->cipher()->setKey(key))
294       return channel->cipher();
295   } else {
296     CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
297     if(user && user->cipher()->setKey(key))
298       return user->cipher();
299   }
300   return 0;
301 }
302
303 QByteArray CoreNetwork::cipherKey(const QString &recipient) const {
304   return _cipherKeys.value(recipient.toLower(), QByteArray());
305 }
306
307 void CoreNetwork::setCipherKey(const QString &recipient, const QByteArray &key) {
308   if(!key.isEmpty())
309     _cipherKeys[recipient.toLower()] = key;
310   else
311     _cipherKeys.remove(recipient.toLower());
312 }
313 #endif /* HAVE_QCA2 */
314
315 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
316   QString chan = channel.toLower();
317   if(_autoWhoPending.value(chan, 0) <= 0)
318     return false;
319   if(--_autoWhoPending[chan] <= 0)
320     _autoWhoPending.remove(chan);
321   return true;
322 }
323
324 void CoreNetwork::setMyNick(const QString &mynick) {
325   Network::setMyNick(mynick);
326   if(connectionState() == Network::Initializing)
327     networkInitialized();
328 }
329
330 void CoreNetwork::socketHasData() {
331   while(socket.canReadLine()) {
332     QByteArray s = socket.readLine().trimmed();
333     NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
334 #if QT_VERSION >= 0x040700
335     event->setTimestamp(QDateTime::currentDateTimeUtc());
336 #else
337     event->setTimestamp(QDateTime::currentDateTime().toUTC());
338 #endif
339     emit newEvent(event);
340   }
341 }
342
343 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
344   if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
345     return;
346
347   _previousConnectionAttemptFailed = true;
348   qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
349   emit connectionError(socket.errorString());
350   displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
351   emitConnectionError(socket.errorString());
352   if(socket.state() < QAbstractSocket::ConnectedState) {
353     socketDisconnected();
354   }
355 }
356
357 void CoreNetwork::socketInitialized() {
358 qDebug() << "connected()";
359   Server server = usedServer();
360 #ifdef HAVE_SSL
361   if(server.useSsl && !socket.isEncrypted())
362     return;
363 #endif
364
365   CoreIdentity *identity = identityPtr();
366   if(!identity) {
367     qCritical() << "Identity invalid!";
368     disconnectFromIrc();
369     return;
370   }
371
372   emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
373
374   // TokenBucket to avoid sending too much at once
375   _messageDelay = 2200;    // this seems to be a safe value (2.2 seconds delay)
376   _burstSize = 5;
377   _tokenBucket = _burstSize; // init with a full bucket
378   _tokenBucketTimer.start(_messageDelay);
379
380   if(networkInfo().useSasl) {
381     putRawLine(serverEncode(QString("CAP REQ :sasl")));
382   }
383   if(!server.password.isEmpty()) {
384     putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
385   }
386   QString nick;
387   if(identity->nicks().isEmpty()) {
388     nick = "quassel";
389     qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
390   } else {
391     nick = identity->nicks()[0];
392   }
393   putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
394   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
395 }
396
397 void CoreNetwork::socketDisconnected() {
398   disablePingTimeout();
399   _msgQueue.clear();
400
401   _autoWhoCycleTimer.stop();
402   _autoWhoTimer.stop();
403   _autoWhoQueue.clear();
404   _autoWhoPending.clear();
405
406   _socketCloseTimer.stop();
407
408   _tokenBucketTimer.stop();
409
410   IrcUser *me_ = me();
411   if(me_) {
412     foreach(QString channel, me_->channels())
413       displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
414   }
415
416   setConnected(false);
417   emit disconnected(networkId());
418   emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
419   if(_quitRequested) {
420     _quitRequested = false;
421     setConnectionState(Network::Disconnected);
422     Core::setNetworkConnected(userId(), networkId(), false);
423   } else if(_autoReconnectCount != 0) {
424     setConnectionState(Network::Reconnecting);
425     if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
426       doAutoReconnect(); // first try is immediate
427     else
428       _autoReconnectTimer.start();
429   }
430 }
431
432 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
433   Network::ConnectionState state;
434   switch(socketState) {
435     case QAbstractSocket::UnconnectedState:
436       state = Network::Disconnected;
437       break;
438     case QAbstractSocket::HostLookupState:
439     case QAbstractSocket::ConnectingState:
440       state = Network::Connecting;
441       break;
442     case QAbstractSocket::ConnectedState:
443       state = Network::Initializing;
444       break;
445     case QAbstractSocket::ClosingState:
446       state = Network::Disconnecting;
447       break;
448     default:
449       state = Network::Disconnected;
450   }
451   setConnectionState(state);
452 }
453
454 void CoreNetwork::networkInitialized() {
455   setConnectionState(Network::Initialized);
456   setConnected(true);
457   _quitRequested = false;
458
459   if(useAutoReconnect()) {
460     // reset counter
461     _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
462   }
463
464   // restore away state
465   QString awayMsg = Core::awayMessage(userId(), networkId());
466   if(!awayMsg.isEmpty())
467     userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
468
469   sendPerform();
470
471   enablePingTimeout();
472
473   if(networkConfig()->autoWhoEnabled()) {
474     _autoWhoCycleTimer.start();
475     _autoWhoTimer.start();
476     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
477   }
478
479   Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
480   Core::setNetworkConnected(userId(), networkId(), true);
481 }
482
483 void CoreNetwork::sendPerform() {
484   BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
485
486   // do auto identify
487   if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
488     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
489   }
490
491   // restore old user modes if server default mode is set.
492   IrcUser *me_ = me();
493   if(me_) {
494     if(!me_->userModes().isEmpty()) {
495       restoreUserModes();
496     } else {
497       connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
498       connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
499     }
500   }
501
502   // send perform list
503   foreach(QString line, perform()) {
504     if(!line.isEmpty()) userInput(statusBuf, line);
505   }
506
507   // rejoin channels we've been in
508   if(rejoinChannels()) {
509     QStringList channels, keys;
510     foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
511       QString key = channelKey(chan);
512       if(!key.isEmpty()) {
513         channels.prepend(chan);
514         keys.prepend(key);
515       } else {
516         channels.append(chan);
517       }
518     }
519     QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
520     if(!joinString.isEmpty())
521       userInputHandler()->handleJoin(statusBuf, joinString);
522   }
523 }
524
525 void CoreNetwork::restoreUserModes() {
526   IrcUser *me_ = me();
527   Q_ASSERT(me_);
528
529   disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
530   disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
531
532   QString modesDelta = Core::userModes(userId(), networkId());
533   QString currentModes = me_->userModes();
534
535   QString addModes, removeModes;
536   if(modesDelta.contains('-')) {
537     addModes = modesDelta.section('-', 0, 0);
538     removeModes = modesDelta.section('-', 1);
539   } else {
540     addModes = modesDelta;
541   }
542
543
544   addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
545   if(currentModes.isEmpty())
546     removeModes = QString();
547   else
548     removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
549
550   if(addModes.isEmpty() && removeModes.isEmpty())
551     return;
552
553   if(!addModes.isEmpty())
554     addModes = '+' + addModes;
555   if(!removeModes.isEmpty())
556     removeModes = '-' + removeModes;
557
558   // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
559   putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
560 }
561
562 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
563   QString addModes;
564   QString removeModes;
565   bool addMode = true;
566
567   for(int i = 0; i < requestedModes.length(); i++) {
568     if(requestedModes[i] == '+') {
569       addMode = true;
570       continue;
571     }
572     if(requestedModes[i] == '-') {
573       addMode = false;
574       continue;
575     }
576     if(addMode) {
577       addModes += requestedModes[i];
578     } else {
579       removeModes += requestedModes[i];
580     }
581   }
582
583
584   QString addModesOld = _requestedUserModes.section('-', 0, 0);
585   QString removeModesOld = _requestedUserModes.section('-', 1);
586
587   addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
588   addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
589   addModes += addModesOld;
590
591   removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
592   removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
593   removeModes += removeModesOld;
594
595   _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
596 }
597
598 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
599   QString persistentUserModes = Core::userModes(userId(), networkId());
600
601   QString requestedAdd = _requestedUserModes.section('-', 0, 0);
602   QString requestedRemove = _requestedUserModes.section('-', 1);
603
604   QString persistentAdd, persistentRemove;
605   if(persistentUserModes.contains('-')) {
606     persistentAdd = persistentUserModes.section('-', 0, 0);
607     persistentRemove = persistentUserModes.section('-', 1);
608   } else {
609     persistentAdd = persistentUserModes;
610   }
611
612   // remove modes we didn't issue
613   if(requestedAdd.isEmpty())
614     addModes = QString();
615   else
616     addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
617
618   if(requestedRemove.isEmpty())
619     removeModes = QString();
620   else
621     removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
622
623   // deduplicate
624   persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
625   persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
626
627   // update
628   persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
629   persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
630
631   // update issued mode list
632   requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
633   requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
634   _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
635
636   persistentAdd += addModes;
637   persistentRemove += removeModes;
638   Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
639 }
640
641 void CoreNetwork::resetPersistentModes() {
642   _requestedUserModes = QString('-');
643   Core::setUserModes(userId(), networkId(), QString());
644 }
645
646 void CoreNetwork::setUseAutoReconnect(bool use) {
647   Network::setUseAutoReconnect(use);
648   if(!use)
649     _autoReconnectTimer.stop();
650 }
651
652 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
653   Network::setAutoReconnectInterval(interval);
654   _autoReconnectTimer.setInterval(interval * 1000);
655 }
656
657 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
658   Network::setAutoReconnectRetries(retries);
659   if(_autoReconnectCount != 0) {
660     if(unlimitedReconnectRetries())
661       _autoReconnectCount = -1;
662     else
663       _autoReconnectCount = autoReconnectRetries();
664   }
665 }
666
667 void CoreNetwork::doAutoReconnect() {
668   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
669     qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
670     return;
671   }
672   if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
673     _autoReconnectCount--; // -2 means we delay the next reconnect
674   connectToIrc(true);
675 }
676
677 void CoreNetwork::sendPing() {
678   uint now = QDateTime::currentDateTime().toTime_t();
679   if(_pingCount != 0) {
680     qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
681              << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
682   }
683   if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
684     // the second check compares the actual elapsed time since the last ping and the pingTimer interval
685     // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
686     // and unable to even handle a ping answer. So we ignore those misses.
687     disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
688   } else {
689     _lastPingTime = now;
690     _pingCount++;
691     userInputHandler()->handlePing(BufferInfo(), QString());
692   }
693 }
694
695 void CoreNetwork::enablePingTimeout(bool enable) {
696   if(!enable)
697     disablePingTimeout();
698   else {
699     resetPingTimeout();
700     if(networkConfig()->pingTimeoutEnabled())
701       _pingTimer.start();
702   }
703 }
704
705 void CoreNetwork::disablePingTimeout() {
706   _pingTimer.stop();
707   resetPingTimeout();
708 }
709
710 void CoreNetwork::setPingInterval(int interval) {
711   _pingTimer.setInterval(interval * 1000);
712 }
713
714 /******** AutoWHO ********/
715
716 void CoreNetwork::startAutoWhoCycle() {
717   if(!_autoWhoQueue.isEmpty()) {
718     _autoWhoCycleTimer.stop();
719     return;
720   }
721   _autoWhoQueue = channels();
722 }
723
724 void CoreNetwork::setAutoWhoDelay(int delay) {
725   _autoWhoTimer.setInterval(delay * 1000);
726 }
727
728 void CoreNetwork::setAutoWhoInterval(int interval) {
729   _autoWhoCycleTimer.setInterval(interval * 1000);
730 }
731
732 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
733   if(enabled && isConnected() && !_autoWhoTimer.isActive())
734     _autoWhoTimer.start();
735   else if(!enabled) {
736     _autoWhoTimer.stop();
737     _autoWhoCycleTimer.stop();
738   }
739 }
740
741 void CoreNetwork::sendAutoWho() {
742   // Don't send autowho if there are still some pending
743   if(_autoWhoPending.count())
744     return;
745
746   while(!_autoWhoQueue.isEmpty()) {
747     QString chan = _autoWhoQueue.takeFirst();
748     IrcChannel *ircchan = ircChannel(chan);
749     if(!ircchan) continue;
750     if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
751       continue;
752     _autoWhoPending[chan]++;
753     putRawLine("WHO " + serverEncode(chan));
754     break;
755   }
756   if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
757     // Timer was stopped, means a new cycle is due immediately
758     _autoWhoCycleTimer.start();
759     startAutoWhoCycle();
760   }
761 }
762
763 #ifdef HAVE_SSL
764 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
765   Q_UNUSED(sslErrors)
766   socket.ignoreSslErrors();
767   // TODO errorhandling
768 }
769 #endif  // HAVE_SSL
770
771 void CoreNetwork::fillBucketAndProcessQueue() {
772   if(_tokenBucket < _burstSize) {
773     _tokenBucket++;
774   }
775
776   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
777     writeToSocket(_msgQueue.takeFirst());
778   }
779 }
780
781 void CoreNetwork::writeToSocket(const QByteArray &data) {
782   socket.write(data);
783   socket.write("\r\n");
784   _tokenBucket--;
785 }
786
787 Network::Server CoreNetwork::usedServer() const {
788   if(_lastUsedServerIndex < serverList().count())
789     return serverList()[_lastUsedServerIndex];
790
791   if(!serverList().isEmpty())
792     return serverList()[0];
793
794   return Network::Server();
795 }
796
797 void CoreNetwork::requestConnect() const {
798   if(connectionState() != Disconnected) {
799     qWarning() << "Requesting connect while already being connected!";
800     return;
801   }
802   QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
803 }
804
805 void CoreNetwork::requestDisconnect() const {
806   if(connectionState() == Disconnected) {
807     qWarning() << "Requesting disconnect while not being connected!";
808     return;
809   }
810   userInputHandler()->handleQuit(BufferInfo(), QString());
811 }
812
813 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
814   Network::Server currentServer = usedServer();
815   setNetworkInfo(info);
816   Core::updateNetwork(coreSession()->user(), info);
817
818   // the order of the servers might have changed,
819   // so we try to find the previously used server
820   _lastUsedServerIndex = 0;
821   for(int i = 0; i < serverList().count(); i++) {
822     Network::Server server = serverList()[i];
823     if(server.host == currentServer.host && server.port == currentServer.port) {
824       _lastUsedServerIndex = i;
825       break;
826     }
827   }
828 }