identd: Implement blocking request queueing
[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     _lastPingTime(0),
48     _pingCount(0),
49     _sendPings(false),
50     _requestedUserModes('-')
51 {
52     _autoReconnectTimer.setSingleShot(true);
53     connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
54
55     setPingInterval(networkConfig()->pingInterval());
56     connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
57
58     setAutoWhoDelay(networkConfig()->autoWhoDelay());
59     setAutoWhoInterval(networkConfig()->autoWhoInterval());
60
61     QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
62     foreach(QString chan, channels.keys()) {
63         _channelKeys[chan.toLower()] = channels[chan];
64     }
65
66     QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
67     foreach(QString buffer, bufferCiphers.keys()) {
68         storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
69     }
70
71     connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
72     connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
73     connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
74     connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
75     connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
76
77     connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
78     connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
79     connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
80     connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(checkTokenBucket()));
81
82     connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
83     connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
84     connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
85     connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
86 #ifdef HAVE_SSL
87     connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
88     connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
89 #endif
90     connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
91
92     // Custom rate limiting
93     // These react to the user changing settings in the client
94     connect(this, SIGNAL(useCustomMessageRateSet(bool)), SLOT(updateRateLimiting()));
95     connect(this, SIGNAL(messageRateBurstSizeSet(quint32)), SLOT(updateRateLimiting()));
96     connect(this, SIGNAL(messageRateDelaySet(quint32)), SLOT(updateRateLimiting()));
97     connect(this, SIGNAL(unlimitedMessageRateSet(bool)), SLOT(updateRateLimiting()));
98
99     // IRCv3 capability handling
100     // These react to CAP messages from the server
101     connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
102     connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
103     connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
104
105     if (Quassel::isOptionSet("oidentd")) {
106         connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
107         connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
108     }
109
110     if (Quassel::isOptionSet("ident-daemon")) {
111         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);
112         connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)), Core::instance()->identServer(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16, qint64)));
113     }
114 }
115
116
117 CoreNetwork::~CoreNetwork()
118 {
119     // Request a proper disconnect, but don't count as user-requested disconnect
120     if (socketConnected()) {
121         // Only try if the socket's fully connected (not initializing or disconnecting).
122         // Force an immediate disconnect, jumping the command queue.  Ensures the proper QUIT is
123         // shown even if other messages are queued.
124         disconnectFromIrc(false, QString(), false, true);
125         // Process the putCmd events that trigger the quit.  Without this, shutting down the core
126         // results in abrubtly closing the socket rather than sending the QUIT as expected.
127         QCoreApplication::processEvents();
128         // Wait briefly for each network to disconnect.  Sometimes it takes a little while to send.
129         if (!forceDisconnect()) {
130             qWarning() << "Timed out quitting network" << networkName() <<
131                           "(user ID " << userId() << ")";
132         }
133     }
134     disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
135     delete _userInputHandler;
136 }
137
138
139 bool CoreNetwork::forceDisconnect(int msecs)
140 {
141     if (socket.state() == QAbstractSocket::UnconnectedState) {
142         // Socket already disconnected.
143         return true;
144     }
145     // Request a socket-level disconnect if not already happened
146     socket.disconnectFromHost();
147     // Return the result of waiting for disconnect; true if successful, otherwise false
148     return socket.waitForDisconnected(msecs);
149 }
150
151
152 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
153 {
154     if (!bufferName.isEmpty()) {
155         IrcChannel *channel = ircChannel(bufferName);
156         if (channel)
157             return channel->decodeString(string);
158     }
159     return decodeString(string);
160 }
161
162
163 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
164 {
165     IrcUser *user = ircUser(userNick);
166     if (user)
167         return user->decodeString(string);
168     return decodeString(string);
169 }
170
171
172 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
173 {
174     if (!bufferName.isEmpty()) {
175         IrcChannel *channel = ircChannel(bufferName);
176         if (channel)
177             return channel->encodeString(string);
178     }
179     return encodeString(string);
180 }
181
182
183 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
184 {
185     IrcUser *user = ircUser(userNick);
186     if (user)
187         return user->encodeString(string);
188     return encodeString(string);
189 }
190
191
192 void CoreNetwork::connectToIrc(bool reconnecting)
193 {
194     if (Core::instance()->identServer()) {
195         _socketId = Core::instance()->identServer()->addWaitingSocket();
196     }
197
198     if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
199         _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
200         if (unlimitedReconnectRetries())
201             _autoReconnectCount = -1;
202         else
203             _autoReconnectCount = autoReconnectRetries();
204     }
205     if (serverList().isEmpty()) {
206         qWarning() << "Server list empty, ignoring connect request!";
207         return;
208     }
209     CoreIdentity *identity = identityPtr();
210     if (!identity) {
211         qWarning() << "Invalid identity configures, ignoring connect request!";
212         return;
213     }
214
215     // cleaning up old quit reason
216     _quitReason.clear();
217
218     // Reset capability negotiation tracking, also handling server changes during reconnect
219     _capsQueuedIndividual.clear();
220     _capsQueuedBundled.clear();
221     clearCaps();
222     _capNegotiationActive = false;
223     _capInitialNegotiationEnded = false;
224
225     // use a random server?
226     if (useRandomServer()) {
227         _lastUsedServerIndex = qrand() % serverList().size();
228     }
229     else if (_previousConnectionAttemptFailed) {
230         // cycle to next server if previous connection attempt failed
231         _previousConnectionAttemptFailed = false;
232         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
233         if (++_lastUsedServerIndex >= serverList().size()) {
234             _lastUsedServerIndex = 0;
235         }
236     }
237     else {
238         // Start out with the top server in the list
239         _lastUsedServerIndex = 0;
240     }
241
242     Server server = usedServer();
243     displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
244     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
245
246     if (server.useProxy) {
247         QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
248         socket.setProxy(proxy);
249     }
250     else {
251         socket.setProxy(QNetworkProxy::NoProxy);
252     }
253
254     enablePingTimeout();
255
256     // 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             userInputHandler()->handlePing(BufferInfo(), QString());
945     }
946 }
947
948
949 void CoreNetwork::enablePingTimeout(bool enable)
950 {
951     if (!enable)
952         disablePingTimeout();
953     else {
954         resetPingTimeout();
955         if (networkConfig()->pingTimeoutEnabled())
956             _pingTimer.start();
957     }
958 }
959
960
961 void CoreNetwork::disablePingTimeout()
962 {
963     _pingTimer.stop();
964     _sendPings = false;
965     resetPingTimeout();
966 }
967
968
969 void CoreNetwork::setPingInterval(int interval)
970 {
971     _pingTimer.setInterval(interval * 1000);
972 }
973
974
975 /******** Custom Rate Limiting ********/
976
977 void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
978 {
979     // Verify and apply custom rate limiting options, always resetting the delay and burst size
980     // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
981     // this may be called while connected to a server.
982
983     if (useCustomMessageRate() || forceUnlimited) {
984         // Custom message rates enabled, or chosen by means of forcing unlimited.  Let's go for it!
985
986         _messageDelay = messageRateDelay();
987
988         _burstSize = messageRateBurstSize();
989         if (_burstSize < 1) {
990             qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
991                        << _burstSize;
992             // Can't go slower than one message at a time
993             _burstSize = 1;
994         }
995
996         if (_tokenBucket > _burstSize) {
997             // Don't let the token bucket exceed the maximum
998             _tokenBucket = _burstSize;
999             // To fill up the token bucket, use resetRateLimiting().  Don't do that here, otherwise
1000             // changing the rate-limit settings while connected to a server will incorrectly reset
1001             // the token bucket.
1002         }
1003
1004         // Toggle the timer according to whether or not rate limiting is enabled
1005         // If we're here, either useCustomMessageRate or forceUnlimited is true.  Thus, the logic is
1006         // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
1007         // Override user preferences if called with force unlimited, only used during connect.
1008         _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
1009         if (_skipMessageRates) {
1010             // If the message queue already contains messages, they need sent before disabling the
1011             // timer.  Set the timer to a rapid pace and let it disable itself.
1012             if (_msgQueue.size() > 0) {
1013                 qDebug() << "Outgoing message queue contains messages while disabling rate "
1014                             "limiting.  Sending remaining queued messages...";
1015                 // Promptly run the timer again to clear the messages.  Rate limiting is disabled,
1016                 // so nothing should cause this to block.. in theory.  However, don't directly call
1017                 // fillBucketAndProcessQueue() in order to keep it on a separate thread.
1018                 //
1019                 // TODO If testing shows this isn't needed, it can be simplified to a direct call.
1020                 // Hesitant to change it without a wide variety of situations to verify behavior.
1021                 _tokenBucketTimer.start(100);
1022             } else {
1023                 // No rate limiting, disable the timer
1024                 _tokenBucketTimer.stop();
1025             }
1026         } else {
1027             // Rate limiting enabled, enable the timer
1028             _tokenBucketTimer.start(_messageDelay);
1029         }
1030     } else {
1031         // Custom message rates disabled.  Go for the default.
1032
1033         _skipMessageRates = false;  // Enable rate-limiting by default
1034         _messageDelay = 2200;       // This seems to be a safe value (2.2 seconds delay)
1035         _burstSize = 5;             // 5 messages at once
1036         if (_tokenBucket > _burstSize) {
1037             // TokenBucket to avoid sending too much at once.  Don't let the token bucket exceed the
1038             // maximum.
1039             _tokenBucket = _burstSize;
1040             // To fill up the token bucket, use resetRateLimiting().  Don't do that here, otherwise
1041             // changing the rate-limit settings while connected to a server will incorrectly reset
1042             // the token bucket.
1043         }
1044         // Rate limiting enabled, enable the timer
1045         _tokenBucketTimer.start(_messageDelay);
1046     }
1047 }
1048
1049 void CoreNetwork::resetTokenBucket()
1050 {
1051     // Fill up the token bucket to the maximum
1052     _tokenBucket = _burstSize;
1053 }
1054
1055
1056 /******** IRCv3 Capability Negotiation ********/
1057
1058 void CoreNetwork::serverCapAdded(const QString &capability)
1059 {
1060     // Check if it's a known capability; if so, add it to the list
1061     // Handle special cases first
1062     if (capability == IrcCap::SASL) {
1063         // Only request SASL if it's enabled
1064         if (networkInfo().useSasl)
1065             queueCap(capability);
1066     } else if (IrcCap::knownCaps.contains(capability)) {
1067         // Handling for general known capabilities
1068         queueCap(capability);
1069     }
1070 }
1071
1072 void CoreNetwork::serverCapAcknowledged(const QString &capability)
1073 {
1074     // This may be called multiple times in certain situations.
1075
1076     // Handle core-side configuration
1077     if (capability == IrcCap::AWAY_NOTIFY) {
1078         // away-notify enabled, stop the autoWho timers, handle manually
1079         setAutoWhoEnabled(false);
1080     }
1081
1082     // Handle capabilities that require further messages sent to the IRC server
1083     // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
1084     if (capability == IrcCap::SASL) {
1085         // If SASL mechanisms specified, limit to what's accepted for authentication
1086         // if the current identity has a cert set, use SASL EXTERNAL
1087         // FIXME use event
1088 #ifdef HAVE_SSL
1089         if (!identityPtr()->sslCert().isNull()) {
1090             if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
1091                 // EXTERNAL authentication supported, send request
1092                 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
1093             } else {
1094                 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1095                            tr("SASL EXTERNAL authentication not supported"));
1096                 sendNextCap();
1097             }
1098         } else {
1099 #endif
1100             if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
1101                 // PLAIN authentication supported, send request
1102                 // Only working with PLAIN atm, blowfish later
1103                 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
1104             } else {
1105                 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1106                            tr("SASL PLAIN authentication not supported"));
1107                 sendNextCap();
1108             }
1109 #ifdef HAVE_SSL
1110         }
1111 #endif
1112     }
1113 }
1114
1115 void CoreNetwork::serverCapRemoved(const QString &capability)
1116 {
1117     // This may be called multiple times in certain situations.
1118
1119     // Handle special cases here
1120     if (capability == IrcCap::AWAY_NOTIFY) {
1121         // away-notify disabled, enable autoWho according to configuration
1122         setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
1123     }
1124 }
1125
1126 void CoreNetwork::queueCap(const QString &capability)
1127 {
1128     // IRCv3 specs all use lowercase capability names
1129     QString _capLowercase = capability.toLower();
1130
1131     if(capsRequiringConfiguration.contains(_capLowercase)) {
1132         // The capability requires additional configuration before being acknowledged (e.g. SASL),
1133         // so we should negotiate it separately from all other capabilities.  Otherwise new
1134         // capabilities will be requested while still configuring the previous one.
1135         if (!_capsQueuedIndividual.contains(_capLowercase)) {
1136             _capsQueuedIndividual.append(_capLowercase);
1137         }
1138     } else {
1139         // The capability doesn't need any special configuration, so it should be safe to try
1140         // bundling together with others.  "Should" being the imperative word, as IRC servers can do
1141         // anything.
1142         if (!_capsQueuedBundled.contains(_capLowercase)) {
1143             _capsQueuedBundled.append(_capLowercase);
1144         }
1145     }
1146 }
1147
1148 QString CoreNetwork::takeQueuedCaps()
1149 {
1150     // Clear the record of the most recently negotiated capability bundle.  Does nothing if the list
1151     // is empty.
1152     _capsQueuedLastBundle.clear();
1153
1154     // First, negotiate all the standalone capabilities that require additional configuration.
1155     if (!_capsQueuedIndividual.empty()) {
1156         // We have an individual capability available.  Take the first and pass it back.
1157         return _capsQueuedIndividual.takeFirst();
1158     } else if (!_capsQueuedBundled.empty()) {
1159         // We have capabilities available that can be grouped.  Try to fit in as many as within the
1160         // maximum length.
1161         // See CoreNetwork::maxCapRequestLength
1162
1163         // Response must have at least one capability regardless of max length for anything to
1164         // happen.
1165         QString capBundle = _capsQueuedBundled.takeFirst();
1166         QString nextCap("");
1167         while (!_capsQueuedBundled.empty()) {
1168             // As long as capabilities remain, get the next...
1169             nextCap = _capsQueuedBundled.first();
1170             if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1171                 // [capability + 1 for a space + this new capability] fit within length limits
1172                 // Add it to formatted list
1173                 capBundle.append(" " + nextCap);
1174                 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1175                 _capsQueuedLastBundle.append(nextCap);
1176                 // Then remove it from the queue
1177                 _capsQueuedBundled.removeFirst();
1178             } else {
1179                 // We've reached the length limit for a single capability request, stop adding more
1180                 break;
1181             }
1182         }
1183         // Return this space-separated set of capabilities, removing any extra spaces
1184         return capBundle.trimmed();
1185     } else {
1186         // No capabilities left to negotiate, return an empty string.
1187         return QString();
1188     }
1189 }
1190
1191 void CoreNetwork::retryCapsIndividually()
1192 {
1193     // The most recent set of capabilities got denied by the IRC server.  As we don't know what got
1194     // denied, try each capability individually.
1195     if (_capsQueuedLastBundle.empty()) {
1196         // No most recently tried capability set, just return.
1197         return;
1198         // Note: there's little point in retrying individually requested caps during negotiation.
1199         // We know the individual capability was the one that failed, and it's not likely it'll
1200         // suddenly start working within a few seconds.  'cap-notify' provides a better system for
1201         // handling capability removal and addition.
1202     }
1203
1204     // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1205     // over efficiency.  If this becomes an issue, implement a binary splicing system instead,
1206     // keeping track of which halves of the group fail, dividing the set each time.
1207
1208     // Add most recently tried capability set to individual list, re-requesting them one at a time
1209     _capsQueuedIndividual.append(_capsQueuedLastBundle);
1210     // Warn of this issue to explain the slower login.  Servers usually shouldn't trigger this.
1211     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1212                tr("Could not negotiate some capabilities, retrying individually (%1)...")
1213                .arg(_capsQueuedLastBundle.join(", ")));
1214     // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1215     // need to remove them here.
1216     // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1217     // indefinitely.
1218     _capsQueuedLastBundle.clear();
1219 }
1220
1221 void CoreNetwork::beginCapNegotiation()
1222 {
1223     // Don't begin negotiation if no capabilities are queued to request
1224     if (!capNegotiationInProgress()) {
1225         // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1226         // normal connection.
1227         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1228         endCapNegotiation();
1229         return;
1230     }
1231
1232     _capNegotiationActive = true;
1233     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1234                tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1235
1236     // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1237     // comma separator between the two if needed (both individual and bundled caps exist).
1238     QString queuedCapsDisplay =
1239             _capsQueuedIndividual.join(", ")
1240             + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
1241             + _capsQueuedBundled.join(", ");
1242     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1243                tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1244
1245     sendNextCap();
1246 }
1247
1248 void CoreNetwork::sendNextCap()
1249 {
1250     if (capNegotiationInProgress()) {
1251         // Request the next set of capabilities and remove them from the list
1252         putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1253     } else {
1254         // No pending desired capabilities, capability negotiation finished
1255         // If SASL requested but not available, print a warning
1256         if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1257             displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1258                        tr("SASL authentication currently not supported by server"));
1259
1260         if (_capNegotiationActive) {
1261             displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1262                    tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1263             _capNegotiationActive = false;
1264         }
1265
1266         endCapNegotiation();
1267     }
1268 }
1269
1270 void CoreNetwork::endCapNegotiation()
1271 {
1272     // If nick registration is already complete, CAP END is not required
1273     if (!_capInitialNegotiationEnded) {
1274         putRawLine(serverEncode(QString("CAP END")));
1275         _capInitialNegotiationEnded = true;
1276     }
1277 }
1278
1279 /******** AutoWHO ********/
1280
1281 void CoreNetwork::startAutoWhoCycle()
1282 {
1283     if (!_autoWhoQueue.isEmpty()) {
1284         _autoWhoCycleTimer.stop();
1285         return;
1286     }
1287     _autoWhoQueue = channels();
1288 }
1289
1290 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1291 {
1292     // Prepend so these new channels/nicks are the first to be checked
1293     // Don't allow duplicates
1294     if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1295         _autoWhoQueue.prepend(channelOrNick.toLower());
1296     }
1297     if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1298         // When away-notify is active, the timer's stopped.  Start a new cycle to who this channel.
1299         setAutoWhoEnabled(true);
1300     }
1301 }
1302
1303
1304 void CoreNetwork::setAutoWhoDelay(int delay)
1305 {
1306     _autoWhoTimer.setInterval(delay * 1000);
1307 }
1308
1309
1310 void CoreNetwork::setAutoWhoInterval(int interval)
1311 {
1312     _autoWhoCycleTimer.setInterval(interval * 1000);
1313 }
1314
1315
1316 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1317 {
1318     if (enabled && isConnected() && !_autoWhoTimer.isActive())
1319         _autoWhoTimer.start();
1320     else if (!enabled) {
1321         _autoWhoTimer.stop();
1322         _autoWhoCycleTimer.stop();
1323     }
1324 }
1325
1326
1327 void CoreNetwork::sendAutoWho()
1328 {
1329     // Don't send autowho if there are still some pending
1330     if (_autoWhoPending.count())
1331         return;
1332
1333     while (!_autoWhoQueue.isEmpty()) {
1334         QString chanOrNick = _autoWhoQueue.takeFirst();
1335         // Check if it's a known channel or nick
1336         IrcChannel *ircchan = ircChannel(chanOrNick);
1337         IrcUser *ircuser = ircUser(chanOrNick);
1338         if (ircchan) {
1339             // Apply channel limiting rules
1340             // If using away-notify, don't impose channel size limits in order to capture away
1341             // state of everyone.  Auto-who won't run on a timer so network impact is minimal.
1342             if (networkConfig()->autoWhoNickLimit() > 0
1343                 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1344                 && !capEnabled(IrcCap::AWAY_NOTIFY))
1345                 continue;
1346             _autoWhoPending[chanOrNick.toLower()]++;
1347         } else if (ircuser) {
1348             // Checking a nick, add it to the pending list
1349             _autoWhoPending[ircuser->nick().toLower()]++;
1350         } else {
1351             // Not a channel or a nick, skip it
1352             qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1353             continue;
1354         }
1355         if (supports("WHOX")) {
1356             // Use WHO extended to poll away users and/or user accounts
1357             // See http://faerion.sourceforge.net/doc/irc/whox.var
1358             // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1359             putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1360                                     .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1361         } else {
1362             putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1363         }
1364         break;
1365     }
1366
1367     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1368         && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1369         // Timer was stopped, means a new cycle is due immediately
1370         // Don't run a new cycle if using away-notify; server will notify as appropriate
1371         _autoWhoCycleTimer.start();
1372         startAutoWhoCycle();
1373     } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1374         // Don't run another who cycle if away-notify is enabled
1375         _autoWhoCycleTimer.stop();
1376     }
1377 }
1378
1379
1380 #ifdef HAVE_SSL
1381 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1382 {
1383     Server server = usedServer();
1384     if (server.sslVerify) {
1385         // Treat the SSL error as a hard error
1386         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1387                                      "since verification is required");
1388         if (!sslErrors.empty()) {
1389             // Add the error reason if known
1390             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1391         }
1392         displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1393
1394         // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1395         // validity, network trouble, etc.
1396         disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1397     } else {
1398         // Treat the SSL error as a warning, continue to connect anyways
1399         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1400                                      "since verification is not required");
1401         if (!sslErrors.empty()) {
1402             // Add the error reason if known
1403             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1404         }
1405         displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1406
1407         // Proceed with the connection
1408         socket.ignoreSslErrors();
1409     }
1410 }
1411
1412
1413 #endif  // HAVE_SSL
1414
1415 void CoreNetwork::checkTokenBucket()
1416 {
1417     if (_skipMessageRates) {
1418         if (_msgQueue.size() == 0) {
1419             // Message queue emptied; stop the timer and bail out
1420             _tokenBucketTimer.stop();
1421             return;
1422         }
1423         // Otherwise, we're emptying the queue, continue on as normal
1424     }
1425
1426     // Process whatever messages are pending
1427     fillBucketAndProcessQueue();
1428 }
1429
1430
1431 void CoreNetwork::fillBucketAndProcessQueue()
1432 {
1433     // If there's less tokens than burst size, refill the token bucket by 1
1434     if (_tokenBucket < _burstSize) {
1435         _tokenBucket++;
1436     }
1437
1438     // As long as there's tokens available and messages remaining, sending messages from the queue
1439     while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1440         writeToSocket(_msgQueue.takeFirst());
1441     }
1442 }
1443
1444
1445 void CoreNetwork::writeToSocket(const QByteArray &data)
1446 {
1447     socket.write(data);
1448     socket.write("\r\n");
1449     if (!_skipMessageRates) {
1450         // Only subtract from the token bucket if message rate limiting is enabled
1451         _tokenBucket--;
1452     }
1453 }
1454
1455
1456 Network::Server CoreNetwork::usedServer() const
1457 {
1458     if (_lastUsedServerIndex < serverList().count())
1459         return serverList()[_lastUsedServerIndex];
1460
1461     if (!serverList().isEmpty())
1462         return serverList()[0];
1463
1464     return Network::Server();
1465 }
1466
1467
1468 void CoreNetwork::requestConnect() const
1469 {
1470     if (connectionState() != Disconnected) {
1471         qWarning() << "Requesting connect while already being connected!";
1472         return;
1473     }
1474     QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1475 }
1476
1477
1478 void CoreNetwork::requestDisconnect() const
1479 {
1480     if (connectionState() == Disconnected) {
1481         qWarning() << "Requesting disconnect while not being connected!";
1482         return;
1483     }
1484     userInputHandler()->handleQuit(BufferInfo(), QString());
1485 }
1486
1487
1488 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1489 {
1490     Network::Server currentServer = usedServer();
1491     setNetworkInfo(info);
1492     Core::updateNetwork(coreSession()->user(), info);
1493
1494     // the order of the servers might have changed,
1495     // so we try to find the previously used server
1496     _lastUsedServerIndex = 0;
1497     for (int i = 0; i < serverList().count(); i++) {
1498         Network::Server server = serverList()[i];
1499         if (server.host == currentServer.host && server.port == currentServer.port) {
1500             _lastUsedServerIndex = i;
1501             break;
1502         }
1503     }
1504 }
1505
1506
1507 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1508 {
1509     QString wrkMsg(message);
1510     QList<QList<QByteArray>> msgsToSend;
1511
1512     // do while (wrkMsg.size() > 0)
1513     do {
1514         // First, check to see if the whole message can be sent at once.  The
1515         // cmdGenerator function is passed in by the caller and is used to encode
1516         // and encrypt (if applicable) the message, since different callers might
1517         // want to use different encoding or encode different values.
1518         int splitPos = wrkMsg.size();
1519         QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1520         int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1521
1522         if (initialOverrun) {
1523             // If the message was too long to be sent, first try splitting it along
1524             // word boundaries with QTextBoundaryFinder.
1525             QString splitMsg(wrkMsg);
1526             QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1527             qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1528             QList<QByteArray> splitMsgEnc;
1529             int overrun = initialOverrun;
1530
1531             while (overrun) {
1532                 splitPos = qtbf.toPreviousBoundary();
1533
1534                 // splitPos==-1 means the QTBF couldn't find a split point at all and
1535                 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1536                 // the string.  Neither one of these works for us.
1537                 if (splitPos > 0) {
1538                     // If a split point could be found, split the message there, calculate the
1539                     // overrun, and continue with the loop.
1540                     splitMsg = splitMsg.left(splitPos);
1541                     splitMsgEnc = cmdGenerator(splitMsg);
1542                     overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1543                 }
1544                 else {
1545                     // If a split point could not be found (the beginning of the message
1546                     // is reached without finding a split point short enough to send) and we
1547                     // are still in Word mode, switch to Grapheme mode.  We also need to restore
1548                     // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1549                     // the previous attempt to find a split point.
1550                     if (qtbf.type() == QTextBoundaryFinder::Word) {
1551                         splitMsg = wrkMsg;
1552                         splitPos = splitMsg.size();
1553                         QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1554                         graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1555                         qtbf = graphemeQtbf;
1556                     }
1557                     else {
1558                         // If the QTBF fails to find a split point in Grapheme mode, we give up.
1559                         // This should never happen, but it should be handled anyway.
1560                         qWarning() << "Unexpected failure to split message!";
1561                         return msgsToSend;
1562                     }
1563                 }
1564             }
1565
1566             // Once a message of sendable length has been found, remove it from the wrkMsg and
1567             // add it to the list of messages to be sent.
1568             wrkMsg.remove(0, splitPos);
1569             msgsToSend.append(splitMsgEnc);
1570         }
1571         else{
1572             // If the entire remaining message is short enough to be sent all at once, remove
1573             // it from the wrkMsg and add it to the list of messages to be sent.
1574             wrkMsg.remove(0, splitPos);
1575             msgsToSend.append(initialSplitMsgEnc);
1576         }
1577     } while (wrkMsg.size() > 0);
1578
1579     return msgsToSend;
1580 }