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