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