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