e0332096fcacde665aceb9d12fa270eeeb2b9d18
[quassel.git] / src / core / corenetwork.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 <QDebug>
24 #include <QHostInfo>
25
26 #include "core.h"
27 #include "coreidentity.h"
28 #include "corenetworkconfig.h"
29 #include "coresession.h"
30 #include "coreuserinputhandler.h"
31 #include "networkevent.h"
32
33 // IRCv3 capabilities
34 #include "irccap.h"
35
36 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
37     : Network(networkid, session),
38     _coreSession(session),
39     _userInputHandler(new CoreUserInputHandler(this)),
40     _autoReconnectCount(0),
41     _quitRequested(false),
42     _disconnectExpected(false),
43
44     _previousConnectionAttemptFailed(false),
45     _lastUsedServerIndex(0),
46
47     _requestedUserModes('-')
48 {
49     // Check if raw IRC logging is enabled
50     _debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
51     _debugLogRawNetId = Quassel::optionValue("debug-irc-id").toInt();
52
53     _autoReconnectTimer.setSingleShot(true);
54     connect(&_socketCloseTimer, &QTimer::timeout, this, &CoreNetwork::socketCloseTimeout);
55
56     setPingInterval(networkConfig()->pingInterval());
57     connect(&_pingTimer, &QTimer::timeout, this, &CoreNetwork::sendPing);
58
59     setAutoWhoDelay(networkConfig()->autoWhoDelay());
60     setAutoWhoInterval(networkConfig()->autoWhoInterval());
61
62     QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
63     foreach(QString chan, channels.keys()) {
64         _channelKeys[chan.toLower()] = channels[chan];
65     }
66
67     QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
68     foreach(QString buffer, bufferCiphers.keys()) {
69         storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
70     }
71
72     connect(networkConfig(), &NetworkConfig::pingTimeoutEnabledSet, this, &CoreNetwork::enablePingTimeout);
73     connect(networkConfig(), &NetworkConfig::pingIntervalSet, this, &CoreNetwork::setPingInterval);
74     connect(networkConfig(), &NetworkConfig::autoWhoEnabledSet, this, &CoreNetwork::setAutoWhoEnabled);
75     connect(networkConfig(), &NetworkConfig::autoWhoIntervalSet, this, &CoreNetwork::setAutoWhoInterval);
76     connect(networkConfig(), &NetworkConfig::autoWhoDelaySet, this, &CoreNetwork::setAutoWhoDelay);
77
78     connect(&_autoReconnectTimer, &QTimer::timeout, this, &CoreNetwork::doAutoReconnect);
79     connect(&_autoWhoTimer, &QTimer::timeout, this, &CoreNetwork::sendAutoWho);
80     connect(&_autoWhoCycleTimer, &QTimer::timeout, this, &CoreNetwork::startAutoWhoCycle);
81     connect(&_tokenBucketTimer, &QTimer::timeout, this, &CoreNetwork::checkTokenBucket);
82
83     connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
84     connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
85     connect(&socket, &QAbstractSocket::stateChanged, this, &CoreNetwork::socketStateChanged);
86     connect(&socket, &QIODevice::readyRead, this, &CoreNetwork::socketHasData);
87 #ifdef HAVE_SSL
88     connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
89     connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
90 #endif
91     connect(this, &CoreNetwork::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
92
93     // Custom rate limiting
94     // These react to the user changing settings in the client
95     connect(this, &Network::useCustomMessageRateSet, this, &CoreNetwork::updateRateLimiting);
96     connect(this, &Network::messageRateBurstSizeSet, this, &CoreNetwork::updateRateLimiting);
97     connect(this, &Network::messageRateDelaySet, this, &CoreNetwork::updateRateLimiting);
98     connect(this, &Network::unlimitedMessageRateSet, this, &CoreNetwork::updateRateLimiting);
99
100     // IRCv3 capability handling
101     // These react to CAP messages from the server
102     connect(this, &Network::capAdded, this, &CoreNetwork::serverCapAdded);
103     connect(this, &Network::capAcknowledged, this, &CoreNetwork::serverCapAcknowledged);
104     connect(this, &Network::capRemoved, this, &CoreNetwork::serverCapRemoved);
105
106     if (Quassel::isOptionSet("oidentd")) {
107         connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
108                 Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Qt::BlockingQueuedConnection);
109         connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
110                 Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)));
111     }
112
113     if (Quassel::isOptionSet("ident-daemon")) {
114         connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
115                 Core::instance()->identServer(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Qt::BlockingQueuedConnection);
116         connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)),
117                 Core::instance()->identServer(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)));
118     }
119 }
120
121
122 CoreNetwork::~CoreNetwork()
123 {
124     // Ensure we don't get any more signals from the socket while shutting down
125     disconnect(&socket, nullptr, this, nullptr);
126     if (!forceDisconnect()) {
127         qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
128                       .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
129     }
130 }
131
132
133 bool CoreNetwork::forceDisconnect(int msecs)
134 {
135     if (socket.state() == QAbstractSocket::UnconnectedState) {
136         // Socket already disconnected.
137         return true;
138     }
139     // Request a socket-level disconnect if not already happened
140     socket.disconnectFromHost();
141     if (socket.state() != QAbstractSocket::UnconnectedState) {
142         return socket.waitForDisconnected(msecs);
143     }
144     return true;
145 }
146
147
148 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
149 {
150     if (!bufferName.isEmpty()) {
151         IrcChannel *channel = ircChannel(bufferName);
152         if (channel)
153             return channel->decodeString(string);
154     }
155     return decodeString(string);
156 }
157
158
159 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
160 {
161     IrcUser *user = ircUser(userNick);
162     if (user)
163         return user->decodeString(string);
164     return decodeString(string);
165 }
166
167
168 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
169 {
170     if (!bufferName.isEmpty()) {
171         IrcChannel *channel = ircChannel(bufferName);
172         if (channel)
173             return channel->encodeString(string);
174     }
175     return encodeString(string);
176 }
177
178
179 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
180 {
181     IrcUser *user = ircUser(userNick);
182     if (user)
183         return user->encodeString(string);
184     return encodeString(string);
185 }
186
187
188 void CoreNetwork::connectToIrc(bool reconnecting)
189 {
190     if (_shuttingDown) {
191         return;
192     }
193
194     if (Core::instance()->identServer()) {
195         _socketId = Core::instance()->identServer()->addWaitingSocket();
196     }
197
198     if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
199         _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
200         if (unlimitedReconnectRetries())
201             _autoReconnectCount = -1;
202         else
203             _autoReconnectCount = autoReconnectRetries();
204     }
205     if (serverList().isEmpty()) {
206         qWarning() << "Server list empty, ignoring connect request!";
207         return;
208     }
209     CoreIdentity *identity = identityPtr();
210     if (!identity) {
211         qWarning() << "Invalid identity configures, ignoring connect request!";
212         return;
213     }
214
215     // cleaning up old quit reason
216     _quitReason.clear();
217
218     // Reset capability negotiation tracking, also handling server changes during reconnect
219     _capsQueuedIndividual.clear();
220     _capsQueuedBundled.clear();
221     clearCaps();
222     _capNegotiationActive = false;
223     _capInitialNegotiationEnded = false;
224
225     // use a random server?
226     if (useRandomServer()) {
227         _lastUsedServerIndex = qrand() % serverList().size();
228     }
229     else if (_previousConnectionAttemptFailed) {
230         // cycle to next server if previous connection attempt failed
231         _previousConnectionAttemptFailed = false;
232         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
233         if (++_lastUsedServerIndex >= serverList().size()) {
234             _lastUsedServerIndex = 0;
235         }
236     }
237     else {
238         // Start out with the top server in the list
239         _lastUsedServerIndex = 0;
240     }
241
242     Server server = usedServer();
243     displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
244     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
245
246     if (server.useProxy) {
247         QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
248         socket.setProxy(proxy);
249     }
250     else {
251         socket.setProxy(QNetworkProxy::NoProxy);
252     }
253
254     enablePingTimeout();
255
256     // Reset tracking for valid timestamps in PONG replies
257     setPongTimestampValid(false);
258
259     // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
260     // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
261     if (! server.useProxy) {
262         //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
263         //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
264         QHostInfo::fromName(server.host);
265     }
266 #ifdef HAVE_SSL
267     if (server.useSsl) {
268         CoreIdentity *identity = identityPtr();
269         if (identity) {
270             socket.setLocalCertificate(identity->sslCert());
271             socket.setPrivateKey(identity->sslKey());
272         }
273         socket.connectToHostEncrypted(server.host, server.port);
274     }
275     else {
276         socket.connectToHost(server.host, server.port);
277     }
278 #else
279     socket.connectToHost(server.host, server.port);
280 #endif
281 }
282
283
284 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
285 {
286     // Disconnecting from the network, should expect a socket close or error
287     _disconnectExpected = true;
288     _quitRequested = requested; // see socketDisconnected();
289     if (!withReconnect) {
290         _autoReconnectTimer.stop();
291         _autoReconnectCount = 0; // prohibiting auto reconnect
292     }
293     disablePingTimeout();
294     _msgQueue.clear();
295
296     IrcUser *me_ = me();
297     if (me_) {
298         QString awayMsg;
299         if (me_->isAway())
300             awayMsg = me_->awayMessage();
301         Core::setAwayMessage(userId(), networkId(), awayMsg);
302     }
303
304     if (reason.isEmpty() && identityPtr())
305         _quitReason = identityPtr()->quitReason();
306     else
307         _quitReason = reason;
308
309     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
310     if (socket.state() == QAbstractSocket::UnconnectedState) {
311         socketDisconnected();
312     }
313     else {
314         if (socket.state() == QAbstractSocket::ConnectedState) {
315             // If shutting down, prioritize the QUIT command
316             userInputHandler()->issueQuit(_quitReason, _shuttingDown);
317         }
318         else {
319             socket.close();
320         }
321         if (socket.state() != QAbstractSocket::UnconnectedState) {
322             // Wait for up to 10 seconds for the socket to close cleanly, then it will be forcefully aborted
323             _socketCloseTimer.start(10000);
324         }
325     }
326 }
327
328
329 void CoreNetwork::socketCloseTimeout()
330 {
331     qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
332                   .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
333     socket.abort();
334 }
335
336
337 void CoreNetwork::shutdown()
338 {
339     _shuttingDown = true;
340     disconnectFromIrc(false, {}, false);
341 }
342
343
344 void CoreNetwork::userInput(BufferInfo buf, QString msg)
345 {
346     userInputHandler()->handleUserInput(buf, msg);
347 }
348
349
350 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
351 {
352     if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.size() == 0)) {
353         // If there's tokens remaining, ...
354         // Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
355         // Send the message now.
356         writeToSocket(s);
357     } else {
358         // Otherwise, queue the message for later
359         if (prepend) {
360             // Jump to the start, skipping other messages
361             _msgQueue.prepend(s);
362         } else {
363             // Add to back, waiting in order
364             _msgQueue.append(s);
365         }
366     }
367 }
368
369
370 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix, const bool prepend)
371 {
372     QByteArray msg;
373
374     if (!prefix.isEmpty())
375         msg += ":" + prefix + " ";
376     msg += cmd.toUpper().toLatin1();
377
378     for (int i = 0; i < params.size(); i++) {
379         msg += " ";
380
381         if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
382             msg += ":";
383
384         msg += params[i];
385     }
386
387     putRawLine(msg, prepend);
388 }
389
390
391 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix, const bool prependAll)
392 {
393     QListIterator<QList<QByteArray>> i(params);
394     while (i.hasNext()) {
395         QList<QByteArray> msg = i.next();
396         putCmd(cmd, msg, prefix, prependAll);
397     }
398 }
399
400
401 void CoreNetwork::setChannelJoined(const QString &channel)
402 {
403     queueAutoWhoOneshot(channel); // check this new channel first
404
405     Core::setChannelPersistent(userId(), networkId(), channel, true);
406     Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
407 }
408
409
410 void CoreNetwork::setChannelParted(const QString &channel)
411 {
412     removeChannelKey(channel);
413     _autoWhoQueue.removeAll(channel.toLower());
414     _autoWhoPending.remove(channel.toLower());
415
416     Core::setChannelPersistent(userId(), networkId(), channel, false);
417 }
418
419
420 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
421 {
422     if (key.isEmpty()) {
423         removeChannelKey(channel);
424     }
425     else {
426         _channelKeys[channel.toLower()] = key;
427     }
428 }
429
430
431 void CoreNetwork::removeChannelKey(const QString &channel)
432 {
433     _channelKeys.remove(channel.toLower());
434 }
435
436
437 #ifdef HAVE_QCA2
438 Cipher *CoreNetwork::cipher(const QString &target)
439 {
440     if (target.isEmpty())
441         return nullptr;
442
443     if (!Cipher::neededFeaturesAvailable())
444         return nullptr;
445
446     auto *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
447     if (channel) {
448         return channel->cipher();
449     }
450     auto *user = qobject_cast<CoreIrcUser *>(ircUser(target));
451     if (user) {
452         return user->cipher();
453     } else if (!isChannelName(target)) {
454         return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
455     }
456     return nullptr;
457 }
458
459
460 QByteArray CoreNetwork::cipherKey(const QString &target) const
461 {
462     auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
463     if (c)
464         return c->cipher()->key();
465
466     auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
467     if (u)
468         return u->cipher()->key();
469
470     return QByteArray();
471 }
472
473
474 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
475 {
476     auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
477     if (c) {
478         c->setEncrypted(c->cipher()->setKey(key));
479         coreSession()->setBufferCipher(networkId(), target, key);
480         return;
481     }
482
483     auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
484     if (!u && !isChannelName(target))
485         u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
486
487     if (u) {
488         u->setEncrypted(u->cipher()->setKey(key));
489         coreSession()->setBufferCipher(networkId(), target, key);
490         return;
491     }
492 }
493
494
495 bool CoreNetwork::cipherUsesCBC(const QString &target)
496 {
497     auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
498     if (c)
499         return c->cipher()->usesCBC();
500     auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
501     if (u)
502         return u->cipher()->usesCBC();
503
504     return false;
505 }
506 #endif /* HAVE_QCA2 */
507
508 bool CoreNetwork::setAutoWhoDone(const QString &name)
509 {
510     QString chanOrNick = name.toLower();
511     if (_autoWhoPending.value(chanOrNick, 0) <= 0)
512         return false;
513     if (--_autoWhoPending[chanOrNick] <= 0)
514         _autoWhoPending.remove(chanOrNick);
515     return true;
516 }
517
518
519 void CoreNetwork::setMyNick(const QString &mynick)
520 {
521     Network::setMyNick(mynick);
522     if (connectionState() == Network::Initializing)
523         networkInitialized();
524 }
525
526
527 void CoreNetwork::socketHasData()
528 {
529     while (socket.canReadLine()) {
530         QByteArray s = socket.readLine();
531         if (s.endsWith("\r\n"))
532             s.chop(2);
533         else if (s.endsWith("\n"))
534             s.chop(1);
535         NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
536         event->setTimestamp(QDateTime::currentDateTimeUtc());
537         emit newEvent(event);
538     }
539 }
540
541
542 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
543 {
544     // Ignore socket closed errors if expected
545     if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
546         return;
547     }
548
549     _previousConnectionAttemptFailed = true;
550     qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
551     emit connectionError(socket.errorString());
552     displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
553     emitConnectionError(socket.errorString());
554     if (socket.state() < QAbstractSocket::ConnectedState) {
555         socketDisconnected();
556     }
557 }
558
559
560 void CoreNetwork::socketInitialized()
561 {
562     CoreIdentity *identity = identityPtr();
563     if (!identity) {
564         qCritical() << "Identity invalid!";
565         disconnectFromIrc();
566         return;
567     }
568
569     Server server = usedServer();
570
571 #ifdef HAVE_SSL
572     // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
573     // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
574     if (!server.useSsl || !socket.isEncrypted()) {
575         emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
576     }
577
578     if (server.useSsl && !socket.isEncrypted()) {
579         // We'll finish setup once we're encrypted, and called again
580         return;
581     }
582 #else
583     emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
584 #endif
585
586     socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
587
588     // Update the TokenBucket, force-enabling unlimited message rates for initial registration and
589     // capability negotiation.  networkInitialized() will call updateRateLimiting() without the
590     // force flag to apply user preferences.  When making changes, ensure that this still happens!
591     // As Quassel waits for CAP ACK/NAK and AUTHENTICATE replies, this shouldn't ever fill the IRC
592     // server receive queue and cause a kill.  "Shouldn't" being the operative word; the real world
593     // is a scary place.
594     updateRateLimiting(true);
595     // Fill up the token bucket as we're connecting from scratch
596     resetTokenBucket();
597
598     // Request capabilities as per IRCv3.2 specifications
599     // Older servers should ignore this; newer servers won't downgrade to RFC1459
600     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
601     putRawLine(serverEncode(QString("CAP LS 302")));
602
603     if (!server.password.isEmpty()) {
604         putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
605     }
606     QString nick;
607     if (identity->nicks().isEmpty()) {
608         nick = "quassel";
609         qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
610     }
611     else {
612         nick = identity->nicks()[0];
613     }
614     putRawLine(serverEncode(QString("NICK %1").arg(nick)));
615     // Only allow strict-compliant idents when strict mode is enabled
616     putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(
617                                 coreSession()->strictCompliantIdent(identity),
618                                 identity->realName())));
619 }
620
621
622 void CoreNetwork::socketDisconnected()
623 {
624     disablePingTimeout();
625     _msgQueue.clear();
626
627     _autoWhoCycleTimer.stop();
628     _autoWhoTimer.stop();
629     _autoWhoQueue.clear();
630     _autoWhoPending.clear();
631
632     _socketCloseTimer.stop();
633
634     _tokenBucketTimer.stop();
635
636     IrcUser *me_ = me();
637     if (me_) {
638         foreach(QString channel, me_->channels())
639         displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
640     }
641
642     setConnected(false);
643     emit disconnected(networkId());
644     emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort(), _socketId);
645     // Reset disconnect expectations
646     _disconnectExpected = false;
647     if (_quitRequested) {
648         _quitRequested = false;
649         setConnectionState(Network::Disconnected);
650         Core::setNetworkConnected(userId(), networkId(), false);
651     }
652     else if (_autoReconnectCount != 0) {
653         setConnectionState(Network::Reconnecting);
654         if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
655             doAutoReconnect();  // first try is immediate
656         else
657             _autoReconnectTimer.start();
658     }
659 }
660
661
662 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
663 {
664     Network::ConnectionState state;
665     switch (socketState) {
666     case QAbstractSocket::UnconnectedState:
667         state = Network::Disconnected;
668         socketDisconnected();
669         break;
670     case QAbstractSocket::HostLookupState:
671     case QAbstractSocket::ConnectingState:
672         state = Network::Connecting;
673         break;
674     case QAbstractSocket::ConnectedState:
675         state = Network::Initializing;
676         break;
677     case QAbstractSocket::ClosingState:
678         state = Network::Disconnecting;
679         break;
680     default:
681         state = Network::Disconnected;
682     }
683     setConnectionState(state);
684 }
685
686
687 void CoreNetwork::networkInitialized()
688 {
689     setConnectionState(Network::Initialized);
690     setConnected(true);
691     _disconnectExpected = false;
692     _quitRequested = false;
693
694     // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
695     // flag used for initial registration and capability negotiation.
696     updateRateLimiting();
697
698     if (useAutoReconnect()) {
699         // reset counter
700         _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
701     }
702
703     // restore away state
704     QString awayMsg = Core::awayMessage(userId(), networkId());
705     if (!awayMsg.isEmpty()) {
706         // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
707         // '%%%%%%%%' -> '%%%%'  If processed again, it'd result in '%%'.
708         userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
709     }
710
711     sendPerform();
712
713     _sendPings = true;
714
715     if (networkConfig()->autoWhoEnabled()) {
716         _autoWhoCycleTimer.start();
717         _autoWhoTimer.start();
718         startAutoWhoCycle(); // FIXME wait for autojoin to be completed
719     }
720
721     Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
722     Core::setNetworkConnected(userId(), networkId(), true);
723 }
724
725
726 void CoreNetwork::sendPerform()
727 {
728     BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
729
730     // do auto identify
731     if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
732         userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
733     }
734
735     // restore old user modes if server default mode is set.
736     IrcUser *me_ = me();
737     if (me_) {
738         if (!me_->userModes().isEmpty()) {
739             restoreUserModes();
740         }
741         else {
742             connect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
743             connect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
744         }
745     }
746
747     // send perform list
748     foreach(QString line, perform()) {
749         if (!line.isEmpty()) userInput(statusBuf, line);
750     }
751
752     // rejoin channels we've been in
753     if (rejoinChannels()) {
754         QStringList channels, keys;
755         foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
756             QString key = channelKey(chan);
757             if (!key.isEmpty()) {
758                 channels.prepend(chan);
759                 keys.prepend(key);
760             }
761             else {
762                 channels.append(chan);
763             }
764         }
765         QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
766         if (!joinString.isEmpty())
767             userInputHandler()->handleJoin(statusBuf, joinString);
768     }
769 }
770
771
772 void CoreNetwork::restoreUserModes()
773 {
774     IrcUser *me_ = me();
775     Q_ASSERT(me_);
776
777     disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
778     disconnect(me_, &IrcUser::userModesAdded, this, &CoreNetwork::restoreUserModes);
779
780     QString modesDelta = Core::userModes(userId(), networkId());
781     QString currentModes = me_->userModes();
782
783     QString addModes, removeModes;
784     if (modesDelta.contains('-')) {
785         addModes = modesDelta.section('-', 0, 0);
786         removeModes = modesDelta.section('-', 1);
787     }
788     else {
789         addModes = modesDelta;
790     }
791
792     addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
793     if (currentModes.isEmpty())
794         removeModes = QString();
795     else
796         removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
797
798     if (addModes.isEmpty() && removeModes.isEmpty())
799         return;
800
801     if (!addModes.isEmpty())
802         addModes = '+' + addModes;
803     if (!removeModes.isEmpty())
804         removeModes = '-' + removeModes;
805
806     // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
807     putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
808 }
809
810
811 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
812 {
813     QString addModes;
814     QString removeModes;
815     bool addMode = true;
816
817     for (auto requestedMode : requestedModes) {
818         if (requestedMode == '+') {
819             addMode = true;
820             continue;
821         }
822         if (requestedMode == '-') {
823             addMode = false;
824             continue;
825         }
826         if (addMode) {
827             addModes += requestedMode;
828         }
829         else {
830             removeModes += requestedMode;
831         }
832     }
833
834     QString addModesOld = _requestedUserModes.section('-', 0, 0);
835     QString removeModesOld = _requestedUserModes.section('-', 1);
836
837     addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
838     addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
839     addModes += addModesOld;
840
841     removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
842     removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
843     removeModes += removeModesOld;
844
845     _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
846 }
847
848
849 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
850 {
851     QString persistentUserModes = Core::userModes(userId(), networkId());
852
853     QString requestedAdd = _requestedUserModes.section('-', 0, 0);
854     QString requestedRemove = _requestedUserModes.section('-', 1);
855
856     QString persistentAdd, persistentRemove;
857     if (persistentUserModes.contains('-')) {
858         persistentAdd = persistentUserModes.section('-', 0, 0);
859         persistentRemove = persistentUserModes.section('-', 1);
860     }
861     else {
862         persistentAdd = persistentUserModes;
863     }
864
865     // remove modes we didn't issue
866     if (requestedAdd.isEmpty())
867         addModes = QString();
868     else
869         addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
870
871     if (requestedRemove.isEmpty())
872         removeModes = QString();
873     else
874         removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
875
876     // deduplicate
877     persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
878     persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
879
880     // update
881     persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
882     persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
883
884     // update issued mode list
885     requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
886     requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
887     _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
888
889     persistentAdd += addModes;
890     persistentRemove += removeModes;
891     Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
892 }
893
894
895 void CoreNetwork::resetPersistentModes()
896 {
897     _requestedUserModes = QString('-');
898     Core::setUserModes(userId(), networkId(), QString());
899 }
900
901
902 void CoreNetwork::setUseAutoReconnect(bool use)
903 {
904     Network::setUseAutoReconnect(use);
905     if (!use)
906         _autoReconnectTimer.stop();
907 }
908
909
910 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
911 {
912     Network::setAutoReconnectInterval(interval);
913     _autoReconnectTimer.setInterval(interval * 1000);
914 }
915
916
917 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
918 {
919     Network::setAutoReconnectRetries(retries);
920     if (_autoReconnectCount != 0) {
921         if (unlimitedReconnectRetries())
922             _autoReconnectCount = -1;
923         else
924             _autoReconnectCount = autoReconnectRetries();
925     }
926 }
927
928
929 void CoreNetwork::doAutoReconnect()
930 {
931     if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
932         qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
933         return;
934     }
935     if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
936         _autoReconnectCount--;  // -2 means we delay the next reconnect
937     connectToIrc(true);
938 }
939
940
941 void CoreNetwork::sendPing()
942 {
943     qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
944     if (_pingCount != 0) {
945         qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
946                  << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
947     }
948     if ((int)_pingCount >= networkConfig()->maxPingCount()
949             && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
950         // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
951         // However, to reduce the risk of breaking things by changing past behavior, we still allow
952         // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
953         //
954         // the second check compares the actual elapsed time since the last ping and the pingTimer interval
955         // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
956         // and unable to even handle a ping answer. So we ignore those misses.
957         disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
958     }
959     else {
960         _lastPingTime = now;
961         _pingCount++;
962         // Don't send pings until the network is initialized
963         if(_sendPings) {
964             // Mark as waiting for a reply
965             _pongReplyPending = true;
966             // Send default timestamp ping
967             userInputHandler()->handlePing(BufferInfo(), QString());
968         }
969     }
970 }
971
972
973 void CoreNetwork::enablePingTimeout(bool enable)
974 {
975     if (!enable)
976         disablePingTimeout();
977     else {
978         resetPingTimeout();
979         resetPongReplyPending();
980         if (networkConfig()->pingTimeoutEnabled())
981             _pingTimer.start();
982     }
983 }
984
985
986 void CoreNetwork::disablePingTimeout()
987 {
988     _pingTimer.stop();
989     _sendPings = false;
990     resetPingTimeout();
991     resetPongReplyPending();
992 }
993
994
995 void CoreNetwork::setPingInterval(int interval)
996 {
997     _pingTimer.setInterval(interval * 1000);
998 }
999
1000
1001 void CoreNetwork::setPongTimestampValid(bool validTimestamp)
1002 {
1003     _pongTimestampValid = validTimestamp;
1004 }
1005
1006
1007 /******** Custom Rate Limiting ********/
1008
1009 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
1010 {
1011     // Verify and apply custom rate limiting options, always resetting the delay and burst size
1012     // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
1013     // this may be called while connected to a server.
1014
1015     if (useCustomMessageRate() || forceUnlimited) {
1016         // Custom message rates enabled, or chosen by means of forcing unlimited.  Let's go for it!
1017
1018         _messageDelay = messageRateDelay();
1019
1020         _burstSize = messageRateBurstSize();
1021         if (_burstSize < 1) {
1022             qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
1023                        << _burstSize;
1024             // Can't go slower than one message at a time
1025             _burstSize = 1;
1026         }
1027
1028         if (_tokenBucket > _burstSize) {
1029             // Don't let the token bucket exceed the maximum
1030             _tokenBucket = _burstSize;
1031             // To fill up the token bucket, use resetRateLimiting().  Don't do that here, otherwise
1032             // changing the rate-limit settings while connected to a server will incorrectly reset
1033             // the token bucket.
1034         }
1035
1036         // Toggle the timer according to whether or not rate limiting is enabled
1037         // If we're here, either useCustomMessageRate or forceUnlimited is true.  Thus, the logic is
1038         // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1039         // Override user preferences if called with force unlimited, only used during connect.
1040         _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1041         if (_skipMessageRates) {
1042             // If the message queue already contains messages, they need sent before disabling the
1043             // timer.  Set the timer to a rapid pace and let it disable itself.
1044             if (_msgQueue.size() > 0) {
1045                 qDebug() << "Outgoing message queue contains messages while disabling rate "
1046                             "limiting.  Sending remaining queued messages...";
1047                 // Promptly run the timer again to clear the messages.  Rate limiting is disabled,
1048                 // so nothing should cause this to block.. in theory.  However, don't directly call
1049                 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1050                 //
1051                 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1052                 // Hesitant to change it without a wide variety of situations to verify behavior.
1053                 _tokenBucketTimer.start(100);
1054             } else {
1055                 // No rate limiting, disable the timer
1056                 _tokenBucketTimer.stop();
1057             }
1058         } else {
1059             // Rate limiting enabled, enable the timer
1060             _tokenBucketTimer.start(_messageDelay);
1061         }
1062     } else {
1063         // Custom message rates disabled.  Go for the default.
1064
1065         _skipMessageRates = false;  // Enable rate-limiting by default
1066         _messageDelay = 2200;       // This seems to be a safe value (2.2 seconds delay)
1067         _burstSize = 5;             // 5 messages at once
1068         if (_tokenBucket > _burstSize) {
1069             // TokenBucket to avoid sending too much at once.  Don't let the token bucket exceed the
1070             // maximum.
1071             _tokenBucket = _burstSize;
1072             // To fill up the token bucket, use resetRateLimiting().  Don't do that here, otherwise
1073             // changing the rate-limit settings while connected to a server will incorrectly reset
1074             // the token bucket.
1075         }
1076         // Rate limiting enabled, enable the timer
1077         _tokenBucketTimer.start(_messageDelay);
1078     }
1079 }
1080
1081 void CoreNetwork::resetTokenBucket()
1082 {
1083     // Fill up the token bucket to the maximum
1084     _tokenBucket = _burstSize;
1085 }
1086
1087
1088 /******** IRCv3 Capability Negotiation ********/
1089
1090 void CoreNetwork::serverCapAdded(const QString &capability)
1091 {
1092     // Check if it's a known capability; if so, add it to the list
1093     // Handle special cases first
1094     if (capability == IrcCap::SASL) {
1095         // Only request SASL if it's enabled
1096         if (networkInfo().useSasl)
1097             queueCap(capability);
1098     } else if (IrcCap::knownCaps.contains(capability)) {
1099         // Handling for general known capabilities
1100         queueCap(capability);
1101     }
1102 }
1103
1104 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1105 {
1106     // This may be called multiple times in certain situations.
1107
1108     // Handle core-side configuration
1109     if (capability == IrcCap::AWAY_NOTIFY) {
1110         // away-notify enabled, stop the autoWho timers, handle manually
1111         setAutoWhoEnabled(false);
1112     }
1113
1114     // Handle capabilities that require further messages sent to the IRC server
1115     // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1116     if (capability == IrcCap::SASL) {
1117         // If SASL mechanisms specified, limit to what's accepted for authentication
1118         // if the current identity has a cert set, use SASL EXTERNAL
1119         // FIXME use event
1120 #ifdef HAVE_SSL
1121         if (!identityPtr()->sslCert().isNull()) {
1122             if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1123                 // EXTERNAL authentication supported, send request
1124                 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1125             } else {
1126                 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1127                            tr("SASL EXTERNAL authentication not supported"));
1128                 sendNextCap();
1129             }
1130         } else {
1131 #endif
1132             if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1133                 // PLAIN authentication supported, send request
1134                 // Only working with PLAIN atm, blowfish later
1135                 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1136             } else {
1137                 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1138                            tr("SASL PLAIN authentication not supported"));
1139                 sendNextCap();
1140             }
1141 #ifdef HAVE_SSL
1142         }
1143 #endif
1144     }
1145 }
1146
1147 void CoreNetwork::serverCapRemoved(const QString &capability)
1148 {
1149     // This may be called multiple times in certain situations.
1150
1151     // Handle special cases here
1152     if (capability == IrcCap::AWAY_NOTIFY) {
1153         // away-notify disabled, enable autoWho according to configuration
1154         setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1155     }
1156 }
1157
1158 void CoreNetwork::queueCap(const QString &capability)
1159 {
1160     // IRCv3 specs all use lowercase capability names
1161     QString _capLowercase = capability.toLower();
1162
1163     if(capsRequiringConfiguration.contains(_capLowercase)) {
1164         // The capability requires additional configuration before being acknowledged (e.g. SASL),
1165         // so we should negotiate it separately from all other capabilities.  Otherwise new
1166         // capabilities will be requested while still configuring the previous one.
1167         if (!_capsQueuedIndividual.contains(_capLowercase)) {
1168             _capsQueuedIndividual.append(_capLowercase);
1169         }
1170     } else {
1171         // The capability doesn't need any special configuration, so it should be safe to try
1172         // bundling together with others.  "Should" being the imperative word, as IRC servers can do
1173         // anything.
1174         if (!_capsQueuedBundled.contains(_capLowercase)) {
1175             _capsQueuedBundled.append(_capLowercase);
1176         }
1177     }
1178 }
1179
1180 QString CoreNetwork::takeQueuedCaps()
1181 {
1182     // Clear the record of the most recently negotiated capability bundle.  Does nothing if the list
1183     // is empty.
1184     _capsQueuedLastBundle.clear();
1185
1186     // First, negotiate all the standalone capabilities that require additional configuration.
1187     if (!_capsQueuedIndividual.empty()) {
1188         // We have an individual capability available.  Take the first and pass it back.
1189         return _capsQueuedIndividual.takeFirst();
1190     } else if (!_capsQueuedBundled.empty()) {
1191         // We have capabilities available that can be grouped.  Try to fit in as many as within the
1192         // maximum length.
1193         // See CoreNetwork::maxCapRequestLength
1194
1195         // Response must have at least one capability regardless of max length for anything to
1196         // happen.
1197         QString capBundle = _capsQueuedBundled.takeFirst();
1198         QString nextCap("");
1199         while (!_capsQueuedBundled.empty()) {
1200             // As long as capabilities remain, get the next...
1201             nextCap = _capsQueuedBundled.first();
1202             if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1203                 // [capability + 1 for a space + this new capability] fit within length limits
1204                 // Add it to formatted list
1205                 capBundle.append(" " + nextCap);
1206                 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1207                 _capsQueuedLastBundle.append(nextCap);
1208                 // Then remove it from the queue
1209                 _capsQueuedBundled.removeFirst();
1210             } else {
1211                 // We've reached the length limit for a single capability request, stop adding more
1212                 break;
1213             }
1214         }
1215         // Return this space-separated set of capabilities, removing any extra spaces
1216         return capBundle.trimmed();
1217     } else {
1218         // No capabilities left to negotiate, return an empty string.
1219         return QString();
1220     }
1221 }
1222
1223 void CoreNetwork::retryCapsIndividually()
1224 {
1225     // The most recent set of capabilities got denied by the IRC server.  As we don't know what got
1226     // denied, try each capability individually.
1227     if (_capsQueuedLastBundle.empty()) {
1228         // No most recently tried capability set, just return.
1229         return;
1230         // Note: there's little point in retrying individually requested caps during negotiation.
1231         // We know the individual capability was the one that failed, and it's not likely it'll
1232         // suddenly start working within a few seconds.  'cap-notify' provides a better system for
1233         // handling capability removal and addition.
1234     }
1235
1236     // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1237     // over efficiency.  If this becomes an issue, implement a binary splicing system instead,
1238     // keeping track of which halves of the group fail, dividing the set each time.
1239
1240     // Add most recently tried capability set to individual list, re-requesting them one at a time
1241     _capsQueuedIndividual.append(_capsQueuedLastBundle);
1242     // Warn of this issue to explain the slower login.  Servers usually shouldn't trigger this.
1243     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1244                tr("Could not negotiate some capabilities, retrying individually (%1)...")
1245                .arg(_capsQueuedLastBundle.join(", ")));
1246     // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1247     // need to remove them here.
1248     // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1249     // indefinitely.
1250     _capsQueuedLastBundle.clear();
1251 }
1252
1253 void CoreNetwork::beginCapNegotiation()
1254 {
1255     // Don't begin negotiation if no capabilities are queued to request
1256     if (!capNegotiationInProgress()) {
1257         // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1258         // normal connection.
1259         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1260         endCapNegotiation();
1261         return;
1262     }
1263
1264     _capNegotiationActive = true;
1265     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1266                tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1267
1268     // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1269     // comma separator between the two if needed (both individual and bundled caps exist).
1270     QString queuedCapsDisplay =
1271             _capsQueuedIndividual.join(", ")
1272             + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1273             + _capsQueuedBundled.join(", ");
1274     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1275                tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1276
1277     sendNextCap();
1278 }
1279
1280 void CoreNetwork::sendNextCap()
1281 {
1282     if (capNegotiationInProgress()) {
1283         // Request the next set of capabilities and remove them from the list
1284         putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1285     } else {
1286         // No pending desired capabilities, capability negotiation finished
1287         // If SASL requested but not available, print a warning
1288         if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1289             displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1290                        tr("SASL authentication currently not supported by server"));
1291
1292         if (_capNegotiationActive) {
1293             displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1294                    tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1295             _capNegotiationActive = false;
1296         }
1297
1298         endCapNegotiation();
1299     }
1300 }
1301
1302 void CoreNetwork::endCapNegotiation()
1303 {
1304     // If nick registration is already complete, CAP END is not required
1305     if (!_capInitialNegotiationEnded) {
1306         putRawLine(serverEncode(QString("CAP END")));
1307         _capInitialNegotiationEnded = true;
1308     }
1309 }
1310
1311 /******** AutoWHO ********/
1312
1313 void CoreNetwork::startAutoWhoCycle()
1314 {
1315     if (!_autoWhoQueue.isEmpty()) {
1316         _autoWhoCycleTimer.stop();
1317         return;
1318     }
1319     _autoWhoQueue = channels();
1320 }
1321
1322 void CoreNetwork::queueAutoWhoOneshot(const QString &name)
1323 {
1324     // Prepend so these new channels/nicks are the first to be checked
1325     // Don't allow duplicates
1326     if (!_autoWhoQueue.contains(name.toLower())) {
1327         _autoWhoQueue.prepend(name.toLower());
1328     }
1329     if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1330         // When away-notify is active, the timer's stopped.  Start a new cycle to who this channel.
1331         setAutoWhoEnabled(true);
1332     }
1333 }
1334
1335
1336 void CoreNetwork::setAutoWhoDelay(int delay)
1337 {
1338     _autoWhoTimer.setInterval(delay * 1000);
1339 }
1340
1341
1342 void CoreNetwork::setAutoWhoInterval(int interval)
1343 {
1344     _autoWhoCycleTimer.setInterval(interval * 1000);
1345 }
1346
1347
1348 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1349 {
1350     if (enabled && isConnected() && !_autoWhoTimer.isActive())
1351         _autoWhoTimer.start();
1352     else if (!enabled) {
1353         _autoWhoTimer.stop();
1354         _autoWhoCycleTimer.stop();
1355     }
1356 }
1357
1358
1359 void CoreNetwork::sendAutoWho()
1360 {
1361     // Don't send autowho if there are still some pending
1362     if (_autoWhoPending.count())
1363         return;
1364
1365     while (!_autoWhoQueue.isEmpty()) {
1366         QString chanOrNick = _autoWhoQueue.takeFirst();
1367         // Check if it's a known channel or nick
1368         IrcChannel *ircchan = ircChannel(chanOrNick);
1369         IrcUser *ircuser = ircUser(chanOrNick);
1370         if (ircchan) {
1371             // Apply channel limiting rules
1372             // If using away-notify, don't impose channel size limits in order to capture away
1373             // state of everyone.  Auto-who won't run on a timer so network impact is minimal.
1374             if (networkConfig()->autoWhoNickLimit() > 0
1375                 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1376                 && !capEnabled(IrcCap::AWAY_NOTIFY))
1377                 continue;
1378             _autoWhoPending[chanOrNick.toLower()]++;
1379         } else if (ircuser) {
1380             // Checking a nick, add it to the pending list
1381             _autoWhoPending[ircuser->nick().toLower()]++;
1382         } else {
1383             // Not a channel or a nick, skip it
1384             qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1385             continue;
1386         }
1387         if (supports("WHOX")) {
1388             // Use WHO extended to poll away users and/or user accounts
1389             // Explicitly only match on nickname ("n"), don't rely on server defaults
1390             //
1391             // WHO <nickname> n%chtsunfra,<unique_number>
1392             //
1393             // See http://faerion.sourceforge.net/doc/irc/whox.var
1394             // And https://github.com/quakenet/snircd/blob/master/doc/readme.who
1395             // And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
1396             putRawLine(serverEncode(QString("WHO %1 n%chtsunfra,%2")
1397                                     .arg(serverEncode(chanOrNick),
1398                                          QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1399         } else {
1400             // Fall back to normal WHO
1401             //
1402             // Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
1403             // hostmask, etc.  There's nothing we can do about that :(
1404             //
1405             // See https://tools.ietf.org/html/rfc1459#section-4.5.1
1406             putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1407         }
1408         break;
1409     }
1410
1411     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1412         && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1413         // Timer was stopped, means a new cycle is due immediately
1414         // Don't run a new cycle if using away-notify; server will notify as appropriate
1415         _autoWhoCycleTimer.start();
1416         startAutoWhoCycle();
1417     } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1418         // Don't run another who cycle if away-notify is enabled
1419         _autoWhoCycleTimer.stop();
1420     }
1421 }
1422
1423
1424 #ifdef HAVE_SSL
1425 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1426 {
1427     Server server = usedServer();
1428     if (server.sslVerify) {
1429         // Treat the SSL error as a hard error
1430         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1431                                      "since verification is required");
1432         if (!sslErrors.empty()) {
1433             // Add the error reason if known
1434             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1435         }
1436         displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1437
1438         // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1439         // validity, network trouble, etc.
1440         disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1441     } else {
1442         // Treat the SSL error as a warning, continue to connect anyways
1443         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1444                                      "since verification is not required");
1445         if (!sslErrors.empty()) {
1446             // Add the error reason if known
1447             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1448         }
1449         displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1450
1451         // Proceed with the connection
1452         socket.ignoreSslErrors();
1453     }
1454 }
1455
1456
1457 #endif  // HAVE_SSL
1458
1459 void CoreNetwork::checkTokenBucket()
1460 {
1461     if (_skipMessageRates) {
1462         if (_msgQueue.size() == 0) {
1463             // Message queue emptied; stop the timer and bail out
1464             _tokenBucketTimer.stop();
1465             return;
1466         }
1467         // Otherwise, we're emptying the queue, continue on as normal
1468     }
1469
1470     // Process whatever messages are pending
1471     fillBucketAndProcessQueue();
1472 }
1473
1474
1475 void CoreNetwork::fillBucketAndProcessQueue()
1476 {
1477     // If there's less tokens than burst size, refill the token bucket by 1
1478     if (_tokenBucket < _burstSize) {
1479         _tokenBucket++;
1480     }
1481
1482     // As long as there's tokens available and messages remaining, sending messages from the queue
1483     while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1484         writeToSocket(_msgQueue.takeFirst());
1485     }
1486 }
1487
1488
1489 void CoreNetwork::writeToSocket(const QByteArray &data)
1490 {
1491     // Log the message if enabled and network ID matches or allows all
1492     if (_debugLogRawIrc
1493             && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
1494         // Include network ID
1495         qDebug() << "IRC net" << networkId() << ">>" << data;
1496     }
1497     socket.write(data);
1498     socket.write("\r\n");
1499     if (!_skipMessageRates) {
1500         // Only subtract from the token bucket if message rate limiting is enabled
1501         _tokenBucket--;
1502     }
1503 }
1504
1505
1506 Network::Server CoreNetwork::usedServer() const
1507 {
1508     if (_lastUsedServerIndex < serverList().count())
1509         return serverList()[_lastUsedServerIndex];
1510
1511     if (!serverList().isEmpty())
1512         return serverList()[0];
1513
1514     return Network::Server();
1515 }
1516
1517
1518 void CoreNetwork::requestConnect() const
1519 {
1520     if (_shuttingDown) {
1521         return;
1522     }
1523     if (connectionState() != Disconnected) {
1524         qWarning() << "Requesting connect while already being connected!";
1525         return;
1526     }
1527     QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1528 }
1529
1530
1531 void CoreNetwork::requestDisconnect() const
1532 {
1533     if (_shuttingDown) {
1534         return;
1535     }
1536     if (connectionState() == Disconnected) {
1537         qWarning() << "Requesting disconnect while not being connected!";
1538         return;
1539     }
1540     userInputHandler()->handleQuit(BufferInfo(), QString());
1541 }
1542
1543
1544 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1545 {
1546     Network::Server currentServer = usedServer();
1547     setNetworkInfo(info);
1548     Core::updateNetwork(coreSession()->user(), info);
1549
1550     // the order of the servers might have changed,
1551     // so we try to find the previously used server
1552     _lastUsedServerIndex = 0;
1553     for (int i = 0; i < serverList().count(); i++) {
1554         Network::Server server = serverList()[i];
1555         if (server.host == currentServer.host && server.port == currentServer.port) {
1556             _lastUsedServerIndex = i;
1557             break;
1558         }
1559     }
1560 }
1561
1562
1563 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1564 {
1565     QString wrkMsg(message);
1566     QList<QList<QByteArray>> msgsToSend;
1567
1568     // do while (wrkMsg.size() > 0)
1569     do {
1570         // First, check to see if the whole message can be sent at once.  The
1571         // cmdGenerator function is passed in by the caller and is used to encode
1572         // and encrypt (if applicable) the message, since different callers might
1573         // want to use different encoding or encode different values.
1574         int splitPos = wrkMsg.size();
1575         QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1576         int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1577
1578         if (initialOverrun) {
1579             // If the message was too long to be sent, first try splitting it along
1580             // word boundaries with QTextBoundaryFinder.
1581             QString splitMsg(wrkMsg);
1582             QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1583             qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1584             QList<QByteArray> splitMsgEnc;
1585             int overrun = initialOverrun;
1586
1587             while (overrun) {
1588                 splitPos = qtbf.toPreviousBoundary();
1589
1590                 // splitPos==-1 means the QTBF couldn't find a split point at all and
1591                 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1592                 // the string.  Neither one of these works for us.
1593                 if (splitPos > 0) {
1594                     // If a split point could be found, split the message there, calculate the
1595                     // overrun, and continue with the loop.
1596                     splitMsg = splitMsg.left(splitPos);
1597                     splitMsgEnc = cmdGenerator(splitMsg);
1598                     overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1599                 }
1600                 else {
1601                     // If a split point could not be found (the beginning of the message
1602                     // is reached without finding a split point short enough to send) and we
1603                     // are still in Word mode, switch to Grapheme mode.  We also need to restore
1604                     // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1605                     // the previous attempt to find a split point.
1606                     if (qtbf.type() == QTextBoundaryFinder::Word) {
1607                         splitMsg = wrkMsg;
1608                         splitPos = splitMsg.size();
1609                         QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1610                         graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1611                         qtbf = graphemeQtbf;
1612                     }
1613                     else {
1614                         // If the QTBF fails to find a split point in Grapheme mode, we give up.
1615                         // This should never happen, but it should be handled anyway.
1616                         qWarning() << "Unexpected failure to split message!";
1617                         return msgsToSend;
1618                     }
1619                 }
1620             }
1621
1622             // Once a message of sendable length has been found, remove it from the wrkMsg and
1623             // add it to the list of messages to be sent.
1624             wrkMsg.remove(0, splitPos);
1625             msgsToSend.append(splitMsgEnc);
1626         }
1627         else{
1628             // If the entire remaining message is short enough to be sent all at once, remove
1629             // it from the wrkMsg and add it to the list of messages to be sent.
1630             wrkMsg.remove(0, splitPos);
1631             msgsToSend.append(initialSplitMsgEnc);
1632         }
1633     } while (wrkMsg.size() > 0);
1634
1635     return msgsToSend;
1636 }