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