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