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