mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(iot): publish connection lifecycle events (#5277)
* feat(iot): publish connection lifecycle events The MQTT broker publishes $aws/events/presence/connected and disconnected for every session, with its session identifier, certificate principal, version number and disconnect reason, through topic rules and to subscribers. Topic filters starting with a wildcard no longer match $ topics, as on AWS. Closes #5275 * fix(iot): keep lifecycle events within the reset guard A lifecycle event admits its topic rules under the rule state at the time of the event, so one queued before an emulator reset skips them. A DeleteConnection that wins the session tolerates an endpoint the client's DISCONNECT already closed. * fix(iot): serialize session transitions and report keep-alive timeouts Admission, takeover, DeleteConnection and session end now allocate the versionNumber and change the session map under one lock, with endpoint I/O kept outside it. A takeover of an endpoint that is already closed still accepts the new connection. A close after a full keep-alive period without a packet from the client is reported as MQTT_KEEP_ALIVE_TIMEOUT, as AWS IoT does. The WebSocket upgrade carries the client's port, and the wildcard-first exclusion is limited to the lifecycle topics, which AWS does not deliver to such filters while it does deliver shadow topics. * fix(iot): keep ended sessions out of subscriptions and time keep-alive from CONNECT * test(iot): drive keep-alive tests from an injected nano-time source The broker takes a LongSupplier nano-time source, as ReloadingKeyManager does, so the keep-alive unit tests move a fake clock forward instead of sleeping. The race test uses ThreadStates.awaitBlockedOrDone.
This commit is contained in:
1 parent
fcb41966a8
commit
87aa6f38a1
12 files changed
+1488
-79
No files matched your search
@@ -57,9 +57,11 @@ public class IotCustomAuthorizer {
|
||||
/**
|
||||
* What a WebSocket upgrade carried: the header names lower-cased, the raw query without its
|
||||
* {@code ?} ({@code ""} when there was none), the server name, null unless it came over TLS, and
|
||||
* the client's IP address, as the broker sees only the bridge's loopback socket.
|
||||
* the client's IP address and port ({@code -1} when unknown), as the broker sees only the
|
||||
* bridge's loopback socket.
|
||||
*/
|
||||
record WebSocketUpgrade(Map<String, String> headers, String queryString, String serverName, String sourceIp) {
|
||||
record WebSocketUpgrade(Map<String, String> headers, String queryString, String serverName, String sourceIp,
|
||||
int sourcePort) {
|
||||
}
|
||||
|
||||
@Inject
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
|
||||
import io.netty.handler.codec.TooLongFrameException;
|
||||
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
|
||||
import io.netty.handler.codec.mqtt.MqttProperties;
|
||||
import io.netty.handler.codec.mqtt.MqttQoS;
|
||||
@@ -40,6 +43,7 @@ import javax.net.ssl.SSLPeerUnverifiedException;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.X509ExtendedTrustManager;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
@@ -52,9 +56,11 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -113,6 +119,15 @@ public class IotMqttBrokerService implements Resettable {
|
||||
|
||||
static final int MAX_PENDING_RULE_EVALUATIONS = 1_000;
|
||||
|
||||
static final String CLIENT_INITIATED_DISCONNECT = "CLIENT_INITIATED_DISCONNECT";
|
||||
static final String CONNECTION_LOST = "CONNECTION_LOST";
|
||||
static final String MQTT_KEEP_ALIVE_TIMEOUT = "MQTT_KEEP_ALIVE_TIMEOUT";
|
||||
static final String PRESENCE_TOPIC_PREFIX = "$aws/events/presence/";
|
||||
private static final String DUPLICATE_CLIENTID = "DUPLICATE_CLIENTID";
|
||||
private static final String API_INITIATED_DISCONNECT = "API_INITIATED_DISCONNECT";
|
||||
private static final String CLIENT_ERROR = "CLIENT_ERROR";
|
||||
private static final long KEEP_ALIVE_SLACK_NANOS = TimeUnit.MILLISECONDS.toNanos(250);
|
||||
|
||||
private static final long RULES_RESETTING = 1;
|
||||
private static final long RULES_STOPPED = 2;
|
||||
private static final long RULE_STATE_STEP = 4;
|
||||
@@ -122,9 +137,14 @@ public class IotMqttBrokerService implements Resettable {
|
||||
private final Instance<IotService> iotService;
|
||||
private final IotCustomAuthorizer customAuthorizer;
|
||||
private final TlsConfigurationRegistry tlsRegistry;
|
||||
private final LongSupplier nanoTime;
|
||||
final WorkerExecutor ruleWorker;
|
||||
private final Map<String, ClientSession> sessionsByClient = new ConcurrentHashMap<>();
|
||||
private final Map<String, Map<String, Subscription>> subscriptionsByClient = new ConcurrentHashMap<>();
|
||||
/** Serializes admitting and ending sessions and the versionNumbers they take; never held across endpoint I/O. */
|
||||
private final Object sessionLock = new Object();
|
||||
/** The last lifecycle event versionNumber per client id; neither a state reset nor a broker restart clears it. */
|
||||
private final Map<String, Long> presenceVersions = new ConcurrentHashMap<>();
|
||||
private final AtomicInteger pendingRuleEvaluations = new AtomicInteger();
|
||||
private final AtomicBoolean ruleEvaluationsThrottled = new AtomicBoolean();
|
||||
/**
|
||||
@@ -141,11 +161,17 @@ public class IotMqttBrokerService implements Resettable {
|
||||
@Inject
|
||||
public IotMqttBrokerService(EmulatorConfig config, Vertx vertx, Instance<IotService> iotService,
|
||||
IotCustomAuthorizer customAuthorizer, TlsConfigurationRegistry tlsRegistry) {
|
||||
this(config, vertx, iotService, customAuthorizer, tlsRegistry, System::nanoTime);
|
||||
}
|
||||
|
||||
IotMqttBrokerService(EmulatorConfig config, Vertx vertx, Instance<IotService> iotService,
|
||||
IotCustomAuthorizer customAuthorizer, TlsConfigurationRegistry tlsRegistry, LongSupplier nanoTime) {
|
||||
this.config = config;
|
||||
this.vertx = vertx;
|
||||
this.iotService = iotService;
|
||||
this.customAuthorizer = customAuthorizer;
|
||||
this.tlsRegistry = tlsRegistry;
|
||||
this.nanoTime = nanoTime;
|
||||
this.ruleWorker = vertx.createSharedWorkerExecutor("floci-iot-mqtt-rules", 1);
|
||||
}
|
||||
|
||||
@@ -305,11 +331,9 @@ public class IotMqttBrokerService implements Resettable {
|
||||
tlsServer = null;
|
||||
keyManager = null;
|
||||
sessionsByClient.values().forEach(session -> {
|
||||
try {
|
||||
session.endpoint().close();
|
||||
} catch (IllegalStateException e) {
|
||||
LOG.debugv("IoT MQTT client {0} was already closed during broker shutdown", session.clientId());
|
||||
}
|
||||
// Ended before the close, so a broker shutdown publishes no disconnected event.
|
||||
session.ended().set(true);
|
||||
closeEndpoint(session);
|
||||
});
|
||||
sessionsByClient.clear();
|
||||
subscriptionsByClient.clear();
|
||||
@@ -348,17 +372,28 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
boolean disconnectClient(String clientId, boolean cleanSession) {
|
||||
ClientSession session = sessionsByClient.remove(clientId);
|
||||
if (session == null) {
|
||||
return false;
|
||||
ClientSession session;
|
||||
synchronized (sessionLock) {
|
||||
session = sessionsByClient.get(clientId);
|
||||
if (session == null || !endSession(session, API_INITIATED_DISCONNECT)) {
|
||||
return false;
|
||||
}
|
||||
if (cleanSession) {
|
||||
subscriptionsByClient.remove(clientId);
|
||||
}
|
||||
}
|
||||
if (cleanSession) {
|
||||
subscriptionsByClient.remove(clientId);
|
||||
}
|
||||
session.endpoint().close();
|
||||
closeEndpoint(session);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void closeEndpoint(ClientSession session) {
|
||||
try {
|
||||
session.endpoint().close();
|
||||
} catch (IllegalStateException e) {
|
||||
LOG.debugv("IoT MQTT client {0} was already closed", session.clientId());
|
||||
}
|
||||
}
|
||||
|
||||
Optional<ConnectionInfo> getConnection(String clientId) {
|
||||
if (server == null) {
|
||||
return Optional.empty();
|
||||
@@ -385,9 +420,11 @@ public class IotMqttBrokerService implements Resettable {
|
||||
* every client except one that names a custom authorizer, see {@link #authorizeCustom}.
|
||||
*/
|
||||
void handleEndpoint(MqttEndpoint endpoint, boolean verifyDevice) {
|
||||
long connectNanos = nanoTime.getAsLong();
|
||||
String clientId = endpoint.clientIdentifier();
|
||||
SocketAddress remoteAddress = endpoint.remoteAddress();
|
||||
String sourceIp = remoteAddress == null ? null : remoteAddress.host();
|
||||
int sourcePort = remoteAddress == null ? -1 : remoteAddress.port();
|
||||
String principal = null;
|
||||
if (verifyDevice) {
|
||||
principal = admittedDevice(endpoint, clientId, sourceIp);
|
||||
@@ -399,14 +436,18 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
} else {
|
||||
IotCustomAuthorizer.WebSocketUpgrade upgrade = remoteAddress == null ? null : webSocketUpgrades.remove(remoteAddress);
|
||||
if (upgrade != null && upgrade.sourceIp() != null) {
|
||||
sourceIp = upgrade.sourceIp();
|
||||
sourcePort = upgrade.sourcePort();
|
||||
}
|
||||
String username = endpoint.auth() == null ? null : endpoint.auth().getUsername();
|
||||
String authorizerName = IotCustomAuthorizer.authorizerName(username, upgrade);
|
||||
if (authorizerName != null) {
|
||||
authorizeCustom(endpoint, authorizerName, upgrade, upgrade == null ? sourceIp : upgrade.sourceIp());
|
||||
authorizeCustom(endpoint, authorizerName, upgrade, sourceIp, sourcePort, connectNanos);
|
||||
return;
|
||||
}
|
||||
}
|
||||
admit(endpoint, principal);
|
||||
admit(endpoint, principal, sourceIp, sourcePort, connectNanos);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -416,7 +457,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
* MQTT 5 with reason code 0x87, as AWS IoT does.
|
||||
*/
|
||||
private void authorizeCustom(MqttEndpoint endpoint, String authorizerName, IotCustomAuthorizer.WebSocketUpgrade upgrade,
|
||||
String sourceIp) {
|
||||
String sourceIp, int sourcePort, long connectNanos) {
|
||||
String clientId = endpoint.clientIdentifier();
|
||||
String username = endpoint.auth() == null ? null : endpoint.auth().getUsername();
|
||||
String password = endpoint.auth() == null ? null : endpoint.auth().getPassword();
|
||||
@@ -431,7 +472,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
return;
|
||||
}
|
||||
if (decision.succeeded() && decision.result()) {
|
||||
admit(endpoint, null);
|
||||
admit(endpoint, null, sourceIp, sourcePort, connectNanos);
|
||||
return;
|
||||
}
|
||||
LOG.debugv("IoT MQTT client {0} refused by custom authorizer {1}: {2}", clientId, authorizerName,
|
||||
@@ -447,39 +488,72 @@ public class IotMqttBrokerService implements Resettable {
|
||||
});
|
||||
}
|
||||
|
||||
private void admit(MqttEndpoint endpoint, String principal) {
|
||||
/**
|
||||
* {@code principal} is the certificate id a TLS client was admitted with, null otherwise.
|
||||
* {@code clientIp} and {@code clientPort} are the address the client connected from: the
|
||||
* socket's, or for a WebSocket client the one the bridge recorded at the upgrade, as the
|
||||
* bridge's own socket is loopback. {@code connectNanos} is when the CONNECT arrived, which
|
||||
* the keep-alive runs from.
|
||||
*/
|
||||
private void admit(MqttEndpoint endpoint, String principal, String clientIp, int clientPort, long connectNanos) {
|
||||
String clientId = endpoint.clientIdentifier();
|
||||
SocketAddress remoteAddress = endpoint.remoteAddress();
|
||||
String sourceIp = remoteAddress == null ? null : remoteAddress.host();
|
||||
ClientSession session = new ClientSession(
|
||||
clientId,
|
||||
endpoint,
|
||||
sourceIp,
|
||||
remoteAddress == null ? -1 : remoteAddress.port(),
|
||||
endpoint.isCleanSession());
|
||||
|
||||
endpoint.subscriptionAutoAck(false);
|
||||
endpoint.publishAutoAck(false);
|
||||
endpoint.exceptionHandler(error -> LOG.warnv("IoT MQTT client {0} error: {1}", clientId, error.getMessage()));
|
||||
endpoint.subscribeHandler(message -> handleSubscribe(session, message));
|
||||
endpoint.unsubscribeHandler(message -> handleUnsubscribe(session, message));
|
||||
endpoint.publishHandler(message -> handlePublish(session, message));
|
||||
endpoint.disconnectHandler(ignored -> removeSession(session));
|
||||
endpoint.closeHandler(ignored -> removeSession(session));
|
||||
|
||||
ClientSession previous = sessionsByClient.put(clientId, session);
|
||||
if (previous != null && previous.endpoint() != endpoint) {
|
||||
previous.endpoint().close();
|
||||
boolean cleanSession = endpoint.isCleanSession();
|
||||
ClientSession session;
|
||||
ClientSession replaced = null;
|
||||
synchronized (sessionLock) {
|
||||
long versionNumber = presenceVersions.merge(clientId, 0L, (last, unused) -> last + 1);
|
||||
session = new ClientSession(
|
||||
clientId,
|
||||
endpoint,
|
||||
clientIp,
|
||||
clientPort,
|
||||
cleanSession,
|
||||
UUID.randomUUID().toString(),
|
||||
principal,
|
||||
versionNumber,
|
||||
new AtomicBoolean(),
|
||||
new AtomicLong(connectNanos));
|
||||
ClientSession previous = sessionsByClient.put(clientId, session);
|
||||
if (previous != null && previous.endpoint() != endpoint) {
|
||||
endSession(previous, DUPLICATE_CLIENTID);
|
||||
replaced = previous;
|
||||
}
|
||||
}
|
||||
if (replaced != null) {
|
||||
closeEndpoint(replaced);
|
||||
}
|
||||
|
||||
endpoint.accept();
|
||||
try {
|
||||
endpoint.subscriptionAutoAck(false);
|
||||
endpoint.publishAutoAck(false);
|
||||
endpoint.exceptionHandler(error -> {
|
||||
LOG.warnv("IoT MQTT client {0} error: {1}", clientId, error.getMessage());
|
||||
if (error instanceof TooLongFrameException) {
|
||||
endSession(session, CLIENT_ERROR);
|
||||
endpoint.close();
|
||||
}
|
||||
});
|
||||
endpoint.subscribeHandler(message -> handleSubscribe(session, message));
|
||||
endpoint.unsubscribeHandler(message -> handleUnsubscribe(session, message));
|
||||
endpoint.publishHandler(message -> handlePublish(session, message));
|
||||
endpoint.pingHandler(ignored -> received(session));
|
||||
endpoint.publishAcknowledgeHandler(ignored -> received(session));
|
||||
endpoint.disconnectHandler(ignored -> endSession(session, CLIENT_INITIATED_DISCONNECT));
|
||||
endpoint.closeHandler(ignored -> endSession(session, keepAliveExpired(session) ? MQTT_KEEP_ALIVE_TIMEOUT : CONNECTION_LOST));
|
||||
endpoint.accept();
|
||||
} catch (IllegalStateException e) {
|
||||
// Only another thread closes the endpoint here: a takeover, DeleteConnection or stop,
|
||||
// each of which has already ended the session, so its connected event pairs with that.
|
||||
LOG.debugv("IoT MQTT client {0} closed before it was accepted: {1}", clientId, e.getMessage());
|
||||
}
|
||||
if (principal != null) {
|
||||
LOG.debugv("IoT MQTT TLS client {0} admitted as {1}", clientId, principal);
|
||||
}
|
||||
publishPresence(session, "connected", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The certificate ARN of the device behind the connection when it may connect, otherwise null.
|
||||
* The certificate id of the device behind the connection when it may connect, otherwise null.
|
||||
* A failure while deciding refuses the client rather than leaving the CONNECT unanswered. A
|
||||
* refusal is the client's own doing and reaches it as the CONNACK, so it is logged at debug
|
||||
* only: the CONNECT is reachable by anyone.
|
||||
@@ -491,12 +565,12 @@ public class IotMqttBrokerService implements Resettable {
|
||||
LOG.debugv("IoT MQTT TLS client {0} refused: no registered certificate presented", clientId);
|
||||
return null;
|
||||
}
|
||||
String certificateArn = device.get().certificate().getCertificateArn();
|
||||
String certificateId = device.get().certificate().getCertificateId();
|
||||
if (!iotService.get().isConnectAllowed(device.get(), clientId, sourceIp, requestedServerName(endpoint.sslSession()))) {
|
||||
LOG.debugv("IoT MQTT TLS client {0} refused: iot:Connect is not allowed for {1}", clientId, certificateArn);
|
||||
LOG.debugv("IoT MQTT TLS client {0} refused: iot:Connect is not allowed for {1}", clientId, certificateId);
|
||||
return null;
|
||||
}
|
||||
return certificateArn;
|
||||
return certificateId;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "IoT MQTT TLS client {0} refused: device verification failed: {1}", clientId, e.getMessage());
|
||||
return null;
|
||||
@@ -545,8 +619,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
private void handleSubscribe(ClientSession session, MqttSubscribeMessage message) {
|
||||
Map<String, Subscription> clientSubscriptions = subscriptionsByClient.computeIfAbsent(
|
||||
session.clientId(), ignored -> new ConcurrentHashMap<>());
|
||||
received(session);
|
||||
List<MqttQoS> grantedQos = new ArrayList<>();
|
||||
List<Subscription> accepted = new ArrayList<>();
|
||||
|
||||
@@ -559,38 +632,56 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
int granted = qos == MqttQoS.AT_LEAST_ONCE ? 1 : 0;
|
||||
Subscription subscription = new Subscription(topicFilter, granted);
|
||||
clientSubscriptions.put(topicFilter, subscription);
|
||||
accepted.add(subscription);
|
||||
accepted.add(new Subscription(topicFilter, granted));
|
||||
grantedQos.add(granted == 1 ? MqttQoS.AT_LEAST_ONCE : MqttQoS.AT_MOST_ONCE);
|
||||
}
|
||||
synchronized (sessionLock) {
|
||||
// An ended session no longer owns its client id's subscriptions; a newer connection may.
|
||||
if (session.ended().get()) {
|
||||
return;
|
||||
}
|
||||
Map<String, Subscription> clientSubscriptions = subscriptionsByClient.computeIfAbsent(
|
||||
session.clientId(), ignored -> new ConcurrentHashMap<>());
|
||||
for (Subscription subscription : accepted) {
|
||||
clientSubscriptions.put(subscription.topicFilter(), subscription);
|
||||
}
|
||||
}
|
||||
|
||||
session.endpoint().subscribeAcknowledge(message.messageId(), grantedQos);
|
||||
deliverRetained(session, accepted);
|
||||
}
|
||||
|
||||
private void handleUnsubscribe(ClientSession session, MqttUnsubscribeMessage message) {
|
||||
Map<String, Subscription> clientSubscriptions = subscriptionsByClient.get(session.clientId());
|
||||
if (clientSubscriptions != null) {
|
||||
for (String topic : message.topics()) {
|
||||
clientSubscriptions.remove(topic);
|
||||
received(session);
|
||||
synchronized (sessionLock) {
|
||||
if (session.ended().get()) {
|
||||
return;
|
||||
}
|
||||
if (clientSubscriptions.isEmpty()) {
|
||||
subscriptionsByClient.remove(session.clientId(), clientSubscriptions);
|
||||
Map<String, Subscription> clientSubscriptions = subscriptionsByClient.get(session.clientId());
|
||||
if (clientSubscriptions != null) {
|
||||
for (String topic : message.topics()) {
|
||||
clientSubscriptions.remove(topic);
|
||||
}
|
||||
if (clientSubscriptions.isEmpty()) {
|
||||
subscriptionsByClient.remove(session.clientId(), clientSubscriptions);
|
||||
}
|
||||
}
|
||||
}
|
||||
session.endpoint().unsubscribeAcknowledge(message.messageId());
|
||||
}
|
||||
|
||||
private void handlePublish(ClientSession session, MqttPublishMessage message) {
|
||||
received(session);
|
||||
if (message.payload().length() > MAX_PAYLOAD_SIZE) {
|
||||
LOG.debugv("IoT MQTT client {0} disconnected: {1} byte payload on {2} exceeds the AWS limit",
|
||||
session.clientId(), Integer.toString(message.payload().length()), message.topicName());
|
||||
endSession(session, CLIENT_ERROR);
|
||||
session.endpoint().close();
|
||||
return;
|
||||
}
|
||||
byte[] payload = message.payload().getBytes();
|
||||
if (message.qosLevel() == MqttQoS.EXACTLY_ONCE) {
|
||||
endSession(session, CLIENT_ERROR);
|
||||
session.endpoint().close();
|
||||
return;
|
||||
}
|
||||
@@ -619,7 +710,10 @@ public class IotMqttBrokerService implements Resettable {
|
||||
* its rules.
|
||||
*/
|
||||
void evaluateRulesOnWorker(String topic, Runnable rules) {
|
||||
long admitted = ruleState.get();
|
||||
evaluateRulesOnWorker(topic, rules, ruleState.get());
|
||||
}
|
||||
|
||||
void evaluateRulesOnWorker(String topic, Runnable rules, long admitted) {
|
||||
if ((admitted & (RULES_RESETTING | RULES_STOPPED)) != 0) {
|
||||
return;
|
||||
}
|
||||
@@ -688,13 +782,66 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
private void removeSession(ClientSession session) {
|
||||
sessionsByClient.remove(session.clientId(), session);
|
||||
if (session.cleanSession()) {
|
||||
subscriptionsByClient.remove(session.clientId());
|
||||
/**
|
||||
* Ends the session once: the first reason reported wins, and only that one publishes the
|
||||
* disconnected event and gets true. The versionNumber counts up only while the session is still
|
||||
* the client id's current one, so a session replaced by a newer connection leaves it alone.
|
||||
*/
|
||||
private boolean endSession(ClientSession session, String reason) {
|
||||
synchronized (sessionLock) {
|
||||
if (!session.ended().compareAndSet(false, true)) {
|
||||
return false;
|
||||
}
|
||||
if (sessionsByClient.remove(session.clientId(), session)) {
|
||||
presenceVersions.computeIfPresent(session.clientId(), (id, version) -> version + 1);
|
||||
}
|
||||
if (session.cleanSession()) {
|
||||
subscriptionsByClient.remove(session.clientId());
|
||||
}
|
||||
publishPresence(session, "disconnected", reason);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes the AWS lifecycle event of a session the way a client publish goes: recorded, run
|
||||
* through every region's topic rules on the rule worker, then fanned out to subscribers. A
|
||||
* client id holding {@code #} or {@code +} gets none, as on AWS: its topic would not be valid.
|
||||
*/
|
||||
private void publishPresence(ClientSession session, String eventType, String disconnectReason) {
|
||||
if (session.clientId().contains("#") || session.clientId().contains("+")) {
|
||||
return;
|
||||
}
|
||||
String topic = PRESENCE_TOPIC_PREFIX + eventType + "/" + session.clientId();
|
||||
ObjectNode event = JsonNodeFactory.instance.objectNode();
|
||||
event.put("clientId", session.clientId());
|
||||
event.put("timestamp", System.currentTimeMillis());
|
||||
event.put("eventType", eventType);
|
||||
event.put("sessionIdentifier", session.sessionIdentifier());
|
||||
if (session.principalIdentifier() != null) {
|
||||
event.put("principalIdentifier", session.principalIdentifier());
|
||||
}
|
||||
event.put("versionNumber", session.versionNumber());
|
||||
if (disconnectReason == null) {
|
||||
if (session.sourceIp() != null) {
|
||||
event.put("ipAddress", session.sourceIp());
|
||||
}
|
||||
} else {
|
||||
event.put("clientInitiatedDisconnect", CLIENT_INITIATED_DISCONNECT.equals(disconnectReason));
|
||||
event.put("disconnectReason", disconnectReason);
|
||||
}
|
||||
byte[] payload = event.toString().getBytes(StandardCharsets.UTF_8);
|
||||
// Vert.x runs an endpoint callback holding that endpoint's monitor and the fan-out takes each subscriber's,
|
||||
// so the event is published once the callback returns; events scheduled from one thread keep their order.
|
||||
// Its rules are admitted under the rule state at the time of the event.
|
||||
long admitted = ruleState.get();
|
||||
vertx.runOnContext(ignored -> {
|
||||
iotService.get().publish(topic, payload, false, 0, null, session.clientId(),
|
||||
rules -> evaluateRulesOnWorker(topic, rules, admitted));
|
||||
fanOut(topic, payload, false);
|
||||
});
|
||||
}
|
||||
|
||||
private boolean isValidTopicFilter(String topicFilter) {
|
||||
if (topicFilter == null || topicFilter.isBlank()) {
|
||||
return false;
|
||||
@@ -717,6 +864,10 @@ public class IotMqttBrokerService implements Resettable {
|
||||
return true;
|
||||
}
|
||||
String[] filterLevels = topicFilter.split("/", -1);
|
||||
// Measured on AWS IoT: a wildcard first level matches the $aws/things shadow topics but not the lifecycle topics.
|
||||
if (topic.startsWith(PRESENCE_TOPIC_PREFIX) && ("#".equals(filterLevels[0]) || "+".equals(filterLevels[0]))) {
|
||||
return false;
|
||||
}
|
||||
String[] topicLevels = topic.split("/", -1);
|
||||
for (int i = 0; i < filterLevels.length; i++) {
|
||||
String filterLevel = filterLevels[i];
|
||||
@@ -733,12 +884,29 @@ public class IotMqttBrokerService implements Resettable {
|
||||
return filterLevels.length == topicLevels.length;
|
||||
}
|
||||
|
||||
private void received(ClientSession session) {
|
||||
session.lastPacketNanos().set(nanoTime.getAsLong());
|
||||
}
|
||||
|
||||
private boolean keepAliveExpired(ClientSession session) {
|
||||
int keepAlive = session.endpoint().keepAliveTimeSeconds();
|
||||
// Vert.x closes a client silent for ceil(1.5 * keep-alive) seconds since Netty's last read.
|
||||
// Every packet is stamped here before Netty stamps it, the CONNECT microseconds after.
|
||||
long timeout = TimeUnit.SECONDS.toNanos((long) Math.ceil(keepAlive * 1.5)) - KEEP_ALIVE_SLACK_NANOS;
|
||||
return keepAlive > 0 && nanoTime.getAsLong() - session.lastPacketNanos().get() >= timeout;
|
||||
}
|
||||
|
||||
private record ClientSession(
|
||||
String clientId,
|
||||
MqttEndpoint endpoint,
|
||||
String sourceIp,
|
||||
int sourcePort,
|
||||
boolean cleanSession) {
|
||||
boolean cleanSession,
|
||||
String sessionIdentifier,
|
||||
String principalIdentifier,
|
||||
long versionNumber,
|
||||
AtomicBoolean ended,
|
||||
AtomicLong lastPacketNanos) {
|
||||
}
|
||||
|
||||
private record Subscription(String topicFilter, int qos) {
|
||||
|
||||
@@ -120,7 +120,8 @@ public class IotMqttWebSocketBridge {
|
||||
|
||||
/**
|
||||
* The upgrade as AWS hands it to a custom authorizer; the server name only over TLS, from SNI or
|
||||
* else the Host header. The client's address rides along for the broker's policy evaluation.
|
||||
* else the Host header. The client's address and port ride along for the broker's policy
|
||||
* evaluation and GetConnection.
|
||||
*/
|
||||
private static IotCustomAuthorizer.WebSocketUpgrade upgradeOf(ServerWebSocket ws) {
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
@@ -135,7 +136,7 @@ public class IotMqttWebSocketBridge {
|
||||
}
|
||||
SocketAddress client = ws.remoteAddress();
|
||||
return new IotCustomAuthorizer.WebSocketUpgrade(headers, ws.query() == null ? "" : ws.query(), serverName,
|
||||
client == null ? null : client.host());
|
||||
client == null ? null : client.host(), client == null ? -1 : client.port());
|
||||
}
|
||||
|
||||
static final class BridgeSession {
|
||||
|
||||
@@ -2035,6 +2035,11 @@ public class IotService {
|
||||
return false;
|
||||
}
|
||||
String[] filterParts = filter.split("/", -1);
|
||||
// Measured on AWS IoT: a wildcard first level matches the $aws/things shadow topics but not the lifecycle topics.
|
||||
if (topic.startsWith(IotMqttBrokerService.PRESENCE_TOPIC_PREFIX)
|
||||
&& ("#".equals(filterParts[0]) || "+".equals(filterParts[0]))) {
|
||||
return false;
|
||||
}
|
||||
String[] topicParts = topic.split("/", -1);
|
||||
int i = 0;
|
||||
for (; i < filterParts.length; i++) {
|
||||
|
||||
Reference in new issue
Block a user