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