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