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