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