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