+ state = Network::Disconnected;
+ }
+ setConnectionState(state);
+}
+
+
+void CoreNetwork::networkInitialized()
+{
+ setConnectionState(Network::Initialized);
+ setConnected(true);
+ _disconnectExpected = false;
+ _quitRequested = false;
+
+ // Update the TokenBucket with specified rate-limiting settings, removing the force-unlimited
+ // flag used for initial registration and capability negotiation.
+ updateRateLimiting();
+
+ if (useAutoReconnect()) {
+ // reset counter
+ _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
+ }
+
+ // restore away state
+ QString awayMsg = Core::awayMessage(userId(), networkId());
+ if (!awayMsg.isEmpty()) {
+ // Don't re-apply any timestamp formatting in order to preserve escaped percent signs, e.g.
+ // '%%%%%%%%' -> '%%%%' If processed again, it'd result in '%%'.
+ userInputHandler()->handleAway(BufferInfo(), awayMsg, true);
+ }
+
+ sendPerform();
+
+ _sendPings = true;
+
+ if (networkConfig()->autoWhoEnabled()) {
+ _autoWhoCycleTimer.start();
+ _autoWhoTimer.start();
+ startAutoWhoCycle(); // FIXME wait for autojoin to be completed
+ }
+
+ Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
+ Core::setNetworkConnected(userId(), networkId(), true);
+}
+
+
+void CoreNetwork::sendPerform()
+{
+ BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
+
+ // do auto identify
+ if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
+ userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
+ }
+
+ // restore old user modes if server default mode is set.
+ IrcUser *me_ = me();
+ if (me_) {
+ if (!me_->userModes().isEmpty()) {
+ restoreUserModes();
+ }
+ else {
+ connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
+ connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
+ }
+ }
+
+ // send perform list
+ foreach(QString line, perform()) {
+ if (!line.isEmpty()) userInput(statusBuf, line);
+ }
+
+ // rejoin channels we've been in
+ if (rejoinChannels()) {
+ QStringList channels, keys;
+ foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
+ QString key = channelKey(chan);
+ if (!key.isEmpty()) {
+ channels.prepend(chan);
+ keys.prepend(key);
+ }
+ else {
+ channels.append(chan);
+ }
+ }
+ QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
+ if (!joinString.isEmpty())
+ userInputHandler()->handleJoin(statusBuf, joinString);
+ }
+}
+
+
+void CoreNetwork::restoreUserModes()
+{
+ IrcUser *me_ = me();
+ Q_ASSERT(me_);
+
+ disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
+ disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
+
+ QString modesDelta = Core::userModes(userId(), networkId());
+ QString currentModes = me_->userModes();
+
+ QString addModes, removeModes;
+ if (modesDelta.contains('-')) {
+ addModes = modesDelta.section('-', 0, 0);
+ removeModes = modesDelta.section('-', 1);
+ }
+ else {
+ addModes = modesDelta;
+ }
+
+ addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
+ if (currentModes.isEmpty())
+ removeModes = QString();
+ else
+ removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
+
+ if (addModes.isEmpty() && removeModes.isEmpty())
+ return;
+
+ if (!addModes.isEmpty())
+ addModes = '+' + addModes;
+ if (!removeModes.isEmpty())
+ removeModes = '-' + removeModes;
+
+ // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
+ putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
+}
+
+
+void CoreNetwork::updateIssuedModes(const QString &requestedModes)
+{
+ QString addModes;
+ QString removeModes;
+ bool addMode = true;
+
+ for (int i = 0; i < requestedModes.length(); i++) {
+ if (requestedModes[i] == '+') {
+ addMode = true;
+ continue;
+ }
+ if (requestedModes[i] == '-') {
+ addMode = false;
+ continue;
+ }
+ if (addMode) {
+ addModes += requestedModes[i];
+ }
+ else {
+ removeModes += requestedModes[i];
+ }
+ }
+
+ QString addModesOld = _requestedUserModes.section('-', 0, 0);
+ QString removeModesOld = _requestedUserModes.section('-', 1);
+
+ addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
+ addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
+ addModes += addModesOld;
+
+ removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
+ removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
+ removeModes += removeModesOld;
+
+ _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
+}
+
+
+void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
+{
+ QString persistentUserModes = Core::userModes(userId(), networkId());
+
+ QString requestedAdd = _requestedUserModes.section('-', 0, 0);
+ QString requestedRemove = _requestedUserModes.section('-', 1);
+
+ QString persistentAdd, persistentRemove;
+ if (persistentUserModes.contains('-')) {
+ persistentAdd = persistentUserModes.section('-', 0, 0);
+ persistentRemove = persistentUserModes.section('-', 1);
+ }
+ else {
+ persistentAdd = persistentUserModes;
+ }
+
+ // remove modes we didn't issue
+ if (requestedAdd.isEmpty())
+ addModes = QString();
+ else
+ addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
+
+ if (requestedRemove.isEmpty())
+ removeModes = QString();
+ else
+ removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
+
+ // deduplicate
+ persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
+ persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
+
+ // update
+ persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
+ persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
+
+ // update issued mode list
+ requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
+ requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
+ _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
+
+ persistentAdd += addModes;
+ persistentRemove += removeModes;
+ Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
+}
+
+
+void CoreNetwork::resetPersistentModes()
+{
+ _requestedUserModes = QString('-');
+ Core::setUserModes(userId(), networkId(), QString());
+}
+
+
+void CoreNetwork::setUseAutoReconnect(bool use)
+{
+ Network::setUseAutoReconnect(use);
+ if (!use)
+ _autoReconnectTimer.stop();
+}
+
+
+void CoreNetwork::setAutoReconnectInterval(quint32 interval)
+{
+ Network::setAutoReconnectInterval(interval);
+ _autoReconnectTimer.setInterval(interval * 1000);
+}
+
+
+void CoreNetwork::setAutoReconnectRetries(quint16 retries)
+{
+ Network::setAutoReconnectRetries(retries);
+ if (_autoReconnectCount != 0) {
+ if (unlimitedReconnectRetries())
+ _autoReconnectCount = -1;
+ else
+ _autoReconnectCount = autoReconnectRetries();
+ }
+}
+
+
+void CoreNetwork::doAutoReconnect()
+{
+ if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
+ qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
+ return;
+ }
+ if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
+ _autoReconnectCount--; // -2 means we delay the next reconnect
+ connectToIrc(true);
+}
+
+
+void CoreNetwork::sendPing()
+{
+ qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
+ if (_pingCount != 0) {
+ qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
+ << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
+ }
+ if ((int)_pingCount >= networkConfig()->maxPingCount()
+ && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
+ // In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
+ // However, to reduce the risk of breaking things by changing past behavior, we still allow
+ // up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
+ //
+ // the second check compares the actual elapsed time since the last ping and the pingTimer interval
+ // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
+ // and unable to even handle a ping answer. So we ignore those misses.
+ disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
+ }
+ else {
+ _lastPingTime = now;
+ _pingCount++;
+ // Don't send pings until the network is initialized
+ if(_sendPings)
+ userInputHandler()->handlePing(BufferInfo(), QString());
+ }
+}
+
+
+void CoreNetwork::enablePingTimeout(bool enable)
+{
+ if (!enable)
+ disablePingTimeout();
+ else {
+ resetPingTimeout();
+ if (networkConfig()->pingTimeoutEnabled())
+ _pingTimer.start();
+ }
+}
+
+
+void CoreNetwork::disablePingTimeout()
+{
+ _pingTimer.stop();
+ _sendPings = false;
+ resetPingTimeout();
+}
+
+
+void CoreNetwork::setPingInterval(int interval)
+{
+ _pingTimer.setInterval(interval * 1000);
+}
+
+
+/******** Custom Rate Limiting ********/
+
+void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
+{
+ // Verify and apply custom rate limiting options, always resetting the delay and burst size
+ // (safe-guarding against accidentally starting the timer), but don't reset the token bucket as
+ // this may be called while connected to a server.
+
+ if (useCustomMessageRate() || forceUnlimited) {
+ // Custom message rates enabled, or chosen by means of forcing unlimited. Let's go for it!
+
+ _messageDelay = messageRateDelay();
+
+ _burstSize = messageRateBurstSize();
+ if (_burstSize < 1) {
+ qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
+ << _burstSize;
+ // Can't go slower than one message at a time
+ _burstSize = 1;
+ }
+
+ if (_tokenBucket > _burstSize) {
+ // Don't let the token bucket exceed the maximum
+ _tokenBucket = _burstSize;
+ // To fill up the token bucket, use resetRateLimiting(). Don't do that here, otherwise
+ // changing the rate-limit settings while connected to a server will incorrectly reset
+ // the token bucket.
+ }
+
+ // Toggle the timer according to whether or not rate limiting is enabled
+ // If we're here, either useCustomMessageRate or forceUnlimited is true. Thus, the logic is
+ // _skipMessageRates = ((useCustomMessageRate && unlimitedMessageRate) || forceUnlimited)
+ // Override user preferences if called with force unlimited, only used during connect.
+ _skipMessageRates = (unlimitedMessageRate() || forceUnlimited);
+ if (_skipMessageRates) {
+ // If the message queue already contains messages, they need sent before disabling the
+ // timer. Set the timer to a rapid pace and let it disable itself.
+ if (_msgQueue.size() > 0) {
+ qDebug() << "Outgoing message queue contains messages while disabling rate "
+ "limiting. Sending remaining queued messages...";
+ // Promptly run the timer again to clear the messages. Rate limiting is disabled,
+ // so nothing should cause this to block.. in theory. However, don't directly call
+ // fillBucketAndProcessQueue() in order to keep it on a separate thread.
+ //
+ // TODO If testing shows this isn't needed, it can be simplified to a direct call.
+ // Hesitant to change it without a wide variety of situations to verify behavior.
+ _tokenBucketTimer.start(100);
+ } else {
+ // No rate limiting, disable the timer
+ _tokenBucketTimer.stop();
+ }
+ } else {
+ // Rate limiting enabled, enable the timer
+ _tokenBucketTimer.start(_messageDelay);
+ }