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