broker/ProtocolProcessor: code formatter used
This commit is contained in:
@@ -13,6 +13,7 @@
|
||||
*
|
||||
* You may elect to redistribute this code under either of these licenses.
|
||||
*/
|
||||
|
||||
package io.moquette.spi.impl;
|
||||
|
||||
import io.moquette.interception.InterceptHandler;
|
||||
@@ -34,7 +35,6 @@ import io.netty.handler.codec.mqtt.*;
|
||||
import io.netty.handler.timeout.IdleStateHandler;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
@@ -43,7 +43,6 @@ import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import static io.moquette.spi.impl.InternalRepublisher.createPublishForQos;
|
||||
import static io.moquette.spi.impl.Utils.messageId;
|
||||
import static io.moquette.spi.impl.Utils.readBytesAndRewind;
|
||||
@@ -52,8 +51,8 @@ import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
|
||||
import static io.netty.handler.codec.mqtt.MqttQoS.*;
|
||||
|
||||
/**
|
||||
* Class responsible to handle the logic of MQTT protocol it's the director of
|
||||
* the protocol execution.
|
||||
* Class responsible to handle the logic of MQTT protocol it's the director of the protocol
|
||||
* execution.
|
||||
*
|
||||
* Used by the front facing class ProtocolProcessorBootstrapper.
|
||||
*
|
||||
@@ -62,6 +61,7 @@ import static io.netty.handler.codec.mqtt.MqttQoS.*;
|
||||
public class ProtocolProcessor {
|
||||
|
||||
static final class WillMessage {
|
||||
|
||||
private final String topic;
|
||||
private final ByteBuffer payload;
|
||||
private final boolean retained;
|
||||
@@ -89,7 +89,6 @@ public class ProtocolProcessor {
|
||||
public MqttQoS getQos() {
|
||||
return qos;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private enum SubscriptionState {
|
||||
@@ -97,6 +96,7 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private class RunningSubscription {
|
||||
|
||||
final String clientID;
|
||||
final long packetId;
|
||||
|
||||
@@ -107,12 +107,15 @@ public class ProtocolProcessor {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
RunningSubscription that = (RunningSubscription) o;
|
||||
|
||||
return packetId == that.packetId && (clientID != null ? clientID.equals(that.clientID) : that.clientID == null);
|
||||
return packetId == that.packetId
|
||||
&& (clientID != null ? clientID.equals(that.clientID) : that.clientID == null);
|
||||
|
||||
}
|
||||
|
||||
@@ -148,49 +151,77 @@ public class ProtocolProcessor {
|
||||
// maps clientID to Will testament, if specified on CONNECT
|
||||
private ConcurrentMap<String, WillMessage> m_willStore = new ConcurrentHashMap<>();
|
||||
|
||||
ProtocolProcessor() {}
|
||||
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService,
|
||||
ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator,
|
||||
boolean allowAnonymous, IAuthorizator authorizator, BrokerInterceptor interceptor) {
|
||||
init(subscriptions,storageService,sessionsStore,authenticator,allowAnonymous, false, authorizator,interceptor,null);
|
||||
ProtocolProcessor() {
|
||||
}
|
||||
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService,
|
||||
ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator,
|
||||
boolean allowAnonymous,
|
||||
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor) {
|
||||
init(subscriptions,storageService,sessionsStore,authenticator,allowAnonymous, allowZeroByteClientId, authorizator,interceptor,null);
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator,
|
||||
BrokerInterceptor interceptor) {
|
||||
init(
|
||||
subscriptions,
|
||||
storageService,
|
||||
sessionsStore,
|
||||
authenticator,
|
||||
allowAnonymous,
|
||||
false,
|
||||
authorizator,
|
||||
interceptor,
|
||||
null);
|
||||
}
|
||||
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService,
|
||||
ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator,
|
||||
boolean allowAnonymous,
|
||||
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
|
||||
init(new ConnectionDescriptorStore(sessionsStore), subscriptions, storageService, sessionsStore, authenticator,
|
||||
allowAnonymous, allowZeroByteClientId, authorizator, interceptor, serverPort);
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
|
||||
IAuthorizator authorizator, BrokerInterceptor interceptor) {
|
||||
init(
|
||||
subscriptions,
|
||||
storageService,
|
||||
sessionsStore,
|
||||
authenticator,
|
||||
allowAnonymous,
|
||||
allowZeroByteClientId,
|
||||
authorizator,
|
||||
interceptor,
|
||||
null);
|
||||
}
|
||||
|
||||
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
|
||||
IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
|
||||
init(
|
||||
new ConnectionDescriptorStore(sessionsStore),
|
||||
subscriptions,
|
||||
storageService,
|
||||
sessionsStore,
|
||||
authenticator,
|
||||
allowAnonymous,
|
||||
allowZeroByteClientId,
|
||||
authorizator,
|
||||
interceptor,
|
||||
serverPort);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param subscriptions the subscription store where are stored all the existing
|
||||
* clients subscriptions.
|
||||
* @param storageService the persistent store to use for save/load of messages
|
||||
* for QoS1 and QoS2 handling.
|
||||
* @param sessionsStore the clients sessions store, used to persist subscriptions.
|
||||
* @param authenticator the authenticator used in connect messages.
|
||||
* @param allowAnonymous true connection to clients without credentials.
|
||||
* @param allowZeroByteClientId true to allow clients connect without a clientid
|
||||
* @param authorizator used to apply ACL policies to publishes and subscriptions.
|
||||
* @param interceptor to notify events to an intercept handler
|
||||
* @param subscriptions
|
||||
* the subscription store where are stored all the existing clients subscriptions.
|
||||
* @param storageService
|
||||
* the persistent store to use for save/load of messages for QoS1 and QoS2 handling.
|
||||
* @param sessionsStore
|
||||
* the clients sessions store, used to persist subscriptions.
|
||||
* @param authenticator
|
||||
* the authenticator used in connect messages.
|
||||
* @param allowAnonymous
|
||||
* true connection to clients without credentials.
|
||||
* @param allowZeroByteClientId
|
||||
* true to allow clients connect without a clientid
|
||||
* @param authorizator
|
||||
* used to apply ACL policies to publishes and subscriptions.
|
||||
* @param interceptor
|
||||
* to notify events to an intercept handler
|
||||
*/
|
||||
void init(ConnectionDescriptorStore connectionDescriptors, SubscriptionsStore subscriptions, IMessagesStore storageService,
|
||||
ISessionsStore sessionsStore,
|
||||
IAuthenticator authenticator,
|
||||
boolean allowAnonymous,
|
||||
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
|
||||
void init(ConnectionDescriptorStore connectionDescriptors, SubscriptionsStore subscriptions,
|
||||
IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator,
|
||||
boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator,
|
||||
BrokerInterceptor interceptor, String serverPort) {
|
||||
LOG.info("Initializing MQTT protocol processor...");
|
||||
this.connectionDescriptors = connectionDescriptors;
|
||||
this.subscriptionInCourse = new ConcurrentHashMap<>();
|
||||
@@ -209,15 +240,36 @@ public class ProtocolProcessor {
|
||||
|
||||
LOG.info("Initializing messages publisher...");
|
||||
final PersistentQueueMessageSender messageSender = new PersistentQueueMessageSender(this.connectionDescriptors);
|
||||
this.messagesPublisher = new MessagesPublisher(connectionDescriptors, sessionsStore, m_messagesStore, messageSender);
|
||||
this.messagesPublisher = new MessagesPublisher(
|
||||
connectionDescriptors,
|
||||
sessionsStore,
|
||||
m_messagesStore,
|
||||
messageSender);
|
||||
|
||||
LOG.info("Initializing QoS publish handlers...");
|
||||
this.qos0PublishHandler = new Qos0PublishHandler(m_authorizator, subscriptions, m_messagesStore,
|
||||
m_interceptor, this.messagesPublisher);
|
||||
this.qos1PublishHandler = new Qos1PublishHandler(m_authorizator, subscriptions, m_messagesStore,
|
||||
m_interceptor, this.connectionDescriptors, m_server_port, this.messagesPublisher);
|
||||
this.qos2PublishHandler = new Qos2PublishHandler(m_authorizator, subscriptions, m_messagesStore,
|
||||
m_interceptor, this.connectionDescriptors, m_sessionsStore, m_server_port, this.messagesPublisher);
|
||||
this.qos0PublishHandler = new Qos0PublishHandler(
|
||||
m_authorizator,
|
||||
subscriptions,
|
||||
m_messagesStore,
|
||||
m_interceptor,
|
||||
this.messagesPublisher);
|
||||
this.qos1PublishHandler = new Qos1PublishHandler(
|
||||
m_authorizator,
|
||||
subscriptions,
|
||||
m_messagesStore,
|
||||
m_interceptor,
|
||||
this.connectionDescriptors,
|
||||
m_server_port,
|
||||
this.messagesPublisher);
|
||||
this.qos2PublishHandler = new Qos2PublishHandler(
|
||||
m_authorizator,
|
||||
subscriptions,
|
||||
m_messagesStore,
|
||||
m_interceptor,
|
||||
this.connectionDescriptors,
|
||||
m_sessionsStore,
|
||||
m_server_port,
|
||||
this.messagesPublisher);
|
||||
|
||||
LOG.info("Initializing internal republisher...");
|
||||
this.internalRepublisher = new InternalRepublisher(messageSender);
|
||||
@@ -228,8 +280,8 @@ public class ProtocolProcessor {
|
||||
String clientId = payload.clientIdentifier();
|
||||
LOG.info("Processing CONNECT message. CId = {}, username = {}", clientId, payload.userName());
|
||||
|
||||
if (msg.variableHeader().version() != MqttVersion.MQTT_3_1.protocolLevel() &&
|
||||
msg.variableHeader().version() != MqttVersion.MQTT_3_1_1.protocolLevel()) {
|
||||
if (msg.variableHeader().version() != MqttVersion.MQTT_3_1.protocolLevel()
|
||||
&& msg.variableHeader().version() != MqttVersion.MQTT_3_1_1.protocolLevel()) {
|
||||
MqttConnAckMessage badProto = connAck(CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION);
|
||||
|
||||
LOG.error("The MQTT protocol version is not valid. CId = {}", clientId);
|
||||
@@ -250,8 +302,10 @@ public class ProtocolProcessor {
|
||||
|
||||
// Generating client id.
|
||||
clientId = UUID.randomUUID().toString().replace("-", "");
|
||||
LOG.info("The client has connected with a server generated identifier. CId = {}, username = {}",
|
||||
clientId, payload.userName());
|
||||
LOG.info(
|
||||
"The client has connected with a server generated identifier. CId = {}, username = {}",
|
||||
clientId,
|
||||
payload.userName());
|
||||
}
|
||||
|
||||
if (!login(channel, msg, clientId)) {
|
||||
@@ -259,11 +313,13 @@ public class ProtocolProcessor {
|
||||
return;
|
||||
}
|
||||
|
||||
ConnectionDescriptor descriptor = new ConnectionDescriptor(clientId, channel, msg.variableHeader().isCleanSession());
|
||||
ConnectionDescriptor descriptor = new ConnectionDescriptor(
|
||||
clientId,
|
||||
channel,
|
||||
msg.variableHeader().isCleanSession());
|
||||
ConnectionDescriptor existing = this.connectionDescriptors.addConnection(descriptor);
|
||||
if (existing != null) {
|
||||
LOG.info("The client ID is being used in an existing connection. It will be closed. CId = {}",
|
||||
clientId);
|
||||
LOG.info("The client ID is being used in an existing connection. It will be closed. CId = {}", clientId);
|
||||
existing.abort();
|
||||
return;
|
||||
}
|
||||
@@ -289,7 +345,8 @@ public class ProtocolProcessor {
|
||||
channel.close();
|
||||
return;
|
||||
}
|
||||
final boolean success = descriptor.assignState(ConnectionState.MESSAGES_REPUBLISHED, ConnectionState.ESTABLISHED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.MESSAGES_REPUBLISHED, ConnectionState.ESTABLISHED);
|
||||
if (!success) {
|
||||
channel.close();
|
||||
}
|
||||
@@ -306,7 +363,12 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private MqttConnAckMessage connAck(MqttConnectReturnCode returnCode, boolean sessionPresent) {
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0);
|
||||
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
|
||||
MqttMessageType.CONNACK,
|
||||
false,
|
||||
MqttQoS.AT_MOST_ONCE,
|
||||
false,
|
||||
0);
|
||||
MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(returnCode, sessionPresent);
|
||||
return new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader);
|
||||
}
|
||||
@@ -318,20 +380,25 @@ public class ProtocolProcessor {
|
||||
if (msg.variableHeader().hasPassword()) {
|
||||
pwd = msg.payload().password().getBytes();
|
||||
} else if (!this.allowAnonymous) {
|
||||
LOG.error("The client didn't supply any password and MQTT anonymous mode is disabled. CId = {}.",
|
||||
LOG.error(
|
||||
"The client didn't supply any password and MQTT anonymous mode is disabled. CId = {}.",
|
||||
clientId);
|
||||
failedCredentials(channel);
|
||||
return false;
|
||||
}
|
||||
if (!m_authenticator.checkValid(clientId, msg.payload().userName(), pwd)) {
|
||||
LOG.error("The authenticator has rejected the MQTT credentials. CId = {}, username = {}, password = {}.",
|
||||
clientId, msg.payload().userName(), pwd);
|
||||
LOG.error(
|
||||
"The authenticator has rejected the MQTT credentials. CId = {}, username = {}, password = {}.",
|
||||
clientId,
|
||||
msg.payload().userName(),
|
||||
pwd);
|
||||
failedCredentials(channel);
|
||||
return false;
|
||||
}
|
||||
NettyUtils.userName(channel, msg.payload().userName());
|
||||
} else if (!this.allowAnonymous) {
|
||||
LOG.error("The client didn't supply any credentials and MQTT anonymous mode is disabled. CId = {}.",
|
||||
LOG.error(
|
||||
"The client didn't supply any credentials and MQTT anonymous mode is disabled. CId = {}.",
|
||||
clientId);
|
||||
failedCredentials(channel);
|
||||
return false;
|
||||
@@ -376,20 +443,33 @@ public class ProtocolProcessor {
|
||||
int idleTime = Math.round(keepAlive * 1.5f);
|
||||
setIdleTime(channel.pipeline(), idleTime);
|
||||
|
||||
LOG.info("The connection has been configured. CId = {}, keepAlive = {}, cleanSession = {}, idleTime = {}.",
|
||||
clientId, keepAlive, msg.variableHeader().isCleanSession(), idleTime);
|
||||
LOG.info(
|
||||
"The connection has been configured. CId = {}, keepAlive = {}, cleanSession = {}, idleTime = {}.",
|
||||
clientId,
|
||||
keepAlive,
|
||||
msg.variableHeader().isCleanSession(),
|
||||
idleTime);
|
||||
}
|
||||
|
||||
private void storeWillMessage(MqttConnectMessage msg, final String clientId) {
|
||||
// Handle will flag
|
||||
if (msg.variableHeader().isWillFlag()) {
|
||||
MqttQoS willQos = MqttQoS.valueOf(msg.variableHeader().willQos());
|
||||
LOG.info("Configuring MQTT last will and testament. CId = {}, willQos = {}, willTopic = {}, willRetain = {}.",
|
||||
clientId, willQos, msg.payload().willTopic(), msg.variableHeader().isWillRetain());
|
||||
LOG.info(
|
||||
"Configuring MQTT last will and testament. "
|
||||
+ "CId = {}, willQos = {}, willTopic = {}, willRetain = {}.",
|
||||
clientId,
|
||||
willQos,
|
||||
msg.payload().willTopic(),
|
||||
msg.variableHeader().isWillRetain());
|
||||
byte[] willPayload = msg.payload().willMessage().getBytes();
|
||||
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(willPayload.length).put(willPayload).flip();
|
||||
// save the will testament in the clientID store
|
||||
WillMessage will = new WillMessage(msg.payload().willTopic(), bb, msg.variableHeader().isWillRetain(), willQos);
|
||||
WillMessage will = new WillMessage(
|
||||
msg.payload().willTopic(),
|
||||
bb,
|
||||
msg.variableHeader().isWillRetain(),
|
||||
willQos);
|
||||
m_willStore.put(clientId, will);
|
||||
LOG.info("MQTT last will and testament has been configured. CId = {}.", clientId);
|
||||
}
|
||||
@@ -415,7 +495,8 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private boolean republish(ConnectionDescriptor descriptor, MqttConnectMessage msg, ClientSession clientSession) {
|
||||
final boolean success = descriptor.assignState(ConnectionState.SESSION_CREATED, ConnectionState.MESSAGES_REPUBLISHED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.SESSION_CREATED, ConnectionState.MESSAGES_REPUBLISHED);
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
@@ -443,7 +524,7 @@ public class ProtocolProcessor {
|
||||
|
||||
/**
|
||||
* Republish QoS1 and QoS2 messages stored into the session for the clientID.
|
||||
* */
|
||||
*/
|
||||
private void republishStoredInSession(ClientSession clientSession) {
|
||||
LOG.info("Republishing stored publish events. CId = {}.", clientSession.clientID);
|
||||
BlockingQueue<StoredMessage> publishedEvents = clientSession.queue();
|
||||
@@ -474,15 +555,20 @@ public class ProtocolProcessor {
|
||||
ByteBuf payload = msg.payload();
|
||||
byte[] payloadContent = readBytesAndRewind(payload);
|
||||
|
||||
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(payloadContent,
|
||||
msg.fixedHeader().qosLevel(), msg.variableHeader().topicName());
|
||||
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(
|
||||
payloadContent,
|
||||
msg.fixedHeader().qosLevel(),
|
||||
msg.variableHeader().topicName());
|
||||
stored.setRetained(msg.fixedHeader().isRetain());
|
||||
stored.setMessageID(msg.variableHeader().messageId());
|
||||
return stored;
|
||||
}
|
||||
|
||||
private static IMessagesStore.StoredMessage asStoredMessage(WillMessage will) {
|
||||
IMessagesStore.StoredMessage pub = new IMessagesStore.StoredMessage(will.getPayload().array(), will.getQos(), will.getTopic());
|
||||
IMessagesStore.StoredMessage pub = new IMessagesStore.StoredMessage(
|
||||
will.getPayload().array(),
|
||||
will.getQos(),
|
||||
will.getTopic());
|
||||
pub.setRetained(will.isRetained());
|
||||
return pub;
|
||||
}
|
||||
@@ -490,8 +576,12 @@ public class ProtocolProcessor {
|
||||
public void processPublish(Channel channel, MqttPublishMessage msg) {
|
||||
final MqttQoS qos = msg.fixedHeader().qosLevel();
|
||||
final String clientId = NettyUtils.clientID(channel);
|
||||
LOG.info("Processing PUBLISH message. CId = {}, topic = {}, messageId = {}, qos = {}.",
|
||||
clientId, msg.variableHeader().topicName(), msg.variableHeader().messageId(), qos);
|
||||
LOG.info(
|
||||
"Processing PUBLISH message. CId = {}, topic = {}, messageId = {}, qos = {}.",
|
||||
clientId,
|
||||
msg.variableHeader().topicName(),
|
||||
msg.variableHeader().messageId(),
|
||||
qos);
|
||||
switch (qos) {
|
||||
case AT_MOST_ONCE:
|
||||
this.qos0PublishHandler.receivedPublishQos0(channel, msg);
|
||||
@@ -508,16 +598,17 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Intended usage is only for embedded versions of the broker, where the hosting application want to use the
|
||||
* broker to send a publish message.
|
||||
* Inspired by {@link #processPublish} but with some changes to avoid security check, and the handshake phases
|
||||
* for Qos1 and Qos2.
|
||||
* It also doesn't notifyTopicPublished because using internally the owner should already know where
|
||||
* it's publishing.
|
||||
* Intended usage is only for embedded versions of the broker, where the hosting application
|
||||
* want to use the broker to send a publish message. Inspired by {@link #processPublish} but
|
||||
* with some changes to avoid security check, and the handshake phases for Qos1 and Qos2. It
|
||||
* also doesn't notifyTopicPublished because using internally the owner should already know
|
||||
* where it's publishing.
|
||||
*
|
||||
* @param msg the message to publish.
|
||||
* @param clientId the clientID
|
||||
* */
|
||||
* @param msg
|
||||
* the message to publish.
|
||||
* @param clientId
|
||||
* the clientID
|
||||
*/
|
||||
public void internalPublish(MqttPublishMessage msg, final String clientId) {
|
||||
final MqttQoS qos = msg.fixedHeader().qosLevel();
|
||||
final String topic = msg.variableHeader().topicName();
|
||||
@@ -581,11 +672,14 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored message and publish
|
||||
* to all interested subscribers.
|
||||
* @param channel the channel of the incoming message.
|
||||
* @param msg the decoded pubrel message.
|
||||
* */
|
||||
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored
|
||||
* message and publish to all interested subscribers.
|
||||
*
|
||||
* @param channel
|
||||
* the channel of the incoming message.
|
||||
* @param msg
|
||||
* the decoded pubrel message.
|
||||
*/
|
||||
public void processPubRel(Channel channel, MqttMessage msg) {
|
||||
this.qos2PublishHandler.processPubRel(channel, msg);
|
||||
}
|
||||
@@ -629,8 +723,7 @@ public class ProtocolProcessor {
|
||||
|
||||
if (existingDescriptor.doesNotUseChannel(channel)) {
|
||||
// another client saved it's descriptor, exit
|
||||
LOG.warn("Another client is using the connection descriptor. Closing connection. CId = {}.",
|
||||
clientID);
|
||||
LOG.warn("Another client is using the connection descriptor. Closing connection. CId = {}.", clientID);
|
||||
existingDescriptor.abort();
|
||||
return;
|
||||
}
|
||||
@@ -669,7 +762,8 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private boolean removeSubscriptions(ConnectionDescriptor descriptor, String clientID) {
|
||||
final boolean success = descriptor.assignState(ConnectionState.ESTABLISHED, ConnectionState.SUBSCRIPTIONS_REMOVED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.ESTABLISHED, ConnectionState.SUBSCRIPTIONS_REMOVED);
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
@@ -683,7 +777,8 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private boolean dropStoredMessages(ConnectionDescriptor descriptor, String clientID) {
|
||||
final boolean success = descriptor.assignState(ConnectionState.SUBSCRIPTIONS_REMOVED, ConnectionState.MESSAGES_DROPPED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.SUBSCRIPTIONS_REMOVED, ConnectionState.MESSAGES_DROPPED);
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
@@ -697,7 +792,8 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private boolean cleanWillMessageAndNotifyInterceptor(ConnectionDescriptor descriptor, String clientID) {
|
||||
final boolean success = descriptor.assignState(ConnectionState.MESSAGES_DROPPED, ConnectionState.INTERCEPTORS_NOTIFIED);
|
||||
final boolean success = descriptor
|
||||
.assignState(ConnectionState.MESSAGES_DROPPED, ConnectionState.INTERCEPTORS_NOTIFIED);
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
@@ -726,10 +822,13 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the clientID from topic subscription, if not previously subscribed,
|
||||
* doesn't reply any error.
|
||||
* @param channel the channel of the incoming message.
|
||||
* @param msg the decoded unsubscribe message.
|
||||
* Remove the clientID from topic subscription, if not previously subscribed, doesn't reply any
|
||||
* error.
|
||||
*
|
||||
* @param channel
|
||||
* the channel of the incoming message.
|
||||
* @param msg
|
||||
* the decoded unsubscribe message.
|
||||
*/
|
||||
public void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg) {
|
||||
List<String> topics = msg.payload().topics();
|
||||
@@ -743,8 +842,11 @@ public class ProtocolProcessor {
|
||||
if (!validTopic) {
|
||||
// close the connection, not valid topicFilter is a protocol violation
|
||||
channel.close();
|
||||
LOG.error("The topic filter is not valid. CId = {}, topics = {}, badTopicFilter = {}.",
|
||||
clientID, topics, topic);
|
||||
LOG.error(
|
||||
"The topic filter is not valid. CId = {}, topics = {}, badTopicFilter = {}.",
|
||||
clientID,
|
||||
topics,
|
||||
topic);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -770,18 +872,25 @@ public class ProtocolProcessor {
|
||||
LOG.info("Processing SUBSCRIBE message. CId = {}, messageId = {}.", clientID, messageID);
|
||||
|
||||
RunningSubscription executionKey = new RunningSubscription(clientID, messageID);
|
||||
SubscriptionState currentStatus = this.subscriptionInCourse.putIfAbsent(executionKey, SubscriptionState.VERIFIED);
|
||||
SubscriptionState currentStatus = this.subscriptionInCourse
|
||||
.putIfAbsent(executionKey, SubscriptionState.VERIFIED);
|
||||
if (currentStatus != null) {
|
||||
LOG.warn("The client sent another SUBSCRIBE message while this one was being processed. " +
|
||||
"CId = {}, messageId = {}.", clientID, messageID);
|
||||
LOG.warn(
|
||||
"The client sent another SUBSCRIBE message while this one was being processed. "
|
||||
+ "CId = {}, messageId = {}.",
|
||||
clientID,
|
||||
messageID);
|
||||
return;
|
||||
}
|
||||
String username = NettyUtils.userName(channel);
|
||||
List<MqttTopicSubscription> ackTopics = doVerify(clientID, username, msg);
|
||||
MqttSubAckMessage ackMessage = doAckMessageFromValidateFilters(ackTopics, messageID);
|
||||
if (!this.subscriptionInCourse.replace(executionKey, SubscriptionState.VERIFIED, SubscriptionState.STORED)) {
|
||||
LOG.warn("The client sent another SUBSCRIBE message while the topic filters were being verified. " +
|
||||
"CId = {}, messageId = {}.", clientID, messageID);
|
||||
LOG.warn(
|
||||
"The client sent another SUBSCRIBE message while the topic filters were being verified. "
|
||||
+ "CId = {}, messageId = {}.",
|
||||
clientID,
|
||||
messageID);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -826,11 +935,14 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param clientID the clientID
|
||||
* @param username the username
|
||||
* @param msg the subscribe message to verify
|
||||
* @param clientID
|
||||
* the clientID
|
||||
* @param username
|
||||
* the username
|
||||
* @param msg
|
||||
* the subscribe message to verify
|
||||
* @return the list of verified topics for the given subscribe message.
|
||||
* */
|
||||
*/
|
||||
private List<MqttTopicSubscription> doVerify(String clientID, String username, MqttSubscribeMessage msg) {
|
||||
ClientSession clientSession = m_sessionsStore.sessionForClient(clientID);
|
||||
List<MqttTopicSubscription> ackTopics = new ArrayList<>();
|
||||
@@ -839,18 +951,31 @@ public class ProtocolProcessor {
|
||||
for (MqttTopicSubscription req : msg.payload().topicSubscriptions()) {
|
||||
if (!m_authorizator.canRead(req.topicName(), username, clientSession.clientID)) {
|
||||
// send SUBACK with 0x80, the user hasn't credentials to read the topic
|
||||
LOG.error("The client does not have read permissions on the topic. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID, username, messageId, req.topicName());
|
||||
LOG.error(
|
||||
"The client does not have read permissions on the topic. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID,
|
||||
username,
|
||||
messageId,
|
||||
req.topicName());
|
||||
ackTopics.add(new MqttTopicSubscription(req.topicName(), FAILURE));
|
||||
} else {
|
||||
MqttQoS qos;
|
||||
if (SubscriptionsStore.validate(req.topicName())) {
|
||||
LOG.info("The client will be subscribed to the topic. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID, username, messageId, req.topicName());
|
||||
LOG.info(
|
||||
"The client will be subscribed to the topic. "
|
||||
+ "CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID,
|
||||
username,
|
||||
messageId,
|
||||
req.topicName());
|
||||
qos = req.qualityOfService();
|
||||
} else {
|
||||
LOG.error("The topic filter is not valid. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID, username, messageId, req.topicName());
|
||||
LOG.error(
|
||||
"The topic filter is not valid. CId = {}, username = {}, messageId = {}, topic = {}.",
|
||||
clientID,
|
||||
username,
|
||||
messageId,
|
||||
req.topicName());
|
||||
qos = FAILURE;
|
||||
}
|
||||
ackTopics.add(new MqttTopicSubscription(req.topicName(), qos));
|
||||
@@ -861,7 +986,7 @@ public class ProtocolProcessor {
|
||||
|
||||
/**
|
||||
* Create the SUBACK response from a list of topicFilters
|
||||
* */
|
||||
*/
|
||||
private MqttSubAckMessage doAckMessageFromValidateFilters(List<MqttTopicSubscription> topicFilters, int messageId) {
|
||||
List<Integer> grantedQoSLevels = new ArrayList<>();
|
||||
for (MqttTopicSubscription req : topicFilters) {
|
||||
@@ -874,12 +999,15 @@ public class ProtocolProcessor {
|
||||
}
|
||||
|
||||
private void publishRetainedMessagesInSession(final Subscription newSubscription, String username) {
|
||||
LOG.info("Retrieving retained messages. CId = {}, topics = {}.", newSubscription.getClientId(),
|
||||
LOG.info(
|
||||
"Retrieving retained messages. CId = {}, topics = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter());
|
||||
|
||||
// scans retained messages to be published to the new subscription
|
||||
// TODO this is ugly, it does a linear scan on potential big dataset
|
||||
Collection<IMessagesStore.StoredMessage> messages = m_messagesStore.searchMatching(new IMatchingCondition() {
|
||||
|
||||
@Override
|
||||
public boolean match(String key) {
|
||||
return SubscriptionsStore.matchTopics(key, newSubscription.getTopicFilter());
|
||||
@@ -887,8 +1015,11 @@ public class ProtocolProcessor {
|
||||
});
|
||||
|
||||
if (!messages.isEmpty()) {
|
||||
LOG.info("Publishing retained messages. CId = {}, topics = {}, messagesNo = {}.",
|
||||
newSubscription.getClientId(), newSubscription.getTopicFilter(), messages.size());
|
||||
LOG.info(
|
||||
"Publishing retained messages. CId = {}, topics = {}, messagesNo = {}.",
|
||||
newSubscription.getClientId(),
|
||||
newSubscription.getTopicFilter(),
|
||||
messages.size());
|
||||
}
|
||||
ClientSession targetSession = m_sessionsStore.sessionForClient(newSubscription.getClientId());
|
||||
this.internalRepublisher.publishRetained(targetSession, messages);
|
||||
@@ -908,7 +1039,12 @@ public class ProtocolProcessor {
|
||||
} else {
|
||||
// recreate a publish from stored publish in queue
|
||||
boolean retained = m_messagesStore.getMessageByGuid(msg.getGuid()) != null;
|
||||
MqttPublishMessage pubMsg = createPublishForQos(msg.getTopic(), msg.getQos(), msg.getMessage(), retained, 0);
|
||||
MqttPublishMessage pubMsg = createPublishForQos(
|
||||
msg.getTopic(),
|
||||
msg.getQos(),
|
||||
msg.getMessage(),
|
||||
retained,
|
||||
0);
|
||||
channel.write(pubMsg);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user