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