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