Fix includes
[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)), Qt::BlockingQueuedConnection);
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   Server server = usedServer();
359 #ifdef HAVE_SSL
360   if(server.useSsl && !socket.isEncrypted())
361     return;
362 #endif
363
364   CoreIdentity *identity = identityPtr();
365   if(!identity) {
366     qCritical() << "Identity invalid!";
367     disconnectFromIrc();
368     return;
369   }
370
371   emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
372
373   // TokenBucket to avoid sending too much at once
374   _messageDelay = 2200;    // this seems to be a safe value (2.2 seconds delay)
375   _burstSize = 5;
376   _tokenBucket = _burstSize; // init with a full bucket
377   _tokenBucketTimer.start(_messageDelay);
378
379   if(networkInfo().useSasl) {
380     putRawLine(serverEncode(QString("CAP REQ :sasl")));
381   }
382   if(!server.password.isEmpty()) {
383     putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
384   }
385   QString nick;
386   if(identity->nicks().isEmpty()) {
387     nick = "quassel";
388     qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
389   } else {
390     nick = identity->nicks()[0];
391   }
392   putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
393   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
394 }
395
396 void CoreNetwork::socketDisconnected() {
397   disablePingTimeout();
398   _msgQueue.clear();
399
400   _autoWhoCycleTimer.stop();
401   _autoWhoTimer.stop();
402   _autoWhoQueue.clear();
403   _autoWhoPending.clear();
404
405   _socketCloseTimer.stop();
406
407   _tokenBucketTimer.stop();
408
409   IrcUser *me_ = me();
410   if(me_) {
411     foreach(QString channel, me_->channels())
412       displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
413   }
414
415   setConnected(false);
416   emit disconnected(networkId());
417   emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
418   if(_quitRequested) {
419     _quitRequested = false;
420     setConnectionState(Network::Disconnected);
421     Core::setNetworkConnected(userId(), networkId(), false);
422   } else if(_autoReconnectCount != 0) {
423     setConnectionState(Network::Reconnecting);
424     if(_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
425       doAutoReconnect(); // first try is immediate
426     else
427       _autoReconnectTimer.start();
428   }
429 }
430
431 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
432   Network::ConnectionState state;
433   switch(socketState) {
434     case QAbstractSocket::UnconnectedState:
435       state = Network::Disconnected;
436       break;
437     case QAbstractSocket::HostLookupState:
438     case QAbstractSocket::ConnectingState:
439       state = Network::Connecting;
440       break;
441     case QAbstractSocket::ConnectedState:
442       state = Network::Initializing;
443       break;
444     case QAbstractSocket::ClosingState:
445       state = Network::Disconnecting;
446       break;
447     default:
448       state = Network::Disconnected;
449   }
450   setConnectionState(state);
451 }
452
453 void CoreNetwork::networkInitialized() {
454   setConnectionState(Network::Initialized);
455   setConnected(true);
456   _quitRequested = false;
457
458   if(useAutoReconnect()) {
459     // reset counter
460     _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
461   }
462
463   // restore away state
464   QString awayMsg = Core::awayMessage(userId(), networkId());
465   if(!awayMsg.isEmpty())
466     userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
467
468   sendPerform();
469
470   enablePingTimeout();
471
472   if(networkConfig()->autoWhoEnabled()) {
473     _autoWhoCycleTimer.start();
474     _autoWhoTimer.start();
475     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
476   }
477
478   Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
479   Core::setNetworkConnected(userId(), networkId(), true);
480 }
481
482 void CoreNetwork::sendPerform() {
483   BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
484
485   // do auto identify
486   if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
487     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
488   }
489
490   // restore old user modes if server default mode is set.
491   IrcUser *me_ = me();
492   if(me_) {
493     if(!me_->userModes().isEmpty()) {
494       restoreUserModes();
495     } else {
496       connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
497       connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
498     }
499   }
500
501   // send perform list
502   foreach(QString line, perform()) {
503     if(!line.isEmpty()) userInput(statusBuf, line);
504   }
505
506   // rejoin channels we've been in
507   if(rejoinChannels()) {
508     QStringList channels, keys;
509     foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
510       QString key = channelKey(chan);
511       if(!key.isEmpty()) {
512         channels.prepend(chan);
513         keys.prepend(key);
514       } else {
515         channels.append(chan);
516       }
517     }
518     QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
519     if(!joinString.isEmpty())
520       userInputHandler()->handleJoin(statusBuf, joinString);
521   }
522 }
523
524 void CoreNetwork::restoreUserModes() {
525   IrcUser *me_ = me();
526   Q_ASSERT(me_);
527
528   disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
529   disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
530
531   QString modesDelta = Core::userModes(userId(), networkId());
532   QString currentModes = me_->userModes();
533
534   QString addModes, removeModes;
535   if(modesDelta.contains('-')) {
536     addModes = modesDelta.section('-', 0, 0);
537     removeModes = modesDelta.section('-', 1);
538   } else {
539     addModes = modesDelta;
540   }
541
542
543   addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
544   if(currentModes.isEmpty())
545     removeModes = QString();
546   else
547     removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
548
549   if(addModes.isEmpty() && removeModes.isEmpty())
550     return;
551
552   if(!addModes.isEmpty())
553     addModes = '+' + addModes;
554   if(!removeModes.isEmpty())
555     removeModes = '-' + removeModes;
556
557   // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
558   putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
559 }
560
561 void CoreNetwork::updateIssuedModes(const QString &requestedModes) {
562   QString addModes;
563   QString removeModes;
564   bool addMode = true;
565
566   for(int i = 0; i < requestedModes.length(); i++) {
567     if(requestedModes[i] == '+') {
568       addMode = true;
569       continue;
570     }
571     if(requestedModes[i] == '-') {
572       addMode = false;
573       continue;
574     }
575     if(addMode) {
576       addModes += requestedModes[i];
577     } else {
578       removeModes += requestedModes[i];
579     }
580   }
581
582
583   QString addModesOld = _requestedUserModes.section('-', 0, 0);
584   QString removeModesOld = _requestedUserModes.section('-', 1);
585
586   addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
587   addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
588   addModes += addModesOld;
589
590   removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
591   removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
592   removeModes += removeModesOld;
593
594   _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
595 }
596
597 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) {
598   QString persistentUserModes = Core::userModes(userId(), networkId());
599
600   QString requestedAdd = _requestedUserModes.section('-', 0, 0);
601   QString requestedRemove = _requestedUserModes.section('-', 1);
602
603   QString persistentAdd, persistentRemove;
604   if(persistentUserModes.contains('-')) {
605     persistentAdd = persistentUserModes.section('-', 0, 0);
606     persistentRemove = persistentUserModes.section('-', 1);
607   } else {
608     persistentAdd = persistentUserModes;
609   }
610
611   // remove modes we didn't issue
612   if(requestedAdd.isEmpty())
613     addModes = QString();
614   else
615     addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
616
617   if(requestedRemove.isEmpty())
618     removeModes = QString();
619   else
620     removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
621
622   // deduplicate
623   persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
624   persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
625
626   // update
627   persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
628   persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
629
630   // update issued mode list
631   requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
632   requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
633   _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
634
635   persistentAdd += addModes;
636   persistentRemove += removeModes;
637   Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
638 }
639
640 void CoreNetwork::resetPersistentModes() {
641   _requestedUserModes = QString('-');
642   Core::setUserModes(userId(), networkId(), QString());
643 }
644
645 void CoreNetwork::setUseAutoReconnect(bool use) {
646   Network::setUseAutoReconnect(use);
647   if(!use)
648     _autoReconnectTimer.stop();
649 }
650
651 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
652   Network::setAutoReconnectInterval(interval);
653   _autoReconnectTimer.setInterval(interval * 1000);
654 }
655
656 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
657   Network::setAutoReconnectRetries(retries);
658   if(_autoReconnectCount != 0) {
659     if(unlimitedReconnectRetries())
660       _autoReconnectCount = -1;
661     else
662       _autoReconnectCount = autoReconnectRetries();
663   }
664 }
665
666 void CoreNetwork::doAutoReconnect() {
667   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
668     qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
669     return;
670   }
671   if(_autoReconnectCount > 0 || _autoReconnectCount == -1)
672     _autoReconnectCount--; // -2 means we delay the next reconnect
673   connectToIrc(true);
674 }
675
676 void CoreNetwork::sendPing() {
677   uint now = QDateTime::currentDateTime().toTime_t();
678   if(_pingCount != 0) {
679     qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
680              << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
681   }
682   if((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
683     // the second check compares the actual elapsed time since the last ping and the pingTimer interval
684     // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
685     // and unable to even handle a ping answer. So we ignore those misses.
686     disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
687   } else {
688     _lastPingTime = now;
689     _pingCount++;
690     userInputHandler()->handlePing(BufferInfo(), QString());
691   }
692 }
693
694 void CoreNetwork::enablePingTimeout(bool enable) {
695   if(!enable)
696     disablePingTimeout();
697   else {
698     resetPingTimeout();
699     if(networkConfig()->pingTimeoutEnabled())
700       _pingTimer.start();
701   }
702 }
703
704 void CoreNetwork::disablePingTimeout() {
705   _pingTimer.stop();
706   resetPingTimeout();
707 }
708
709 void CoreNetwork::setPingInterval(int interval) {
710   _pingTimer.setInterval(interval * 1000);
711 }
712
713 /******** AutoWHO ********/
714
715 void CoreNetwork::startAutoWhoCycle() {
716   if(!_autoWhoQueue.isEmpty()) {
717     _autoWhoCycleTimer.stop();
718     return;
719   }
720   _autoWhoQueue = channels();
721 }
722
723 void CoreNetwork::setAutoWhoDelay(int delay) {
724   _autoWhoTimer.setInterval(delay * 1000);
725 }
726
727 void CoreNetwork::setAutoWhoInterval(int interval) {
728   _autoWhoCycleTimer.setInterval(interval * 1000);
729 }
730
731 void CoreNetwork::setAutoWhoEnabled(bool enabled) {
732   if(enabled && isConnected() && !_autoWhoTimer.isActive())
733     _autoWhoTimer.start();
734   else if(!enabled) {
735     _autoWhoTimer.stop();
736     _autoWhoCycleTimer.stop();
737   }
738 }
739
740 void CoreNetwork::sendAutoWho() {
741   // Don't send autowho if there are still some pending
742   if(_autoWhoPending.count())
743     return;
744
745   while(!_autoWhoQueue.isEmpty()) {
746     QString chan = _autoWhoQueue.takeFirst();
747     IrcChannel *ircchan = ircChannel(chan);
748     if(!ircchan) continue;
749     if(networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
750       continue;
751     _autoWhoPending[chan]++;
752     putRawLine("WHO " + serverEncode(chan));
753     break;
754   }
755   if(_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
756     // Timer was stopped, means a new cycle is due immediately
757     _autoWhoCycleTimer.start();
758     startAutoWhoCycle();
759   }
760 }
761
762 #ifdef HAVE_SSL
763 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
764   Q_UNUSED(sslErrors)
765   socket.ignoreSslErrors();
766   // TODO errorhandling
767 }
768 #endif  // HAVE_SSL
769
770 void CoreNetwork::fillBucketAndProcessQueue() {
771   if(_tokenBucket < _burstSize) {
772     _tokenBucket++;
773   }
774
775   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
776     writeToSocket(_msgQueue.takeFirst());
777   }
778 }
779
780 void CoreNetwork::writeToSocket(const QByteArray &data) {
781   socket.write(data);
782   socket.write("\r\n");
783   _tokenBucket--;
784 }
785
786 Network::Server CoreNetwork::usedServer() const {
787   if(_lastUsedServerIndex < serverList().count())
788     return serverList()[_lastUsedServerIndex];
789
790   if(!serverList().isEmpty())
791     return serverList()[0];
792
793   return Network::Server();
794 }
795
796 void CoreNetwork::requestConnect() const {
797   if(connectionState() != Disconnected) {
798     qWarning() << "Requesting connect while already being connected!";
799     return;
800   }
801   QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
802 }
803
804 void CoreNetwork::requestDisconnect() const {
805   if(connectionState() == Disconnected) {
806     qWarning() << "Requesting disconnect while not being connected!";
807     return;
808   }
809   userInputHandler()->handleQuit(BufferInfo(), QString());
810 }
811
812 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
813   Network::Server currentServer = usedServer();
814   setNetworkInfo(info);
815   Core::updateNetwork(coreSession()->user(), info);
816
817   // the order of the servers might have changed,
818   // so we try to find the previously used server
819   _lastUsedServerIndex = 0;
820   for(int i = 0; i < serverList().count(); i++) {
821     Network::Server server = serverList()[i];
822     if(server.host == currentServer.host && server.port == currentServer.port) {
823       _lastUsedServerIndex = i;
824       break;
825     }
826   }
827 }