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