Prepend the mode of operation to showkey's output.
[quassel.git] / src / core / corenetwork.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2013 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)
314 {
315     if (target.isEmpty())
316         return 0;
317
318     if (!Cipher::neededFeaturesAvailable())
319         return 0;
320
321     CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
322     if (channel) {
323         return channel->cipher();
324     }
325     CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
326     if (user) {
327         return user->cipher();
328     } else if (!isChannelName(target)) {
329         return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
330     }
331     return 0;
332 }
333
334
335 QByteArray CoreNetwork::cipherKey(const QString &target) const
336 {
337     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
338     if (c)
339         return c->cipher()->key();
340
341     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
342     if (u)
343         return u->cipher()->key();
344
345     return QByteArray();
346 }
347
348
349 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
350 {
351     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
352     if (c) {
353         c->setEncrypted(c->cipher()->setKey(key));
354         return;
355     }
356
357     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
358     if (!u && !isChannelName(target))
359         u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
360
361     if (u) {
362         u->setEncrypted(u->cipher()->setKey(key));
363         return;
364     }
365 }
366
367
368 bool CoreNetwork::cipherUsesCBC(const QString &target)
369 {
370     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
371     if (c)
372         return c->cipher()->usesCBC();
373     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
374     if (u)
375         return u->cipher()->usesCBC();
376
377     return false;
378 }
379 #endif /* HAVE_QCA2 */
380
381 bool CoreNetwork::setAutoWhoDone(const QString &channel)
382 {
383     QString chan = channel.toLower();
384     if (_autoWhoPending.value(chan, 0) <= 0)
385         return false;
386     if (--_autoWhoPending[chan] <= 0)
387         _autoWhoPending.remove(chan);
388     return true;
389 }
390
391
392 void CoreNetwork::setMyNick(const QString &mynick)
393 {
394     Network::setMyNick(mynick);
395     if (connectionState() == Network::Initializing)
396         networkInitialized();
397 }
398
399
400 void CoreNetwork::socketHasData()
401 {
402     while (socket.canReadLine()) {
403         QByteArray s = socket.readLine();
404         s.chop(2);
405         NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
406 #if QT_VERSION >= 0x040700
407         event->setTimestamp(QDateTime::currentDateTimeUtc());
408 #else
409         event->setTimestamp(QDateTime::currentDateTime().toUTC());
410 #endif
411         emit newEvent(event);
412     }
413 }
414
415
416 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
417 {
418     if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
419         return;
420
421     _previousConnectionAttemptFailed = true;
422     qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
423     emit connectionError(socket.errorString());
424     displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
425     emitConnectionError(socket.errorString());
426     if (socket.state() < QAbstractSocket::ConnectedState) {
427         socketDisconnected();
428     }
429 }
430
431
432 void CoreNetwork::socketInitialized()
433 {
434     Server server = usedServer();
435 #ifdef HAVE_SSL
436     if (server.useSsl && !socket.isEncrypted())
437         return;
438 #endif
439
440     CoreIdentity *identity = identityPtr();
441     if (!identity) {
442         qCritical() << "Identity invalid!";
443         disconnectFromIrc();
444         return;
445     }
446
447     emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
448
449     // TokenBucket to avoid sending too much at once
450     _messageDelay = 2200;  // this seems to be a safe value (2.2 seconds delay)
451     _burstSize = 5;
452     _tokenBucket = _burstSize; // init with a full bucket
453     _tokenBucketTimer.start(_messageDelay);
454
455     if (networkInfo().useSasl) {
456         putRawLine(serverEncode(QString("CAP REQ :sasl")));
457     }
458     if (!server.password.isEmpty()) {
459         putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
460     }
461     QString nick;
462     if (identity->nicks().isEmpty()) {
463         nick = "quassel";
464         qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
465     }
466     else {
467         nick = identity->nicks()[0];
468     }
469     putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
470     putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
471 }
472
473
474 void CoreNetwork::socketDisconnected()
475 {
476     disablePingTimeout();
477     _msgQueue.clear();
478
479     _autoWhoCycleTimer.stop();
480     _autoWhoTimer.stop();
481     _autoWhoQueue.clear();
482     _autoWhoPending.clear();
483
484     _socketCloseTimer.stop();
485
486     _tokenBucketTimer.stop();
487
488     IrcUser *me_ = me();
489     if (me_) {
490         foreach(QString channel, me_->channels())
491         displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
492     }
493
494     setConnected(false);
495     emit disconnected(networkId());
496     emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
497     if (_quitRequested) {
498         _quitRequested = false;
499         setConnectionState(Network::Disconnected);
500         Core::setNetworkConnected(userId(), networkId(), false);
501     }
502     else if (_autoReconnectCount != 0) {
503         setConnectionState(Network::Reconnecting);
504         if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
505             doAutoReconnect();  // first try is immediate
506         else
507             _autoReconnectTimer.start();
508     }
509 }
510
511
512 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
513 {
514     Network::ConnectionState state;
515     switch (socketState) {
516     case QAbstractSocket::UnconnectedState:
517         state = Network::Disconnected;
518         break;
519     case QAbstractSocket::HostLookupState:
520     case QAbstractSocket::ConnectingState:
521         state = Network::Connecting;
522         break;
523     case QAbstractSocket::ConnectedState:
524         state = Network::Initializing;
525         break;
526     case QAbstractSocket::ClosingState:
527         state = Network::Disconnecting;
528         break;
529     default:
530         state = Network::Disconnected;
531     }
532     setConnectionState(state);
533 }
534
535
536 void CoreNetwork::networkInitialized()
537 {
538     setConnectionState(Network::Initialized);
539     setConnected(true);
540     _quitRequested = false;
541
542     if (useAutoReconnect()) {
543         // reset counter
544         _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
545     }
546
547     // restore away state
548     QString awayMsg = Core::awayMessage(userId(), networkId());
549     if (!awayMsg.isEmpty())
550         userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
551
552     sendPerform();
553
554     enablePingTimeout();
555
556     if (networkConfig()->autoWhoEnabled()) {
557         _autoWhoCycleTimer.start();
558         _autoWhoTimer.start();
559         startAutoWhoCycle(); // FIXME wait for autojoin to be completed
560     }
561
562     Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
563     Core::setNetworkConnected(userId(), networkId(), true);
564 }
565
566
567 void CoreNetwork::sendPerform()
568 {
569     BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
570
571     // do auto identify
572     if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
573         userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
574     }
575
576     // restore old user modes if server default mode is set.
577     IrcUser *me_ = me();
578     if (me_) {
579         if (!me_->userModes().isEmpty()) {
580             restoreUserModes();
581         }
582         else {
583             connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
584             connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
585         }
586     }
587
588     // send perform list
589     foreach(QString line, perform()) {
590         if (!line.isEmpty()) userInput(statusBuf, line);
591     }
592
593     // rejoin channels we've been in
594     if (rejoinChannels()) {
595         QStringList channels, keys;
596         foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
597             QString key = channelKey(chan);
598             if (!key.isEmpty()) {
599                 channels.prepend(chan);
600                 keys.prepend(key);
601             }
602             else {
603                 channels.append(chan);
604             }
605         }
606         QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
607         if (!joinString.isEmpty())
608             userInputHandler()->handleJoin(statusBuf, joinString);
609     }
610 }
611
612
613 void CoreNetwork::restoreUserModes()
614 {
615     IrcUser *me_ = me();
616     Q_ASSERT(me_);
617
618     disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
619     disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
620
621     QString modesDelta = Core::userModes(userId(), networkId());
622     QString currentModes = me_->userModes();
623
624     QString addModes, removeModes;
625     if (modesDelta.contains('-')) {
626         addModes = modesDelta.section('-', 0, 0);
627         removeModes = modesDelta.section('-', 1);
628     }
629     else {
630         addModes = modesDelta;
631     }
632
633     addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
634     if (currentModes.isEmpty())
635         removeModes = QString();
636     else
637         removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
638
639     if (addModes.isEmpty() && removeModes.isEmpty())
640         return;
641
642     if (!addModes.isEmpty())
643         addModes = '+' + addModes;
644     if (!removeModes.isEmpty())
645         removeModes = '-' + removeModes;
646
647     // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
648     putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
649 }
650
651
652 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
653 {
654     QString addModes;
655     QString removeModes;
656     bool addMode = true;
657
658     for (int i = 0; i < requestedModes.length(); i++) {
659         if (requestedModes[i] == '+') {
660             addMode = true;
661             continue;
662         }
663         if (requestedModes[i] == '-') {
664             addMode = false;
665             continue;
666         }
667         if (addMode) {
668             addModes += requestedModes[i];
669         }
670         else {
671             removeModes += requestedModes[i];
672         }
673     }
674
675     QString addModesOld = _requestedUserModes.section('-', 0, 0);
676     QString removeModesOld = _requestedUserModes.section('-', 1);
677
678     addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
679     addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
680     addModes += addModesOld;
681
682     removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
683     removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
684     removeModes += removeModesOld;
685
686     _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
687 }
688
689
690 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
691 {
692     QString persistentUserModes = Core::userModes(userId(), networkId());
693
694     QString requestedAdd = _requestedUserModes.section('-', 0, 0);
695     QString requestedRemove = _requestedUserModes.section('-', 1);
696
697     QString persistentAdd, persistentRemove;
698     if (persistentUserModes.contains('-')) {
699         persistentAdd = persistentUserModes.section('-', 0, 0);
700         persistentRemove = persistentUserModes.section('-', 1);
701     }
702     else {
703         persistentAdd = persistentUserModes;
704     }
705
706     // remove modes we didn't issue
707     if (requestedAdd.isEmpty())
708         addModes = QString();
709     else
710         addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
711
712     if (requestedRemove.isEmpty())
713         removeModes = QString();
714     else
715         removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
716
717     // deduplicate
718     persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
719     persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
720
721     // update
722     persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
723     persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
724
725     // update issued mode list
726     requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
727     requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
728     _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
729
730     persistentAdd += addModes;
731     persistentRemove += removeModes;
732     Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
733 }
734
735
736 void CoreNetwork::resetPersistentModes()
737 {
738     _requestedUserModes = QString('-');
739     Core::setUserModes(userId(), networkId(), QString());
740 }
741
742
743 void CoreNetwork::setUseAutoReconnect(bool use)
744 {
745     Network::setUseAutoReconnect(use);
746     if (!use)
747         _autoReconnectTimer.stop();
748 }
749
750
751 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
752 {
753     Network::setAutoReconnectInterval(interval);
754     _autoReconnectTimer.setInterval(interval * 1000);
755 }
756
757
758 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
759 {
760     Network::setAutoReconnectRetries(retries);
761     if (_autoReconnectCount != 0) {
762         if (unlimitedReconnectRetries())
763             _autoReconnectCount = -1;
764         else
765             _autoReconnectCount = autoReconnectRetries();
766     }
767 }
768
769
770 void CoreNetwork::doAutoReconnect()
771 {
772     if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
773         qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
774         return;
775     }
776     if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
777         _autoReconnectCount--;  // -2 means we delay the next reconnect
778     connectToIrc(true);
779 }
780
781
782 void CoreNetwork::sendPing()
783 {
784     uint now = QDateTime::currentDateTime().toTime_t();
785     if (_pingCount != 0) {
786         qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
787                  << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
788     }
789     if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
790         // the second check compares the actual elapsed time since the last ping and the pingTimer interval
791         // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
792         // and unable to even handle a ping answer. So we ignore those misses.
793         disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
794     }
795     else {
796         _lastPingTime = now;
797         _pingCount++;
798         userInputHandler()->handlePing(BufferInfo(), QString());
799     }
800 }
801
802
803 void CoreNetwork::enablePingTimeout(bool enable)
804 {
805     if (!enable)
806         disablePingTimeout();
807     else {
808         resetPingTimeout();
809         if (networkConfig()->pingTimeoutEnabled())
810             _pingTimer.start();
811     }
812 }
813
814
815 void CoreNetwork::disablePingTimeout()
816 {
817     _pingTimer.stop();
818     resetPingTimeout();
819 }
820
821
822 void CoreNetwork::setPingInterval(int interval)
823 {
824     _pingTimer.setInterval(interval * 1000);
825 }
826
827
828 /******** AutoWHO ********/
829
830 void CoreNetwork::startAutoWhoCycle()
831 {
832     if (!_autoWhoQueue.isEmpty()) {
833         _autoWhoCycleTimer.stop();
834         return;
835     }
836     _autoWhoQueue = channels();
837 }
838
839
840 void CoreNetwork::setAutoWhoDelay(int delay)
841 {
842     _autoWhoTimer.setInterval(delay * 1000);
843 }
844
845
846 void CoreNetwork::setAutoWhoInterval(int interval)
847 {
848     _autoWhoCycleTimer.setInterval(interval * 1000);
849 }
850
851
852 void CoreNetwork::setAutoWhoEnabled(bool enabled)
853 {
854     if (enabled && isConnected() && !_autoWhoTimer.isActive())
855         _autoWhoTimer.start();
856     else if (!enabled) {
857         _autoWhoTimer.stop();
858         _autoWhoCycleTimer.stop();
859     }
860 }
861
862
863 void CoreNetwork::sendAutoWho()
864 {
865     // Don't send autowho if there are still some pending
866     if (_autoWhoPending.count())
867         return;
868
869     while (!_autoWhoQueue.isEmpty()) {
870         QString chan = _autoWhoQueue.takeFirst();
871         IrcChannel *ircchan = ircChannel(chan);
872         if (!ircchan) continue;
873         if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
874             continue;
875         _autoWhoPending[chan]++;
876         putRawLine("WHO " + serverEncode(chan));
877         break;
878     }
879     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
880         // Timer was stopped, means a new cycle is due immediately
881         _autoWhoCycleTimer.start();
882         startAutoWhoCycle();
883     }
884 }
885
886
887 #ifdef HAVE_SSL
888 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
889 {
890     Q_UNUSED(sslErrors)
891     socket.ignoreSslErrors();
892     // TODO errorhandling
893 }
894
895
896 #endif  // HAVE_SSL
897
898 void CoreNetwork::fillBucketAndProcessQueue()
899 {
900     if (_tokenBucket < _burstSize) {
901         _tokenBucket++;
902     }
903
904     while (_msgQueue.size() > 0 && _tokenBucket > 0) {
905         writeToSocket(_msgQueue.takeFirst());
906     }
907 }
908
909
910 void CoreNetwork::writeToSocket(const QByteArray &data)
911 {
912     socket.write(data);
913     socket.write("\r\n");
914     _tokenBucket--;
915 }
916
917
918 Network::Server CoreNetwork::usedServer() const
919 {
920     if (_lastUsedServerIndex < serverList().count())
921         return serverList()[_lastUsedServerIndex];
922
923     if (!serverList().isEmpty())
924         return serverList()[0];
925
926     return Network::Server();
927 }
928
929
930 void CoreNetwork::requestConnect() const
931 {
932     if (connectionState() != Disconnected) {
933         qWarning() << "Requesting connect while already being connected!";
934         return;
935     }
936     QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
937 }
938
939
940 void CoreNetwork::requestDisconnect() const
941 {
942     if (connectionState() == Disconnected) {
943         qWarning() << "Requesting disconnect while not being connected!";
944         return;
945     }
946     userInputHandler()->handleQuit(BufferInfo(), QString());
947 }
948
949
950 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
951 {
952     Network::Server currentServer = usedServer();
953     setNetworkInfo(info);
954     Core::updateNetwork(coreSession()->user(), info);
955
956     // the order of the servers might have changed,
957     // so we try to find the previously used server
958     _lastUsedServerIndex = 0;
959     for (int i = 0; i < serverList().count(); i++) {
960         Network::Server server = serverList()[i];
961         if (server.host == currentServer.host && server.port == currentServer.port) {
962             _lastUsedServerIndex = i;
963             break;
964         }
965     }
966 }