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