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