Merge pull request #265 from AndreasMager/fromating-broker

Minor Checkstyle adjustement & Fromating broker folder
This commit is contained in:
Andrea Selva
2017-02-09 13:34:45 +01:00
committed by GitHub
126 changed files with 3224 additions and 2583 deletions
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette; package io.moquette;
import java.io.File; import java.io.File;
@@ -21,6 +22,7 @@ import java.io.File;
* Created by andrea on 08/12/15. * Created by andrea on 08/12/15.
*/ */
public class BrokerConstants { public class BrokerConstants {
public static final String INTERCEPT_HANDLER_PROPERTY_NAME = "intercept.handler"; public static final String INTERCEPT_HANDLER_PROPERTY_NAME = "intercept.handler";
public static final String BROKER_INTERCEPTOR_THREAD_POOL_SIZE = "intercept.thread_pool.size"; public static final String BROKER_INTERCEPTOR_THREAD_POOL_SIZE = "intercept.thread_pool.size";
public static final String PERSISTENT_STORE_PROPERTY_NAME = "persistent_store"; public static final String PERSISTENT_STORE_PROPERTY_NAME = "persistent_store";
@@ -29,7 +31,8 @@ public class BrokerConstants {
public static final String PORT_PROPERTY_NAME = "port"; public static final String PORT_PROPERTY_NAME = "port";
public static final String HOST_PROPERTY_NAME = "host"; public static final String HOST_PROPERTY_NAME = "host";
public static final String DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME = "moquette_store.mapdb"; public static final String DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME = "moquette_store.mapdb";
public static final String DEFAULT_PERSISTENT_PATH = System.getProperty("user.dir") + File.separator + DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME; public static final String DEFAULT_PERSISTENT_PATH = System.getProperty("user.dir") + File.separator
+ DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME;
public static final String WEB_SOCKET_PORT_PROPERTY_NAME = "websocket_port"; public static final String WEB_SOCKET_PORT_PROPERTY_NAME = "websocket_port";
public static final String WSS_PORT_PROPERTY_NAME = "secure_websocket_port"; public static final String WSS_PORT_PROPERTY_NAME = "secure_websocket_port";
public static final String SSL_PORT_PROPERTY_NAME = "ssl_port"; public static final String SSL_PORT_PROPERTY_NAME = "ssl_port";
@@ -1,15 +1,16 @@
package io.moquette.connections; package io.moquette.connections;
import java.util.Collection; import java.util.Collection;
/** /**
* This interface will be used by an external codebase to retrieve and close * This interface will be used by an external codebase to retrieve and close physical connections.
* physical connections.
* *
* @author lbarrios * @author lbarrios
* *
*/ */
public interface IConnectionsManager { public interface IConnectionsManager {
/** /**
* Returns the number of physical connections * Returns the number of physical connections
* *
@@ -26,8 +27,7 @@ public interface IConnectionsManager {
public boolean isConnected(String clientID); public boolean isConnected(String clientID);
/** /**
* Returns the identifiers of the MQTT clients that are connected to the * Returns the identifiers of the MQTT clients that are connected to the broker.
* broker.
* *
* @return * @return
*/ */
@@ -45,6 +45,7 @@ public interface IConnectionsManager {
/** /**
* Returns the state of the session of a given client. * Returns the state of the session of a given client.
*
* @param clientID * @param clientID
* @return * @return
*/ */
@@ -52,6 +53,7 @@ public interface IConnectionsManager {
/** /**
* Returns the state of all the sessions * Returns the state of all the sessions
*
* @return * @return
*/ */
public Collection<MqttSession> getSessions(); public Collection<MqttSession> getSessions();
@@ -1,3 +1,4 @@
package io.moquette.connections; package io.moquette.connections;
/** /**
@@ -7,6 +8,7 @@ package io.moquette.connections;
* *
*/ */
public class MqttConnectionMetrics { public class MqttConnectionMetrics {
private long readKb; private long readKb;
private long writtenKb; private long writtenKb;
private long readMessages; private long readMessages;
@@ -1,11 +1,11 @@
package io.moquette.connections; package io.moquette.connections;
import java.util.Collection; import java.util.Collection;
/** /**
* A class that represents the overall connection status of a MQTT session. Its * A class that represents the overall connection status of a MQTT session. Its instances will be
* instances will be used by an external codebase when the broker is configured * used by an external codebase when the broker is configured in embedded mode.
* in embedded mode.
* *
* @author lbarrios * @author lbarrios
* *
@@ -1,3 +1,4 @@
package io.moquette.connections; package io.moquette.connections;
/** /**
@@ -7,6 +8,7 @@ package io.moquette.connections;
* *
*/ */
public class MqttSubscription { public class MqttSubscription {
private final String requestedQos; private final String requestedQos;
private final String clientId; private final String clientId;
private final String topicFilter; private final String topicFilter;
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.interception; package io.moquette.interception;
import io.moquette.interception.messages.InterceptAcknowledgedMessage; import io.moquette.interception.messages.InterceptAcknowledgedMessage;
@@ -36,23 +37,30 @@ public abstract class AbstractInterceptHandler implements InterceptHandler {
} }
@Override @Override
public void onConnect(InterceptConnectMessage msg) {} public void onConnect(InterceptConnectMessage msg) {
}
@Override @Override
public void onDisconnect(InterceptDisconnectMessage msg) {} public void onDisconnect(InterceptDisconnectMessage msg) {
}
@Override @Override
public void onConnectionLost(InterceptConnectionLostMessage msg) {} public void onConnectionLost(InterceptConnectionLostMessage msg) {
}
@Override @Override
public void onPublish(InterceptPublishMessage msg) {} public void onPublish(InterceptPublishMessage msg) {
}
@Override @Override
public void onSubscribe(InterceptSubscribeMessage msg) {} public void onSubscribe(InterceptSubscribeMessage msg) {
}
@Override @Override
public void onUnsubscribe(InterceptUnsubscribeMessage msg) {} public void onUnsubscribe(InterceptUnsubscribeMessage msg) {
}
@Override @Override
public void onMessageAcknowledged(InterceptAcknowledgedMessage msg) {} public void onMessageAcknowledged(InterceptAcknowledgedMessage msg) {
}
} }
@@ -1,3 +1,4 @@
package io.moquette.interception; package io.moquette.interception;
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstance;
@@ -7,7 +8,6 @@ import io.moquette.server.Server;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.moquette.spi.impl.Utils.readBytesAndRewind; import static io.moquette.spi.impl.Utils.readBytesAndRewind;
/** /**
@@ -1,9 +1,8 @@
package io.moquette.interception; package io.moquette.interception;
import io.moquette.interception.messages.InterceptPublishMessage; import io.moquette.interception.messages.InterceptPublishMessage;
import java.io.Serializable; import java.io.Serializable;
import static io.moquette.spi.impl.Utils.readBytesAndRewind; import static io.moquette.spi.impl.Utils.readBytesAndRewind;
/** /**
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.interception; package io.moquette.interception;
import io.moquette.interception.messages.*; import io.moquette.interception.messages.*;
@@ -24,28 +25,29 @@ import io.netty.handler.codec.mqtt.MqttMessage;
* <p> * <p>
* The events can act only as observers. * The events can act only as observers.
* <p> * <p>
* Almost every method receives a subclass of {@link MqttMessage}, except * Almost every method receives a subclass of {@link MqttMessage}, except <code>onDisconnect</code>
* <code>onDisconnect</code> that receives the client id string and * that receives the client id string and <code>onSubscribe</code> and <code>onUnsubscribe</code>
* <code>onSubscribe</code> and <code>onUnsubscribe</code> that receive a * that receive a {@link Subscription} object.
* {@link Subscription} object.
* *
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public interface InterceptHandler { public interface InterceptHandler {
public static final Class<?> ALL_MESSAGE_TYPES[] = { InterceptConnectMessage.class, Class<?>[] ALL_MESSAGE_TYPES = {InterceptConnectMessage.class, InterceptDisconnectMessage.class,
InterceptDisconnectMessage.class, InterceptConnectionLostMessage.class, InterceptPublishMessage.class, InterceptConnectionLostMessage.class, InterceptPublishMessage.class, InterceptSubscribeMessage.class,
InterceptSubscribeMessage.class, InterceptUnsubscribeMessage.class, InterceptAcknowledgedMessage.class }; InterceptUnsubscribeMessage.class, InterceptAcknowledgedMessage.class};
/** /**
* Returns the identifier of this intercept handler. * Returns the identifier of this intercept handler.
*
* @return * @return
*/ */
String getID(); String getID();
/** /**
* Returns the InterceptMessage subtypes that this handler can process. If the result is null or equal to ALL_MESSAGE_TYPES, * Returns the InterceptMessage subtypes that this handler can process. If the result is null or
* all the message types will be processed. * equal to ALL_MESSAGE_TYPES, all the message types will be processed.
*
* @return * @return
*/ */
Class<?>[] getInterceptedMessageTypes(); Class<?>[] getInterceptedMessageTypes();
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.interception; package io.moquette.interception;
import io.moquette.interception.messages.InterceptAcknowledgedMessage; import io.moquette.interception.messages.InterceptAcknowledgedMessage;
@@ -23,12 +24,10 @@ import io.netty.handler.codec.mqtt.MqttPublishMessage;
/** /**
* This interface is to be used internally by the broker components. * This interface is to be used internally by the broker components.
* <p> * <p>
* An interface is used instead of a class to allow more flexibility in changing * An interface is used instead of a class to allow more flexibility in changing an implementation.
* an implementation.
* <p> * <p>
* Interceptor implementations forward notifications to a <code>InterceptHandler</code>, * Interceptor implementations forward notifications to a <code>InterceptHandler</code>, that is
* that is normally a field. So, the implementations should act as a proxy to a custom * normally a field. So, the implementations should act as a proxy to a custom intercept handler.
* intercept handler.
* *
* @see InterceptHandler * @see InterceptHandler
* @author Wagner Macedo * @author Wagner Macedo
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.interception.messages; package io.moquette.interception.messages;
import io.netty.handler.codec.mqtt.MqttMessage; import io.netty.handler.codec.mqtt.MqttMessage;
@@ -22,6 +23,7 @@ import io.netty.handler.codec.mqtt.MqttQoS;
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public abstract class InterceptAbstractMessage implements InterceptMessage { public abstract class InterceptAbstractMessage implements InterceptMessage {
private final MqttMessage msg; private final MqttMessage msg;
InterceptAbstractMessage(MqttMessage msg) { InterceptAbstractMessage(MqttMessage msg) {
@@ -1,8 +1,10 @@
package io.moquette.interception.messages; package io.moquette.interception.messages;
import static io.moquette.spi.IMessagesStore.StoredMessage; import static io.moquette.spi.IMessagesStore.StoredMessage;
public class InterceptAcknowledgedMessage implements InterceptMessage { public class InterceptAcknowledgedMessage implements InterceptMessage {
final private StoredMessage msg; final private StoredMessage msg;
private final String username; private final String username;
private final String topic; private final String topic;
@@ -1,3 +1,4 @@
package io.moquette.interception.messages; package io.moquette.interception.messages;
import io.netty.handler.codec.mqtt.MqttConnectMessage; import io.netty.handler.codec.mqtt.MqttConnectMessage;
@@ -6,6 +7,7 @@ import io.netty.handler.codec.mqtt.MqttConnectMessage;
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public class InterceptConnectMessage extends InterceptAbstractMessage { public class InterceptConnectMessage extends InterceptAbstractMessage {
private final MqttConnectMessage msg; private final MqttConnectMessage msg;
public InterceptConnectMessage(MqttConnectMessage msg) { public InterceptConnectMessage(MqttConnectMessage msg) {
@@ -1,9 +1,11 @@
package io.moquette.interception.messages; package io.moquette.interception.messages;
/** /**
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public class InterceptConnectionLostMessage implements InterceptMessage { public class InterceptConnectionLostMessage implements InterceptMessage {
private final String clientID; private final String clientID;
private final String username; private final String username;
@@ -1,9 +1,11 @@
package io.moquette.interception.messages; package io.moquette.interception.messages;
/** /**
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public class InterceptDisconnectMessage implements InterceptMessage { public class InterceptDisconnectMessage implements InterceptMessage {
private final String clientID; private final String clientID;
private final String username; private final String username;
@@ -1,7 +1,9 @@
package io.moquette.interception.messages; package io.moquette.interception.messages;
/** /**
* An interface that sets the root of the interceptor messages type hierarchy. * An interface that sets the root of the interceptor messages type hierarchy.
*
* @author lbarrios * @author lbarrios
* *
*/ */
@@ -1,3 +1,4 @@
package io.moquette.interception.messages; package io.moquette.interception.messages;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
@@ -7,6 +8,7 @@ import io.netty.handler.codec.mqtt.MqttPublishMessage;
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public class InterceptPublishMessage extends InterceptAbstractMessage { public class InterceptPublishMessage extends InterceptAbstractMessage {
private final MqttPublishMessage msg; private final MqttPublishMessage msg;
private final String clientID; private final String clientID;
private final String username; private final String username;
@@ -1,3 +1,4 @@
package io.moquette.interception.messages; package io.moquette.interception.messages;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
@@ -7,6 +8,7 @@ import io.netty.handler.codec.mqtt.MqttQoS;
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public class InterceptSubscribeMessage implements InterceptMessage { public class InterceptSubscribeMessage implements InterceptMessage {
private final Subscription subscription; private final Subscription subscription;
private final String username; private final String username;
@@ -1,9 +1,11 @@
package io.moquette.interception.messages; package io.moquette.interception.messages;
/** /**
* @author Wagner Macedo * @author Wagner Macedo
*/ */
public class InterceptUnsubscribeMessage implements InterceptMessage { public class InterceptUnsubscribeMessage implements InterceptMessage {
private final String topicFilter; private final String topicFilter;
private final String clientID; private final String clientID;
private final String username; private final String username;
@@ -1,11 +1,12 @@
package io.moquette.logging; package io.moquette.logging;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import io.moquette.interception.InterceptHandler; import io.moquette.interception.InterceptHandler;
public class LoggingUtils { public class LoggingUtils {
public static <T extends InterceptHandler> Collection<String> getInterceptorIds(Collection<T> handlers) { public static <T extends InterceptHandler> Collection<String> getInterceptorIds(Collection<T> handlers) {
Collection<String> result = new ArrayList<>(handlers.size()); Collection<String> result = new ArrayList<>(handlers.size());
for (T handler : handlers) { for (T handler : handlers) {
@@ -13,15 +13,14 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import io.moquette.server.netty.AutoFlushHandler; import io.moquette.server.netty.AutoFlushHandler;
import io.moquette.server.netty.NettyUtils; import io.moquette.server.netty.NettyUtils;
import io.moquette.server.netty.metrics.BytesMetrics; import io.moquette.server.netty.metrics.BytesMetrics;
@@ -30,10 +29,9 @@ import io.moquette.server.netty.metrics.MessageMetrics;
import io.moquette.server.netty.metrics.MessageMetricsHandler; import io.moquette.server.netty.metrics.MessageMetricsHandler;
import io.netty.channel.Channel; import io.netty.channel.Channel;
/** /**
* Value object to maintain the information of single connection, like ClientID, Channel, * Value object to maintain the information of single connection, like ClientID, Channel, and clean
* and clean session flag. * session flag.
* *
* *
* @author andrea * @author andrea
@@ -44,9 +42,15 @@ public class ConnectionDescriptor {
public enum ConnectionState { public enum ConnectionState {
// Connection states // Connection states
DISCONNECTED, SENDACK, SESSION_CREATED, MESSAGES_REPUBLISHED, ESTABLISHED, DISCONNECTED,
SENDACK,
SESSION_CREATED,
MESSAGES_REPUBLISHED,
ESTABLISHED,
// Disconnection states // Disconnection states
SUBSCRIPTIONS_REMOVED, MESSAGES_DROPPED, INTERCEPTORS_NOTIFIED; SUBSCRIPTIONS_REMOVED,
MESSAGES_DROPPED,
INTERCEPTORS_NOTIFIED;
} }
public final String clientID; public final String clientID;
@@ -66,10 +70,14 @@ public class ConnectionDescriptor {
public void setupAutoFlusher(int flushIntervalMs) { public void setupAutoFlusher(int flushIntervalMs) {
try { try {
this.channel.pipeline().addAfter("idleEventHandler", "autoFlusher", new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS)); this.channel.pipeline().addAfter(
"idleEventHandler",
"autoFlusher",
new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS));
} catch (NoSuchElementException nseex) { } catch (NoSuchElementException nseex) {
// the idleEventHandler is not present on the pipeline // the idleEventHandler is not present on the pipeline
this.channel.pipeline().addFirst("autoFlusher", new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS)); this.channel.pipeline()
.addFirst("autoFlusher", new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS));
} }
} }
@@ -102,35 +110,41 @@ public class ConnectionDescriptor {
} }
public boolean assignState(ConnectionState expected, ConnectionState newState) { public boolean assignState(ConnectionState expected, ConnectionState newState) {
LOG.debug("Updating state of connection descriptor. MqttClientId = {}, expectedState = {}, newState = {}.", LOG.debug(
clientID, expected, newState); "Updating state of connection descriptor. MqttClientId = {}, expectedState = {}, newState = {}.",
clientID,
expected,
newState);
boolean retval = channelState.compareAndSet(expected, newState); boolean retval = channelState.compareAndSet(expected, newState);
if (!retval) { if (!retval) {
LOG.error( LOG.error(
"Unable to update state of connection descriptor. MqttclientId = {}, expectedState = {}, newState = {}.", "Unable to update state of connection descriptor."
clientID, expected, newState); + " MqttclientId = {}, expectedState = {}, newState = {}.",
clientID,
expected,
newState);
} }
return retval; return retval;
} }
@Override @Override
public String toString() { public String toString() {
return "ConnectionDescriptor{" + "clientID=" + clientID + return "ConnectionDescriptor{" + "clientID=" + clientID + ", cleanSession=" + cleanSession + ", state="
", cleanSession=" + cleanSession + + channelState.get() + '}';
", state=" + channelState.get() +
'}';
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
ConnectionDescriptor that = (ConnectionDescriptor) o; ConnectionDescriptor that = (ConnectionDescriptor) o;
if (clientID != null ? !clientID.equals(that.clientID) : that.clientID != null) return false; if (clientID != null ? !clientID.equals(that.clientID) : that.clientID != null)
return false;
return !(channel != null ? !channel.equals(that.channel) : that.channel != null); return !(channel != null ? !channel.equals(that.channel) : that.channel != null);
} }
public BytesMetrics getBytesMetrics() { public BytesMetrics getBytesMetrics() {
@@ -1,3 +1,4 @@
package io.moquette.server; package io.moquette.server;
import io.moquette.connections.IConnectionsManager; import io.moquette.connections.IConnectionsManager;
@@ -13,7 +14,6 @@ import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType; import io.netty.handler.codec.mqtt.MqttMessageType;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -43,15 +43,20 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID); ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
if (descriptor == null) { if (descriptor == null) {
if (messageID != null) { if (messageID != null) {
LOG.error("Client has just disconnected. The {} message could not be sent. CId=<{}>, messageId={}", LOG.error(
messageType, clientID, messageID); "Client has just disconnected. The {} message could not be sent. CId=<{}>, messageId={}",
messageType,
clientID,
messageID);
} else { } else {
LOG.error("Client has just disconnected. The {} could not be sent. CId=<{}>", messageType, clientID); LOG.error(
"Client has just disconnected. The {} could not be sent. CId=<{}>",
messageType,
clientID);
} }
/* /*
* If the client has just disconnected, its connection * If the client has just disconnected, its connection descriptor will be null. We
* descriptor will be null. We don't have to make the broker * don't have to make the broker crash: we'll just discard the PUBACK message.
* crash: we'll just discard the PUBACK message.
*/ */
return false; return false;
} }
@@ -99,8 +104,10 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID); ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
if (descriptor == null) { if (descriptor == null) {
LOG.error( LOG.error(
"The connection descriptor doesn't exist. The MQTT connection cannot be closed. CId=<{}>, closeImmediately = {}.", "The connection descriptor doesn't exist. "
clientID, closeImmediately); + "The MQTT connection cannot be closed. CId=<{}>, closeImmediately = {}.",
clientID,
closeImmediately);
return false; return false;
} }
if (closeImmediately) { if (closeImmediately) {
@@ -125,7 +132,7 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
@Override @Override
public Collection<MqttSession> getSessions() { public Collection<MqttSession> getSessions() {
LOG.info("Retrieving status of all sessions."); LOG.info("Retrieving status of all sessions.");
Collection<MqttSession> result = new ArrayList<MqttSession>(); Collection<MqttSession> result = new ArrayList<>();
for (ClientSession session : sessionsStore.getAllSessions()) { for (ClientSession session : sessionsStore.getAllSessions()) {
result.add(buildMqttSession(session)); result.add(buildMqttSession(session));
} }
@@ -136,8 +143,12 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
MqttSession result = new MqttSession(); MqttSession result = new MqttSession();
Collection<MqttSubscription> mqttSubscriptions = new ArrayList<>(); Collection<MqttSubscription> mqttSubscriptions = new ArrayList<>();
for (Subscription subscription : session.getSubscriptions()) { for (Subscription subscription : session.getSubscriptions()) {
mqttSubscriptions.add(new MqttSubscription(subscription.getRequestedQos().toString(), mqttSubscriptions.add(
subscription.getClientId(), subscription.getTopicFilter(), subscription.isActive())); new MqttSubscription(
subscription.getRequestedQos().toString(),
subscription.getClientId(),
subscription.getTopicFilter(),
subscription.isActive()));
} }
result.setActiveSubscriptions(mqttSubscriptions); result.setActiveSubscriptions(mqttSubscriptions);
result.setCleanSession(session.isCleanSession()); result.setCleanSession(session.isCleanSession());
@@ -146,8 +157,12 @@ public class ConnectionDescriptorStore implements IConnectionsManager {
result.setConnectionEstablished(true); result.setConnectionEstablished(true);
BytesMetrics bytesMetrics = descriptor.getBytesMetrics(); BytesMetrics bytesMetrics = descriptor.getBytesMetrics();
MessageMetrics messageMetrics = descriptor.getMessageMetrics(); MessageMetrics messageMetrics = descriptor.getMessageMetrics();
result.setConnectionMetrics(new MqttConnectionMetrics(bytesMetrics.readBytes(), bytesMetrics.wroteBytes(), result.setConnectionMetrics(
messageMetrics.messagesRead(), messageMetrics.messagesWrote())); new MqttConnectionMetrics(
bytesMetrics.readBytes(),
bytesMetrics.wroteBytes(),
messageMetrics.messagesRead(),
messageMetrics.messagesWrote()));
} else { } else {
result.setConnectionEstablished(false); result.setConnectionEstablished(false);
} }
@@ -13,12 +13,14 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
/** /**
* Server constants keeper * Server constants keeper
*/ */
public class Constants { public class Constants {
public static final String ATTR_CLIENTID = "ClientID"; public static final String ATTR_CLIENTID = "ClientID";
public static final String CLEAN_SESSION = "cleanSession"; public static final String CLEAN_SESSION = "cleanSession";
public static final String KEEP_ALIVE = "keepAlive"; public static final String KEEP_ALIVE = "keepAlive";
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -20,20 +21,18 @@ import io.moquette.server.config.IConfig;
import io.moquette.spi.security.ISslContextCreator; import io.moquette.spi.security.ISslContextCreator;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
import java.io.*; import java.io.*;
import java.net.URL; import java.net.URL;
import java.security.*; import java.security.*;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
/** /**
* Moquette server implementation to load SSL certificate from local filesystem path * Moquette server implementation to load SSL certificate from local filesystem path configured in
* configured in config file. * config file.
* *
* Created by andrea on 13/12/15. * Created by andrea on 13/12/15.
*/ */
@@ -90,9 +89,11 @@ class DefaultMoquetteSslContextCreator implements ISslContextCreator {
TrustManager[] trustManagers = null; TrustManager[] trustManagers = null;
if (needsClientAuth) { if (needsClientAuth) {
LOG.warn( LOG.warn(
"Client authentication is enabled. The keystore will be used as a truststore. KeystorePath = {}.", "Client authentication is enabled. "
+ "The keystore will be used as a truststore. KeystorePath = {}.",
jksPath); jksPath);
// use keystore as truststore, as server needs to trust certificates signed by the server certificates // use keystore as truststore, as server needs to trust certificates signed by the
// server certificates
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks); tmf.init(ks);
trustManagers = tmf.getTrustManagers(); trustManagers = tmf.getTrustManagers();
@@ -105,7 +106,10 @@ class DefaultMoquetteSslContextCreator implements ISslContextCreator {
return serverContext; return serverContext;
} catch (NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException } catch (NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException
| KeyManagementException | IOException ex) { | KeyManagementException | IOException ex) {
LOG.error("Unable to initialize SSL context. Cause = {}, errorMessage = {}.", ex.getCause(), ex.getMessage()); LOG.error(
"Unable to initialize SSL context. Cause = {}, errorMessage = {}.",
ex.getCause(),
ex.getMessage());
return null; return null;
} }
} }
@@ -1,3 +1,4 @@
package io.moquette.server; package io.moquette.server;
import com.hazelcast.core.Message; import com.hazelcast.core.Message;
@@ -13,6 +14,7 @@ import org.slf4j.LoggerFactory;
* Created by mackristof on 28/05/2016. * Created by mackristof on 28/05/2016.
*/ */
public class HazelcastListener implements MessageListener<HazelcastMsg> { public class HazelcastListener implements MessageListener<HazelcastMsg> {
private static final Logger LOG = LoggerFactory.getLogger(HazelcastListener.class); private static final Logger LOG = LoggerFactory.getLogger(HazelcastListener.class);
private final Server server; private final Server server;
@@ -26,8 +28,11 @@ public class HazelcastListener implements MessageListener<HazelcastMsg> {
try { try {
if (!msg.getPublishingMember().equals(server.getHazelcastInstance().getCluster().getLocalMember())) { if (!msg.getPublishingMember().equals(server.getHazelcastInstance().getCluster().getLocalMember())) {
HazelcastMsg hzMsg = msg.getMessageObject(); HazelcastMsg hzMsg = msg.getMessageObject();
LOG.info("{} received from hazelcast for topic {} message: {}", hzMsg.getClientId(), LOG.info(
hzMsg.getTopic(), hzMsg.getPayload()); "{} received from hazelcast for topic {} message: {}",
hzMsg.getClientId(),
hzMsg.getTopic(),
hzMsg.getPayload());
// TODO pass forward this information in somehow publishMessage.setLocal(false); // TODO pass forward this information in somehow publishMessage.setLocal(false);
MqttQoS qos = MqttQoS.valueOf(hzMsg.getQos()); MqttQoS qos = MqttQoS.valueOf(hzMsg.getQos());
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import com.hazelcast.config.ClasspathXmlConfig; import com.hazelcast.config.ClasspathXmlConfig;
@@ -38,18 +39,17 @@ import io.moquette.spi.security.ISslContextCreator;
import io.netty.handler.codec.mqtt.MqttPublishMessage; import io.netty.handler.codec.mqtt.MqttPublishMessage;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import static io.moquette.logging.LoggingUtils.getInterceptorIds; import static io.moquette.logging.LoggingUtils.getInterceptorIds;
/** /**
* Launch a configured version of the server. * Launch a configured version of the server.
*
* @author andrea * @author andrea
*/ */
public class Server { public class Server {
@@ -74,6 +74,7 @@ public class Server {
System.out.println("Server started, version 0.10-SNAPSHOT"); System.out.println("Server started, version 0.10-SNAPSHOT");
// Bind a shutdown hook // Bind a shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() { Runtime.getRuntime().addShutdownHook(new Thread() {
@Override @Override
public void run() { public void run() {
server.stopServer(); server.stopServer();
@@ -82,9 +83,10 @@ public class Server {
} }
/** /**
* Starts Moquette bringing the configuration from the file * Starts Moquette bringing the configuration from the file located at m_config/moquette.conf
* located at m_config/moquette.conf *
* @throws IOException in case of any IO error. * @throws IOException
* in case of any IO error.
*/ */
public void startServer() throws IOException { public void startServer() throws IOException {
File defaultConfigurationFile = defaultConfigFile(); File defaultConfigurationFile = defaultConfigFile();
@@ -101,8 +103,11 @@ public class Server {
/** /**
* Starts Moquette bringing the configuration from the given file * Starts Moquette bringing the configuration from the given file
* @param configFile text file that contains the configuration. *
* @throws IOException in case of any IO Error. * @param configFile
* text file that contains the configuration.
* @throws IOException
* in case of any IO Error.
*/ */
public void startServer(File configFile) throws IOException { public void startServer(File configFile) throws IOException {
LOG.info("Starting Moquette server. Configuration file path = {}.", configFile.getAbsolutePath()); LOG.info("Starting Moquette server. Configuration file path = {}.", configFile.getAbsolutePath());
@@ -120,8 +125,10 @@ public class Server {
* <li>password_file</li> * <li>password_file</li>
* </ul> * </ul>
* *
* @param configProps the properties map to use as configuration. * @param configProps
* @throws IOException in case of any IO Error. * the properties map to use as configuration.
* @throws IOException
* in case of any IO Error.
*/ */
public void startServer(Properties configProps) throws IOException { public void startServer(Properties configProps) throws IOException {
LOG.info("Starting Moquette server using properties object..."); LOG.info("Starting Moquette server using properties object...");
@@ -131,8 +138,11 @@ public class Server {
/** /**
* Starts Moquette bringing the configuration files from the given Config implementation. * Starts Moquette bringing the configuration files from the given Config implementation.
* @param config the configuration to use to start the broker. *
* @throws IOException in case of any IO Error. * @param config
* the configuration to use to start the broker.
* @throws IOException
* in case of any IO Error.
*/ */
public void startServer(IConfig config) throws IOException { public void startServer(IConfig config) throws IOException {
LOG.info("Starting Moquette server using IConfig instance..."); LOG.info("Starting Moquette server using IConfig instance...");
@@ -140,20 +150,23 @@ public class Server {
} }
/** /**
* Starts Moquette with config provided by an implementation of IConfig class and with the * Starts Moquette with config provided by an implementation of IConfig class and with the set
* set of InterceptHandler. * of InterceptHandler.
* @param config the configuration to use to start the broker. *
* @param handlers the handlers to install in the broker. * @param config
* @throws IOException in case of any IO Error. * the configuration to use to start the broker.
* */ * @param handlers
* the handlers to install in the broker.
* @throws IOException
* in case of any IO Error.
*/
public void startServer(IConfig config, List<? extends InterceptHandler> handlers) throws IOException { public void startServer(IConfig config, List<? extends InterceptHandler> handlers) throws IOException {
LOG.info("Starting moquette server using IConfig instance and intercept handlers..."); LOG.info("Starting moquette server using IConfig instance and intercept handlers...");
startServer(config, handlers, null, null, null); startServer(config, handlers, null, null, null);
} }
public void startServer(IConfig config, List<? extends InterceptHandler> handlers, public void startServer(IConfig config, List<? extends InterceptHandler> handlers, ISslContextCreator sslCtxCreator,
ISslContextCreator sslCtxCreator, IAuthenticator authenticator, IAuthenticator authenticator, IAuthorizator authorizator) throws IOException {
IAuthorizator authorizator) throws IOException {
if (handlers == null) { if (handlers == null) {
handlers = Collections.emptyList(); handlers = Collections.emptyList();
} }
@@ -164,10 +177,13 @@ public class Server {
config.setProperty(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME, handlerProp); config.setProperty(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME, handlerProp);
} }
configureCluster(config); configureCluster(config);
LOG.info("Configuring Using persistent store file. Path = {}.", config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME)); LOG.info(
"Configuring Using persistent store file. Path = {}.",
config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME));
m_processorBootstrapper = new ProtocolProcessorBootstrapper(); m_processorBootstrapper = new ProtocolProcessorBootstrapper();
LOG.info("Initializing MQTT protocol processor..."); LOG.info("Initializing MQTT protocol processor...");
final ProtocolProcessor processor = m_processorBootstrapper.init(config, handlers, authenticator, authorizator, this); final ProtocolProcessor processor = m_processorBootstrapper
.init(config, handlers, authenticator, authorizator, this);
if (sslCtxCreator == null) { if (sslCtxCreator == null) {
LOG.warn("Using default SSL context creator..."); LOG.warn("Using default SSL context creator...");
@@ -193,9 +209,9 @@ public class Server {
String hzConfigPath = config.getProperty(BrokerConstants.HAZELCAST_CONFIGURATION); String hzConfigPath = config.getProperty(BrokerConstants.HAZELCAST_CONFIGURATION);
if (hzConfigPath != null) { if (hzConfigPath != null) {
boolean isHzConfigOnClasspath = this.getClass().getClassLoader().getResource(hzConfigPath) != null; boolean isHzConfigOnClasspath = this.getClass().getClassLoader().getResource(hzConfigPath) != null;
Config hzconfig = isHzConfigOnClasspath ? Config hzconfig = isHzConfigOnClasspath
new ClasspathXmlConfig(hzConfigPath) : ? new ClasspathXmlConfig(hzConfigPath)
new FileSystemXmlConfig(hzConfigPath); : new FileSystemXmlConfig(hzConfigPath);
LOG.info("Starting Hazelcast instance. ConfigurationFile = {}.", hzconfig); LOG.info("Starting Hazelcast instance. ConfigurationFile = {}.", hzconfig);
hazelcastInstance = Hazelcast.newHazelcastInstance(hzconfig); hazelcastInstance = Hazelcast.newHazelcastInstance(hzconfig);
} else { } else {
@@ -217,18 +233,23 @@ public class Server {
} }
/** /**
* Use the broker to publish a message. It's intended for embedding applications. * Use the broker to publish a message. It's intended for embedding applications. It can be used
* It can be used only after the server is correctly started with startServer. * only after the server is correctly started with startServer.
* *
* @param msg the message to forward. * @param msg
* @param clientId the id of the sending server. * the message to forward.
* @throws IllegalStateException if the server is not yet started * @param clientId
* */ * the id of the sending server.
* @throws IllegalStateException
* if the server is not yet started
*/
public void internalPublish(MqttPublishMessage msg, final String clientId) { public void internalPublish(MqttPublishMessage msg, final String clientId) {
final int messageID = msg.variableHeader().messageId(); final int messageID = msg.variableHeader().messageId();
if (!m_initialized) { if (!m_initialized) {
LOG.error("The server is not started. The message cannot be published. MqttClientId = {}, messageId = {}", LOG.error(
clientId, messageID); "The server is not started. The message cannot be published. MqttClientId = {}, messageId = {}",
clientId,
messageID);
throw new IllegalStateException("Can't publish on a server is not yet started"); throw new IllegalStateException("Can't publish on a server is not yet started");
} }
LOG.debug("Publishing message. MqttClientId = {}, messageId = {}", clientId, messageID); LOG.debug("Publishing message. MqttClientId = {}, messageId = {}", clientId, messageID);
@@ -253,8 +274,8 @@ public class Server {
} }
/** /**
* SPI method used by Broker embedded applications to get list of subscribers. * SPI method used by Broker embedded applications to get list of subscribers. Returns null if
* Returns null if the broker is not started. * the broker is not started.
* *
* @return list of subscriptions. * @return list of subscriptions.
*/ */
@@ -267,14 +288,16 @@ public class Server {
/** /**
* SPI method used by Broker embedded applications to add intercept handlers. * SPI method used by Broker embedded applications to add intercept handlers.
* @param interceptHandler the handler to add. *
* */ * @param interceptHandler
* the handler to add.
*/
public void addInterceptHandler(InterceptHandler interceptHandler) { public void addInterceptHandler(InterceptHandler interceptHandler) {
if (!m_initialized) { if (!m_initialized) {
LOG.error("The server is not started. The MQTT message interceptor cannot be added. InterceptorId = {}.", LOG.error(
"The server is not started. The MQTT message interceptor cannot be added. InterceptorId = {}.",
interceptHandler.getID()); interceptHandler.getID());
throw new IllegalStateException("Can't register interceptors on a server that is not yet started"); throw new IllegalStateException("Can't register interceptors on a server that is not yet started");
} }
LOG.info("Adding MQTT message interceptor. InterceptorId = {}.", interceptHandler.getID()); LOG.info("Adding MQTT message interceptor. InterceptorId = {}.", interceptHandler.getID());
m_processor.addInterceptHandler(interceptHandler); m_processor.addInterceptHandler(interceptHandler);
@@ -282,11 +305,14 @@ public class Server {
/** /**
* SPI method used by Broker embedded applications to remove intercept handlers. * SPI method used by Broker embedded applications to remove intercept handlers.
* @param interceptHandler the handler to remove. *
* */ * @param interceptHandler
* the handler to remove.
*/
public void removeInterceptHandler(InterceptHandler interceptHandler) { public void removeInterceptHandler(InterceptHandler interceptHandler) {
if (!m_initialized) { if (!m_initialized) {
LOG.error("The server is not started. The MQTT message interceptor cannot be removed. InterceptorId = {}.", LOG.error(
"The server is not started. The MQTT message interceptor cannot be removed. InterceptorId = {}.",
interceptHandler.getID()); interceptHandler.getID());
throw new IllegalStateException("Can't deregister interceptors from a server that is not yet started"); throw new IllegalStateException("Can't deregister interceptors from a server that is not yet started");
} }
@@ -13,10 +13,10 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import java.io.IOException; import java.io.IOException;
import io.moquette.server.config.IConfig; import io.moquette.server.config.IConfig;
import io.moquette.spi.impl.ProtocolProcessor; import io.moquette.spi.impl.ProtocolProcessor;
import io.moquette.spi.security.ISslContextCreator; import io.moquette.spi.security.ISslContextCreator;
@@ -1,9 +1,9 @@
package io.moquette.server.config; package io.moquette.server.config;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -13,11 +13,11 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.config; package io.moquette.server.config;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@@ -30,8 +30,8 @@ import java.util.Properties;
/** /**
* Mosquitto configuration parser. * Mosquitto configuration parser.
* *
* A line that at the very first has # is a comment * A line that at the very first has # is a comment Each line has key value format, where the
* Each line has key value format, where the separator used it the space. * separator used it the space.
* *
* @author andrea * @author andrea
*/ */
@@ -50,14 +50,21 @@ class ConfigurationParser {
return; return;
} }
if (!file.exists()) { if (!file.exists()) {
LOG.warn(String.format("parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); LOG.warn(
String.format(
"parsing not existing file %s, so fallback on default configuration!",
file.getAbsolutePath()));
return; return;
} }
try { try {
FileReader reader = new FileReader(file); FileReader reader = new FileReader(file);
parse(reader); parse(reader);
} catch (FileNotFoundException fex) { } catch (FileNotFoundException fex) {
LOG.warn(String.format("parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); LOG.warn(
String.format(
"parsing not existing file %s, so fallback on default configuration!",
file.getAbsolutePath()),
fex);
return; return;
} }
} }
@@ -65,7 +72,8 @@ class ConfigurationParser {
/** /**
* Parse the configuration * Parse the configuration
* *
* @throws ParseException if the format is not compliant. * @throws ParseException
* if the format is not compliant.
*/ */
void parse(Reader reader) throws ParseException { void parse(Reader reader) throws ParseException {
if (reader == null) { if (reader == null) {
@@ -103,12 +111,10 @@ class ConfigurationParser {
} }
} catch (IOException ex) { } catch (IOException ex) {
throw new ParseException("Failed to read", 1); throw new ParseException("Failed to read", 1);
} } finally {
finally {
try { try {
reader.close(); reader.close();
} } catch (IOException e) {
catch (IOException e) {
// ignore // ignore
} }
} }
@@ -1,10 +1,10 @@
package io.moquette.server.config; package io.moquette.server.config;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.Reader; import java.io.Reader;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.config; package io.moquette.server.config;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -23,6 +24,7 @@ import io.moquette.BrokerConstants;
* @author andrea * @author andrea
*/ */
public abstract class IConfig { public abstract class IConfig {
public static final String DEFAULT_CONFIG = "config/moquette.conf"; public static final String DEFAULT_CONFIG = "config/moquette.conf";
public abstract void setProperty(String name, String value); public abstract void setProperty(String name, String value);
@@ -34,9 +36,11 @@ public abstract class IConfig {
void assignDefaults() { void assignDefaults() {
setProperty(BrokerConstants.PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.PORT)); setProperty(BrokerConstants.PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.PORT));
setProperty(BrokerConstants.HOST_PROPERTY_NAME, BrokerConstants.HOST); setProperty(BrokerConstants.HOST_PROPERTY_NAME, BrokerConstants.HOST);
//setProperty(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.WEBSOCKET_PORT)); // setProperty(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME,
// Integer.toString(BrokerConstants.WEBSOCKET_PORT));
setProperty(BrokerConstants.PASSWORD_FILE_PROPERTY_NAME, ""); setProperty(BrokerConstants.PASSWORD_FILE_PROPERTY_NAME, "");
//setProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME, BrokerConstants.DEFAULT_PERSISTENT_PATH); // setProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME,
// BrokerConstants.DEFAULT_PERSISTENT_PATH);
setProperty(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, Boolean.TRUE.toString()); setProperty(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, Boolean.TRUE.toString());
setProperty(BrokerConstants.AUTHENTICATOR_CLASS_NAME, ""); setProperty(BrokerConstants.AUTHENTICATOR_CLASS_NAME, "");
setProperty(BrokerConstants.AUTHORIZATOR_CLASS_NAME, ""); setProperty(BrokerConstants.AUTHORIZATOR_CLASS_NAME, "");
@@ -1,3 +1,4 @@
package io.moquette.server.config; package io.moquette.server.config;
import java.io.Reader; import java.io.Reader;
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.config; package io.moquette.server.config;
import java.util.Map; import java.util.Map;
@@ -37,9 +38,11 @@ public class MemoryConfig extends IConfig {
// private void createDefaults() { // private void createDefaults() {
// m_properties.put(BrokerConstants.PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.PORT)); // m_properties.put(BrokerConstants.PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.PORT));
// m_properties.put(BrokerConstants.HOST_PROPERTY_NAME, BrokerConstants.HOST); // m_properties.put(BrokerConstants.HOST_PROPERTY_NAME, BrokerConstants.HOST);
// m_properties.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.WEBSOCKET_PORT)); // m_properties.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME,
// Integer.toString(BrokerConstants.WEBSOCKET_PORT));
// m_properties.put(BrokerConstants.PASSWORD_FILE_PROPERTY_NAME, ""); // m_properties.put(BrokerConstants.PASSWORD_FILE_PROPERTY_NAME, "");
// m_properties.put(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME, BrokerConstants.DEFAULT_PERSISTENT_PATH); // m_properties.put(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME,
// BrokerConstants.DEFAULT_PERSISTENT_PATH);
// m_properties.put(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, true); // m_properties.put(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, true);
// m_properties.put(BrokerConstants.AUTHENTICATOR_CLASS_NAME, ""); // m_properties.put(BrokerConstants.AUTHENTICATOR_CLASS_NAME, "");
// m_properties.put(BrokerConstants.AUTHORIZATOR_CLASS_NAME, ""); // m_properties.put(BrokerConstants.AUTHORIZATOR_CLASS_NAME, "");
@@ -13,11 +13,11 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.config; package io.moquette.server.config;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.Reader; import java.io.Reader;
import java.text.ParseException; import java.text.ParseException;
import java.util.Properties; import java.util.Properties;
@@ -41,9 +41,8 @@ public class ResourceLoaderConfig extends IConfig {
this.resourceLoader = resourceLoader; this.resourceLoader = resourceLoader;
/* /*
* If we use a conditional operator, the loadResource() and the * If we use a conditional operator, the loadResource() and the loadDefaultResource()
* loadDefaultResource() methods will be always called. This makes the * methods will be always called. This makes the log traces confusing.
* log traces confusing.
*/ */
Reader configReader; Reader configReader;
@@ -54,12 +53,16 @@ public class ResourceLoaderConfig extends IConfig {
} }
if (configReader == null) { if (configReader == null) {
LOG.error("The resource loader returned no configuration reader. ResourceLoader = {}, configName = {}.", LOG.error(
resourceLoader.getName(), configName); "The resource loader returned no configuration reader. ResourceLoader = {}, configName = {}.",
resourceLoader.getName(),
configName);
throw new IllegalArgumentException("Can't locate " + resourceLoader.getName() + " \"" + configName + "\""); throw new IllegalArgumentException("Can't locate " + resourceLoader.getName() + " \"" + configName + "\"");
} }
LOG.info("Parsing configuration properties. ResourceLoader = {}, configName = {}.", resourceLoader.getName(), LOG.info(
"Parsing configuration properties. ResourceLoader = {}, configName = {}.",
resourceLoader.getName(),
configName); configName);
ConfigurationParser confParser = new ConfigurationParser(); ConfigurationParser confParser = new ConfigurationParser();
m_properties = confParser.getProperties(); m_properties = confParser.getProperties();
@@ -68,8 +71,12 @@ public class ResourceLoaderConfig extends IConfig {
confParser.parse(configReader); confParser.parse(configReader);
} catch (ParseException pex) { } catch (ParseException pex) {
LOG.warn( LOG.warn(
"Unable to parse configuration properties. Using default configuration. ResourceLoader = {}, configName = {}, cause = {}, errorMessage = {}.", "Unable to parse configuration properties. Using default configuration. "
resourceLoader.getName(), configName, pex.getCause(), pex.getMessage()); + "ResourceLoader = {}, configName = {}, cause = {}, errorMessage = {}.",
resourceLoader.getName(),
configName,
pex.getCause(),
pex.getMessage());
} }
} }
@@ -13,23 +13,21 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty; package io.moquette.server.netty;
import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.EventExecutor;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Auto-flush data on channel after a read timeout. * Auto-flush data on channel after a read timeout. It's inspired by IdleStateHandler but it's
* It's inspired by IdleStateHandler but it's specialized version, just flushing data after * specialized version, just flushing data after no read is done on the channel after a period. It's
* no read is done on the channel after a period. It's used to avoid aggressively flushing from * used to avoid aggressively flushing from the ProtocolProcessor.
* the ProtocolProcessor.
*/ */
public class AutoFlushHandler extends ChannelDuplexHandler { public class AutoFlushHandler extends ChannelDuplexHandler {
@@ -126,9 +124,7 @@ public class AutoFlushHandler extends ChannelDuplexHandler {
EventExecutor loop = ctx.executor(); EventExecutor loop = ctx.executor();
lastWriteTime = System.nanoTime(); lastWriteTime = System.nanoTime();
writerIdleTimeout = loop.schedule( writerIdleTimeout = loop.schedule(new WriterIdleTimeoutTask(ctx), writerIdleTimeNanos, TimeUnit.NANOSECONDS);
new WriterIdleTimeoutTask(ctx),
writerIdleTimeNanos, TimeUnit.NANOSECONDS);
} }
private void destroy() { private void destroy() {
@@ -143,8 +139,10 @@ public class AutoFlushHandler extends ChannelDuplexHandler {
/** /**
* Is called when the write timeout expire. * Is called when the write timeout expire.
* *
* @param ctx the channel context. * @param ctx
* @throws Exception in case of any IO error. * the channel context.
* @throws Exception
* in case of any IO error.
*/ */
protected void channelIdle(ChannelHandlerContext ctx/* , IdleStateEvent evt */) throws Exception { protected void channelIdle(ChannelHandlerContext ctx/* , IdleStateEvent evt */) throws Exception {
// ctx.fireUserEventTriggered(evt); // ctx.fireUserEventTriggered(evt);
@@ -173,16 +171,13 @@ public class AutoFlushHandler extends ChannelDuplexHandler {
long nextDelay = writerIdleTimeNanos - (System.nanoTime() - lastWriteTime); long nextDelay = writerIdleTimeNanos - (System.nanoTime() - lastWriteTime);
if (nextDelay <= 0) { if (nextDelay <= 0) {
// Writer is idle - set a new timeout and notify the callback. // Writer is idle - set a new timeout and notify the callback.
writerIdleTimeout = ctx.executor().schedule( writerIdleTimeout = ctx.executor().schedule(this, writerIdleTimeNanos, TimeUnit.NANOSECONDS);
this, writerIdleTimeNanos, TimeUnit.NANOSECONDS);
try { try {
/*IdleStateEvent event; /*
if (firstWriterIdleEvent) { * IdleStateEvent event; if (firstWriterIdleEvent) { firstWriterIdleEvent =
firstWriterIdleEvent = false; * false; event = IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT; } else { event =
event = IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT; * IdleStateEvent.WRITER_IDLE_STATE_EVENT; }
} else { */
event = IdleStateEvent.WRITER_IDLE_STATE_EVENT;
}*/
channelIdle(ctx/* , event */); channelIdle(ctx/* , event */);
} catch (Throwable t) { } catch (Throwable t) {
ctx.fireExceptionCaught(t); ctx.fireExceptionCaught(t);
@@ -13,17 +13,18 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty; package io.moquette.server.netty;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.handler.codec.mqtt.*; import io.netty.handler.codec.mqtt.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class MessageBuilder { public class MessageBuilder {
public static class PublishBuilder { public static class PublishBuilder {
private String topic = null; private String topic = null;
private boolean retained = false; private boolean retained = false;
private MqttQoS qos; private MqttQoS qos;
@@ -138,9 +139,13 @@ public class MessageBuilder {
} }
public MqttConnectMessage build() { public MqttConnectMessage build() {
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
MqttConnectVariableHeader mqttConnectVariableHeader = MqttMessageType.CONNECT,
new MqttConnectVariableHeader( false,
MqttQoS.AT_MOST_ONCE,
false,
0);
MqttConnectVariableHeader mqttConnectVariableHeader = new MqttConnectVariableHeader(
version.protocolName(), version.protocolName(),
version.protocolLevel(), version.protocolLevel(),
hasUser, hasUser,
@@ -150,7 +155,12 @@ public class MessageBuilder {
willFlag, willFlag,
cleanSession, cleanSession,
keepAliveSecs); keepAliveSecs);
MqttConnectPayload mqttConnectPayload = new MqttConnectPayload(clientId, willTopic, willMessage, username, password); MqttConnectPayload mqttConnectPayload = new MqttConnectPayload(
clientId,
willTopic,
willMessage,
username,
password);
return new MqttConnectMessage(mqttFixedHeader, mqttConnectVariableHeader, mqttConnectPayload); return new MqttConnectMessage(mqttFixedHeader, mqttConnectVariableHeader, mqttConnectPayload);
} }
} }
@@ -171,7 +181,12 @@ public class MessageBuilder {
} }
public MqttSubscribeMessage build() { public MqttSubscribeMessage build() {
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.SUBSCRIBE, false, MqttQoS.AT_LEAST_ONCE, false, 0); MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
MqttMessageType.SUBSCRIBE,
false,
MqttQoS.AT_LEAST_ONCE,
false,
0);
MqttMessageIdVariableHeader mqttVariableHeader = MqttMessageIdVariableHeader.from(messageId); MqttMessageIdVariableHeader mqttVariableHeader = MqttMessageIdVariableHeader.from(messageId);
MqttSubscribePayload mqttSubscribePayload = new MqttSubscribePayload(subscriptions); MqttSubscribePayload mqttSubscribePayload = new MqttSubscribePayload(subscriptions);
return new MqttSubscribeMessage(mqttFixedHeader, mqttVariableHeader, mqttSubscribePayload); return new MqttSubscribeMessage(mqttFixedHeader, mqttVariableHeader, mqttSubscribePayload);
@@ -194,8 +209,12 @@ public class MessageBuilder {
} }
public MqttUnsubscribeMessage build() { public MqttUnsubscribeMessage build() {
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.UNSUBSCRIBE, false, MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
MqttQoS.AT_LEAST_ONCE, false, 0); MqttMessageType.UNSUBSCRIBE,
false,
MqttQoS.AT_LEAST_ONCE,
false,
0);
MqttMessageIdVariableHeader mqttVariableHeader = MqttMessageIdVariableHeader.from(messageId); MqttMessageIdVariableHeader mqttVariableHeader = MqttMessageIdVariableHeader.from(messageId);
MqttUnsubscribePayload mqttSubscribePayload = new MqttUnsubscribePayload(topicFilters); MqttUnsubscribePayload mqttSubscribePayload = new MqttUnsubscribePayload(topicFilters);
return new MqttUnsubscribeMessage(mqttFixedHeader, mqttVariableHeader, mqttSubscribePayload); return new MqttUnsubscribeMessage(mqttFixedHeader, mqttVariableHeader, mqttSubscribePayload);
@@ -13,11 +13,11 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty; package io.moquette.server.netty;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
@@ -41,7 +41,9 @@ class MoquetteIdleTimeoutHandler extends ChannelDuplexHandler {
} }
} else { } else {
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("Firing Netty event. MqttClientId = {}, eventClass = {}.", NettyUtils.clientID(ctx.channel()), LOG.debug(
"Firing Netty event. MqttClientId = {}, eventClass = {}.",
NettyUtils.clientID(ctx.channel()),
evt.getClass().getName()); evt.getClass().getName());
} }
super.userEventTriggered(ctx, evt); super.userEventTriggered(ctx, evt);
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty; package io.moquette.server.netty;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -42,13 +43,11 @@ import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Future;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static io.moquette.BrokerConstants.*; import static io.moquette.BrokerConstants.*;
/** /**
@@ -62,10 +61,12 @@ public class NettyAcceptor implements ServerAcceptor {
static class WebSocketFrameToByteBufDecoder extends MessageToMessageDecoder<BinaryWebSocketFrame> { static class WebSocketFrameToByteBufDecoder extends MessageToMessageDecoder<BinaryWebSocketFrame> {
@Override @Override
protected void decode(ChannelHandlerContext chc, BinaryWebSocketFrame frame, List<Object> out) throws Exception { protected void decode(ChannelHandlerContext chc, BinaryWebSocketFrame frame, List<Object> out)
throws Exception {
// convert the frame to a ByteBuf // convert the frame to a ByteBuf
ByteBuf bb = frame.content(); ByteBuf bb = frame.content();
//System.out.println("WebSocketFrameToByteBufDecoder decode - " + ByteBufUtil.hexDump(bb)); // System.out.println("WebSocketFrameToByteBufDecoder decode - " +
// ByteBufUtil.hexDump(bb));
bb.retain(); bb.retain();
out.add(bb); out.add(bb);
} }
@@ -77,7 +78,8 @@ public class NettyAcceptor implements ServerAcceptor {
protected void encode(ChannelHandlerContext chc, ByteBuf bb, List<Object> out) throws Exception { protected void encode(ChannelHandlerContext chc, ByteBuf bb, List<Object> out) throws Exception {
// convert the ByteBuf to a WebSocketFrame // convert the ByteBuf to a WebSocketFrame
BinaryWebSocketFrame result = new BinaryWebSocketFrame(); BinaryWebSocketFrame result = new BinaryWebSocketFrame();
//System.out.println("ByteBufToWebSocketFrameEncoder encode - " + ByteBufUtil.hexDump(bb)); // System.out.println("ByteBufToWebSocketFrameEncoder encode - " +
// ByteBufUtil.hexDump(bb));
result.content().writeBytes(bb); result.content().writeBytes(bb);
out.add(result); out.add(result);
} }
@@ -102,13 +104,17 @@ public class NettyAcceptor implements ServerAcceptor {
private int nettyChannelTimeoutSeconds; private int nettyChannelTimeoutSeconds;
@Override @Override
public void initialize(ProtocolProcessor processor, IConfig props, ISslContextCreator sslCtxCreator) throws IOException { public void initialize(ProtocolProcessor processor, IConfig props, ISslContextCreator sslCtxCreator)
throws IOException {
LOG.info("Initializing Netty acceptor..."); LOG.info("Initializing Netty acceptor...");
nettySoBacklog = Integer.parseInt(props.getProperty(BrokerConstants.NETTY_SO_BACKLOG_PROPERTY_NAME, "128")); nettySoBacklog = Integer.parseInt(props.getProperty(BrokerConstants.NETTY_SO_BACKLOG_PROPERTY_NAME, "128"));
nettySoReuseaddr = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_REUSEADDR_PROPERTY_NAME, "true")); nettySoReuseaddr = Boolean
nettyTcpNodelay = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_TCP_NODELAY_PROPERTY_NAME, "true")); .parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_REUSEADDR_PROPERTY_NAME, "true"));
nettySoKeepalive = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_KEEPALIVE_PROPERTY_NAME, "true")); nettyTcpNodelay = Boolean
.parseBoolean(props.getProperty(BrokerConstants.NETTY_TCP_NODELAY_PROPERTY_NAME, "true"));
nettySoKeepalive = Boolean
.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_KEEPALIVE_PROPERTY_NAME, "true"));
nettyChannelTimeoutSeconds = Integer nettyChannelTimeoutSeconds = Integer
.parseInt(props.getProperty(BrokerConstants.NETTY_CHANNEL_TIMEOUT_SECONDS_PROPERTY_NAME, "10")); .parseInt(props.getProperty(BrokerConstants.NETTY_CHANNEL_TIMEOUT_SECONDS_PROPERTY_NAME, "10"));
@@ -134,9 +140,9 @@ public class NettyAcceptor implements ServerAcceptor {
private void initFactory(String host, int port, String protocol, final PipelineInitializer pipeliner) { private void initFactory(String host, int port, String protocol, final PipelineInitializer pipeliner) {
LOG.info("Initializing server. Protocol = {}.", protocol); LOG.info("Initializing server. Protocol = {}.", protocol);
ServerBootstrap b = new ServerBootstrap(); ServerBootstrap b = new ServerBootstrap();
b.group(m_bossGroup, m_workerGroup) b.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() { .childHandler(new ChannelInitializer<SocketChannel>() {
@Override @Override
public void initChannel(SocketChannel ch) throws Exception { public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline(); ChannelPipeline pipeline = ch.pipeline();
@@ -147,9 +153,7 @@ public class NettyAcceptor implements ServerAcceptor {
throw th; throw th;
} }
} }
}) }).option(ChannelOption.SO_BACKLOG, nettySoBacklog).option(ChannelOption.SO_REUSEADDR, nettySoReuseaddr)
.option(ChannelOption.SO_BACKLOG, nettySoBacklog)
.option(ChannelOption.SO_REUSEADDR, nettySoReuseaddr)
.option(ChannelOption.TCP_NODELAY, nettyTcpNodelay) .option(ChannelOption.TCP_NODELAY, nettyTcpNodelay)
.childOption(ChannelOption.SO_KEEPALIVE, nettySoKeepalive); .childOption(ChannelOption.SO_KEEPALIVE, nettySoKeepalive);
try { try {
@@ -169,11 +173,15 @@ public class NettyAcceptor implements ServerAcceptor {
String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME); String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
String tcpPortProp = props.getProperty(PORT_PROPERTY_NAME, DISABLED_PORT_BIND); String tcpPortProp = props.getProperty(PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
if (DISABLED_PORT_BIND.equals(tcpPortProp)) { if (DISABLED_PORT_BIND.equals(tcpPortProp)) {
LOG.info("The property {} has been setted to {}. TCP MQTT will be disabled.", BrokerConstants.PORT_PROPERTY_NAME, DISABLED_PORT_BIND); LOG.info(
"The property {} has been setted to {}. TCP MQTT will be disabled.",
BrokerConstants.PORT_PROPERTY_NAME,
DISABLED_PORT_BIND);
return; return;
} }
int port = Integer.parseInt(tcpPortProp); int port = Integer.parseInt(tcpPortProp);
initFactory(host, port, "TCP MQTT", new PipelineInitializer() { initFactory(host, port, "TCP MQTT", new PipelineInitializer() {
@Override @Override
void init(ChannelPipeline pipeline) { void init(ChannelPipeline pipeline) {
pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds)); pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds));
@@ -194,8 +202,10 @@ public class NettyAcceptor implements ServerAcceptor {
String webSocketPortProp = props.getProperty(WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND); String webSocketPortProp = props.getProperty(WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
if (DISABLED_PORT_BIND.equals(webSocketPortProp)) { if (DISABLED_PORT_BIND.equals(webSocketPortProp)) {
// Do nothing no WebSocket configured // Do nothing no WebSocket configured
LOG.info("The property {} has been setted to {}. Websocket MQTT will be disabled.", LOG.info(
BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, DISABLED_PORT_BIND); "The property {} has been setted to {}. Websocket MQTT will be disabled.",
BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME,
DISABLED_PORT_BIND);
return; return;
} }
int port = Integer.parseInt(webSocketPortProp); int port = Integer.parseInt(webSocketPortProp);
@@ -204,11 +214,14 @@ public class NettyAcceptor implements ServerAcceptor {
String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME); String host = props.getProperty(BrokerConstants.HOST_PROPERTY_NAME);
initFactory(host, port, "Websocket MQTT", new PipelineInitializer() { initFactory(host, port, "Websocket MQTT", new PipelineInitializer() {
@Override @Override
void init(ChannelPipeline pipeline) { void init(ChannelPipeline pipeline) {
pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpServerCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("webSocketHandler", new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST)); pipeline.addLast(
"webSocketHandler",
new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder()); pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder()); pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds)); pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds));
@@ -223,13 +236,16 @@ public class NettyAcceptor implements ServerAcceptor {
}); });
} }
private void initializeSSLTCPTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext) throws IOException { private void initializeSSLTCPTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
throws IOException {
LOG.info("Configuring SSL MQTT transport..."); LOG.info("Configuring SSL MQTT transport...");
String sslPortProp = props.getProperty(SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND); String sslPortProp = props.getProperty(SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
if (DISABLED_PORT_BIND.equals(sslPortProp)) { if (DISABLED_PORT_BIND.equals(sslPortProp)) {
// Do nothing no SSL configured // Do nothing no SSL configured
LOG.info("The property {} has been setted to {}. SSL MQTT will be disabled.", LOG.info(
BrokerConstants.SSL_PORT_PROPERTY_NAME, DISABLED_PORT_BIND); "The property {} has been setted to {}. SSL MQTT will be disabled.",
BrokerConstants.SSL_PORT_PROPERTY_NAME,
DISABLED_PORT_BIND);
return; return;
} }
@@ -241,6 +257,7 @@ public class NettyAcceptor implements ServerAcceptor {
String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false"); String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false");
final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth); final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth);
initFactory(host, sslPort, "SSL MQTT", new PipelineInitializer() { initFactory(host, sslPort, "SSL MQTT", new PipelineInitializer() {
@Override @Override
void init(ChannelPipeline pipeline) throws Exception { void init(ChannelPipeline pipeline) throws Exception {
pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth)); pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth));
@@ -257,13 +274,16 @@ public class NettyAcceptor implements ServerAcceptor {
}); });
} }
private void initializeWSSTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext) throws IOException { private void initializeWSSTransport(final NettyMQTTHandler handler, IConfig props, final SSLContext sslContext)
throws IOException {
LOG.info("Configuring secure websocket MQTT transport..."); LOG.info("Configuring secure websocket MQTT transport...");
String sslPortProp = props.getProperty(WSS_PORT_PROPERTY_NAME, DISABLED_PORT_BIND); String sslPortProp = props.getProperty(WSS_PORT_PROPERTY_NAME, DISABLED_PORT_BIND);
if (DISABLED_PORT_BIND.equals(sslPortProp)) { if (DISABLED_PORT_BIND.equals(sslPortProp)) {
// Do nothing no SSL configured // Do nothing no SSL configured
LOG.info("The property {} has been setted to {}. Secure websocket MQTT will be disabled.", LOG.info(
BrokerConstants.WSS_PORT_PROPERTY_NAME, DISABLED_PORT_BIND); "The property {} has been setted to {}. Secure websocket MQTT will be disabled.",
BrokerConstants.WSS_PORT_PROPERTY_NAME,
DISABLED_PORT_BIND);
return; return;
} }
int sslPort = Integer.parseInt(sslPortProp); int sslPort = Integer.parseInt(sslPortProp);
@@ -272,13 +292,16 @@ public class NettyAcceptor implements ServerAcceptor {
String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false"); String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false");
final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth); final boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth);
initFactory(host, sslPort, "Secure websocket", new PipelineInitializer() { initFactory(host, sslPort, "Secure websocket", new PipelineInitializer() {
@Override @Override
void init(ChannelPipeline pipeline) throws Exception { void init(ChannelPipeline pipeline) throws Exception {
pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth)); pipeline.addLast("ssl", createSslHandler(sslContext, needsClientAuth));
pipeline.addLast("httpEncoder", new HttpResponseEncoder()); pipeline.addLast("httpEncoder", new HttpResponseEncoder());
pipeline.addLast("httpDecoder", new HttpRequestDecoder()); pipeline.addLast("httpDecoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("webSocketHandler", new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST)); pipeline.addLast(
"webSocketHandler",
new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder()); pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder()); pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds)); pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0, nettyChannelTimeoutSeconds));
@@ -303,8 +326,8 @@ public class NettyAcceptor implements ServerAcceptor {
Future<?> bossWaiter = m_bossGroup.shutdownGracefully(); Future<?> bossWaiter = m_bossGroup.shutdownGracefully();
/* /*
* We shouldn't raise an IllegalStateException if we are interrupted. If * We shouldn't raise an IllegalStateException if we are interrupted. If we did so, the
* we did so, the broker is not shut down properly. * broker is not shut down properly.
*/ */
LOG.info("Waiting for worker and boss event loop groups to terminate..."); LOG.info("Waiting for worker and boss event loop groups to terminate...");
try { try {
@@ -326,12 +349,16 @@ public class NettyAcceptor implements ServerAcceptor {
LOG.info("Collecting message metrics..."); LOG.info("Collecting message metrics...");
MessageMetrics metrics = m_metricsCollector.computeMetrics(); MessageMetrics metrics = m_metricsCollector.computeMetrics();
LOG.info("The metrics have been collected. Read messages = {}, written messages = {}.", LOG.info(
metrics.messagesRead(), metrics.messagesWrote()); "The metrics have been collected. Read messages = {}, written messages = {}.",
metrics.messagesRead(),
metrics.messagesWrote());
LOG.info("Collecting bytes metrics..."); LOG.info("Collecting bytes metrics...");
BytesMetrics bytesMetrics = m_bytesMetricsCollector.computeMetrics(); BytesMetrics bytesMetrics = m_bytesMetricsCollector.computeMetrics();
LOG.info("The bytes metrics have been collected. Read bytes = {}, written bytes = {}.", bytesMetrics.readBytes(), LOG.info(
"The bytes metrics have been collected. Read bytes = {}, written bytes = {}.",
bytesMetrics.readBytes(),
bytesMetrics.wroteBytes()); bytesMetrics.wroteBytes());
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty; package io.moquette.server.netty;
import io.moquette.spi.impl.ProtocolProcessor; import io.moquette.spi.impl.ProtocolProcessor;
@@ -22,10 +23,8 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.mqtt.*; import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE; import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
/** /**
* *
* @author andrea * @author andrea
@@ -75,7 +74,12 @@ public class NettyMQTTHandler extends ChannelInboundHandlerAdapter {
m_processor.processPubAck(ctx.channel(), (MqttPubAckMessage) msg); m_processor.processPubAck(ctx.channel(), (MqttPubAckMessage) msg);
break; break;
case PINGREQ: case PINGREQ:
MqttFixedHeader pingHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, AT_MOST_ONCE, false, 0); MqttFixedHeader pingHeader = new MqttFixedHeader(
MqttMessageType.PINGRESP,
false,
AT_MOST_ONCE,
false,
0);
MqttMessage pingResp = new MqttMessage(pingHeader); MqttMessage pingResp = new MqttMessage(pingHeader);
ctx.writeAndFlush(pingResp); ctx.writeAndFlush(pingResp);
break; break;
@@ -99,8 +103,11 @@ public class NettyMQTTHandler extends ChannelInboundHandlerAdapter {
@Override @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.error( LOG.error(
"An unexpected exception was caught while processing MQTT message. Closing Netty channel. MqttClientId = {}, cause = {}, errorMessage = {}.", "An unexpected exception was caught while processing MQTT message. "
NettyUtils.clientID(ctx.channel()), cause.getCause(), cause.getMessage()); + "Closing Netty channel. MqttClientId = {}, cause = {}, errorMessage = {}.",
NettyUtils.clientID(ctx.channel()),
cause.getCause(),
cause.getMessage());
ctx.close(); ctx.close();
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty; package io.moquette.server.netty;
import io.moquette.server.Constants; import io.moquette.server.Constants;
@@ -13,9 +13,11 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty.metrics; package io.moquette.server.netty.metrics;
public class BytesMetrics { public class BytesMetrics {
private long m_readBytes = 0; private long m_readBytes = 0;
private long m_wroteBytes = 0; private long m_wroteBytes = 0;
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty.metrics; package io.moquette.server.netty.metrics;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty.metrics; package io.moquette.server.netty.metrics;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
@@ -55,10 +56,8 @@ public class BytesMetricsHandler extends ChannelDuplexHandler {
ctx.write(msg, promise); ctx.write(msg, promise);
} }
@Override @Override
public void close(ChannelHandlerContext ctx, public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
ChannelPromise promise) throws Exception {
BytesMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get(); BytesMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
m_collector.sumReadBytes(metrics.readBytes()); m_collector.sumReadBytes(metrics.readBytes());
m_collector.sumWroteBytes(metrics.wroteBytes()); m_collector.sumWroteBytes(metrics.wroteBytes());
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty.metrics; package io.moquette.server.netty.metrics;
import io.moquette.server.netty.NettyUtils; import io.moquette.server.netty.NettyUtils;
@@ -23,7 +24,6 @@ import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.mqtt.*; import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.moquette.spi.impl.Utils.messageId; import static io.moquette.spi.impl.Utils.messageId;
/** /**
@@ -54,7 +54,11 @@ public class MQTTMessageLogger extends ChannelDuplexHandler {
break; break;
case SUBSCRIBE: case SUBSCRIBE:
MqttSubscribeMessage subscribe = (MqttSubscribeMessage) msg; MqttSubscribeMessage subscribe = (MqttSubscribeMessage) msg;
LOG.info("{} SUBSCRIBE <{}> to topics {}", direction, clientID, subscribe.payload().topicSubscriptions()); LOG.info(
"{} SUBSCRIBE <{}> to topics {}",
direction,
clientID,
subscribe.payload().topicSubscriptions());
break; break;
case UNSUBSCRIBE: case UNSUBSCRIBE:
MqttUnsubscribeMessage unsubscribe = (MqttUnsubscribeMessage) msg; MqttUnsubscribeMessage unsubscribe = (MqttUnsubscribeMessage) msg;
@@ -13,9 +13,11 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty.metrics; package io.moquette.server.netty.metrics;
public class MessageMetrics { public class MessageMetrics {
private long m_messagesRead = 0; private long m_messagesRead = 0;
private long m_messageWrote = 0; private long m_messageWrote = 0;
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty.metrics; package io.moquette.server.netty.metrics;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
@@ -21,6 +22,7 @@ import java.util.concurrent.atomic.AtomicLong;
* Collects all the metrics from the various pipeline. * Collects all the metrics from the various pipeline.
*/ */
public class MessageMetricsCollector { public class MessageMetricsCollector {
private AtomicLong readMsgs = new AtomicLong(); private AtomicLong readMsgs = new AtomicLong();
private AtomicLong wroteMsgs = new AtomicLong(); private AtomicLong wroteMsgs = new AtomicLong();
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server.netty.metrics; package io.moquette.server.netty.metrics;
import io.netty.channel.Channel; import io.netty.channel.Channel;
@@ -54,10 +55,8 @@ public class MessageMetricsHandler extends ChannelDuplexHandler {
ctx.write(msg, promise); ctx.write(msg, promise);
} }
@Override @Override
public void close(ChannelHandlerContext ctx, public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
ChannelPromise promise) throws Exception {
MessageMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get(); MessageMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
m_collector.sumReadMessages(metrics.messagesRead()); m_collector.sumReadMessages(metrics.messagesRead());
m_collector.sumWroteMessages(metrics.messagesWrote()); m_collector.sumWroteMessages(metrics.messagesWrote());
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi; package io.moquette.spi;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISessionsStore.ClientTopicCouple;
@@ -20,7 +21,6 @@ import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore; import io.moquette.spi.impl.subscriptions.SubscriptionsStore;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
@@ -55,7 +55,8 @@ public class ClientSession {
private volatile boolean cleanSession; private volatile boolean cleanSession;
// private BlockingQueue<AbstractMessage> m_queueToPublish = new ArrayBlockingQueue<>(Constants.MAX_MESSAGE_QUEUE); // private BlockingQueue<AbstractMessage> m_queueToPublish = new
// ArrayBlockingQueue<>(Constants.MAX_MESSAGE_QUEUE);
public ClientSession(String clientID, IMessagesStore messagesStore, ISessionsStore sessionsStore, public ClientSession(String clientID, IMessagesStore messagesStore, ISessionsStore sessionsStore,
boolean cleanSession) { boolean cleanSession) {
@@ -66,12 +67,12 @@ public class ClientSession {
} }
/** /**
* Return the list of persisted publishes for the given clientID. * Return the list of persisted publishes for the given clientID. For QoS1 and QoS2 with clean
* For QoS1 and QoS2 with clean session flag, this method return the list of * session flag, this method return the list of missed publish events while the client was
* missed publish events while the client was disconnected. * disconnected.
* *
* @return the list of messages to be delivered for client related to the session. * @return the list of messages to be delivered for client related to the session.
* */ */
public BlockingQueue<IMessagesStore.StoredMessage> queue() { public BlockingQueue<IMessagesStore.StoredMessage> queue() {
LOG.info("Retrieving stored messages. MqttClientId = {}.", clientID); LOG.info("Retrieving stored messages. MqttClientId = {}.", clientID);
return this.m_sessionsStore.queue(clientID); return this.m_sessionsStore.queue(clientID);
@@ -83,11 +84,16 @@ public class ClientSession {
} }
public boolean subscribe(Subscription newSubscription) { public boolean subscribe(Subscription newSubscription) {
LOG.info("Adding new subscription. MqttClientId = {}, topics = {}, qos = {}.", newSubscription.getClientId(), LOG.info(
newSubscription.getTopicFilter(), newSubscription.getRequestedQos()); "Adding new subscription. MqttClientId = {}, topics = {}, qos = {}.",
newSubscription.getClientId(),
newSubscription.getTopicFilter(),
newSubscription.getRequestedQos());
boolean validTopic = SubscriptionsStore.validate(newSubscription.getTopicFilter()); boolean validTopic = SubscriptionsStore.validate(newSubscription.getTopicFilter());
if (!validTopic) { if (!validTopic) {
LOG.warn("The topic filter is not valid. MqttClientId = {}, topics = {}.", newSubscription.getClientId(), LOG.warn(
"The topic filter is not valid. MqttClientId = {}, topics = {}.",
newSubscription.getClientId(),
newSubscription.getTopicFilter()); newSubscription.getTopicFilter());
// send SUBACK with 0x80 for this topic filter // send SUBACK with 0x80 for this topic filter
return false; return false;
@@ -97,8 +103,12 @@ public class ClientSession {
// update the selected subscriptions if not present or if has a greater qos // update the selected subscriptions if not present or if has a greater qos
if (existingSub == null || existingSub.getRequestedQos().value() < newSubscription.getRequestedQos().value()) { if (existingSub == null || existingSub.getRequestedQos().value() < newSubscription.getRequestedQos().value()) {
if (existingSub != null) { if (existingSub != null) {
LOG.info("The subscription already existed with a lower QoS value. It will be updated. MqttClientId = {}, topics = {}, existingQos = {}, newQos = {}.", LOG.info(
newSubscription.getClientId(), newSubscription.getTopicFilter(), existingSub.getRequestedQos(), "The subscription already existed with a lower QoS value. It will be updated. "
+ "MqttClientId = {}, topics = {}, existingQos = {}, newQos = {}.",
newSubscription.getClientId(),
newSubscription.getTopicFilter(),
existingSub.getRequestedQos(),
newSubscription.getRequestedQos()); newSubscription.getRequestedQos());
subscriptions.remove(newSubscription); subscriptions.remove(newSubscription);
} }
@@ -126,7 +136,6 @@ public class ClientSession {
// cleanup topic subscriptions // cleanup topic subscriptions
cleanSession(); cleanSession();
} }
} }
public void cleanSession() { public void cleanSession() {
@@ -170,8 +179,10 @@ public class ClientSession {
/** /**
* Enqueue a message to be sent to the client. * Enqueue a message to be sent to the client.
* @param message the message to enqueue. *
* */ * @param message
* the message to enqueue.
*/
public void enqueue(IMessagesStore.StoredMessage message) { public void enqueue(IMessagesStore.StoredMessage message) {
this.m_sessionsStore.queue(this.clientID).add(message); this.m_sessionsStore.queue(this.clientID).add(message);
} }
@@ -13,11 +13,12 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi; package io.moquette.spi;
/** /**
*/ */
public interface IMatchingCondition { public interface IMatchingCondition {
boolean match(String key); boolean match(String key);
} }
@@ -13,12 +13,12 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi; package io.moquette.spi;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.handler.codec.mqtt.MqttQoS; import io.netty.handler.codec.mqtt.MqttQoS;
import java.io.Serializable; import java.io.Serializable;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Collection; import java.util.Collection;
@@ -29,6 +29,7 @@ import java.util.Collection;
public interface IMessagesStore { public interface IMessagesStore {
class StoredMessage implements Serializable { class StoredMessage implements Serializable {
private static final long serialVersionUID = 1755296138639817304L; private static final long serialVersionUID = 1755296138639817304L;
final MqttQoS m_qos; final MqttQoS m_qos;
final byte[] m_payload; final byte[] m_payload;
@@ -95,41 +96,42 @@ public interface IMessagesStore {
@Override @Override
public String toString() { public String toString() {
return "PublishEvent{" + return "PublishEvent{" + "m_msgID=" + m_msgID + ", clientID='" + m_clientID + '\'' + ", m_retain="
"m_msgID=" + m_msgID + + m_retained + ", m_qos=" + m_qos + ", m_topic='" + m_topic + '\'' + '}';
", clientID='" + m_clientID + '\'' +
", m_retain=" + m_retained +
", m_qos=" + m_qos +
", m_topic='" + m_topic + '\'' +
'}';
} }
} }
/** /**
* Used to initialize all persistent store structures * Used to initialize all persistent store structures
* */ */
void initStore(); void initStore();
/** /**
* Persist the message. * Persist the message. If the message is empty then the topic is cleaned, else it's stored.
* If the message is empty then the topic is cleaned, else it's stored. *
* @param topic for the retained. * @param topic
* @param guid of the message to mark as retained. * for the retained.
* @param guid
* of the message to mark as retained.
*/ */
void storeRetained(String topic, MessageGUID guid); void storeRetained(String topic, MessageGUID guid);
/** /**
* Return a list of retained messages that satisfy the condition. * Return a list of retained messages that satisfy the condition.
* @param condition the condition to match during the search. *
* @param condition
* the condition to match during the search.
* @return the collection of matching messages. * @return the collection of matching messages.
*/ */
Collection<StoredMessage> searchMatching(IMatchingCondition condition); Collection<StoredMessage> searchMatching(IMatchingCondition condition);
/** /**
* Persist the message. * Persist the message.
* @param storedMessage the message to store for future usage. *
* @param storedMessage
* the message to store for future usage.
* @return the unique id in the storage (guid). * @return the unique id in the storage (guid).
* */ */
MessageGUID storePublishForFuture(StoredMessage storedMessage); MessageGUID storePublishForFuture(StoredMessage storedMessage);
void dropMessagesInSession(String clientID); void dropMessagesInSession(String clientID);
@@ -13,13 +13,13 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi; package io.moquette.spi;
/** /**
* Callback interface used to be notified of some events from the input event queue. * Callback interface used to be notified of some events from the input event queue.
* *
* It's the abstraction of the messaging stuff attached in after the front protocol * It's the abstraction of the messaging stuff attached in after the front protocol parsing stuff.
* parsing stuff.
* *
* @author andrea * @author andrea
*/ */
@@ -13,12 +13,12 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi; package io.moquette.spi;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import io.moquette.spi.IMessagesStore.StoredMessage; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
@@ -30,6 +30,7 @@ import io.moquette.spi.impl.subscriptions.Subscription;
public interface ISessionsStore { public interface ISessionsStore {
class ClientTopicCouple { class ClientTopicCouple {
public final String topicFilter; public final String topicFilter;
public final String clientID; public final String clientID;
@@ -40,12 +41,15 @@ public interface ISessionsStore {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
ClientTopicCouple that = (ClientTopicCouple) o; ClientTopicCouple that = (ClientTopicCouple) o;
if (topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null) return false; if (topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null)
return false;
return !(clientID != null ? !clientID.equals(that.clientID) : that.clientID != null); return !(clientID != null ? !clientID.equals(that.clientID) : that.clientID != null);
} }
@@ -58,10 +62,7 @@ public interface ISessionsStore {
@Override @Override
public String toString() { public String toString() {
return "ClientTopicCouple{" + return "ClientTopicCouple{" + "topicFilter='" + topicFilter + '\'' + ", clientID='" + clientID + '\'' + '}';
"topicFilter='" + topicFilter + '\'' +
", clientID='" + clientID + '\'' +
'}';
} }
} }
@@ -72,32 +73,40 @@ public interface ISessionsStore {
/** /**
* Add a new subscription to the session * Add a new subscription to the session
* @param newSubscription the subscription to add. *
* @param newSubscription
* the subscription to add.
*/ */
void addNewSubscription(Subscription newSubscription); void addNewSubscription(Subscription newSubscription);
/** /**
* Removed a specific subscription * Removed a specific subscription
* @param topic the topic of the subscription. *
* @param clientID the session client. * @param topic
* */ * the topic of the subscription.
* @param clientID
* the session client.
*/
void removeSubscription(String topic, String clientID); void removeSubscription(String topic, String clientID);
/** /**
* Remove all the subscriptions of the session * Remove all the subscriptions of the session
* @param sessionID the client ID *
* @param sessionID
* the client ID
*/ */
void wipeSubscriptions(String sessionID); void wipeSubscriptions(String sessionID);
/** /**
* Return all topic filters to recreate the subscription tree. * Return all topic filters to recreate the subscription tree.
* */ */
List<ClientTopicCouple> listAllSubscriptions(); List<ClientTopicCouple> listAllSubscriptions();
/** /**
* @param couple the subscription descriptor. * @param couple
* the subscription descriptor.
* @return the subscription stored by clientID and topicFilter, if any else null; * @return the subscription stored by clientID and topicFilter, if any else null;
* */ */
Subscription getSubscription(ClientTopicCouple couple); Subscription getSubscription(ClientTopicCouple couple);
/* /*
@@ -106,7 +115,8 @@ public interface ISessionsStore {
List<Subscription> getSubscriptions(); List<Subscription> getSubscriptions();
/** /**
* @param clientID the session client ID. * @param clientID
* the session client ID.
* @return true iff there are subscriptions persisted with clientID * @return true iff there are subscriptions persisted with clientID
*/ */
boolean contains(String clientID); boolean contains(String clientID);
@@ -114,13 +124,15 @@ public interface ISessionsStore {
ClientSession createNewSession(String clientID, boolean cleanSession); ClientSession createNewSession(String clientID, boolean cleanSession);
/** /**
* @param clientID the client owning the session. * @param clientID
* the client owning the session.
* @return the session for the given clientID, null if not found. * @return the session for the given clientID, null if not found.
* */ */
ClientSession sessionForClient(String clientID); ClientSession sessionForClient(String clientID);
/** /**
* Returns all the sessions * Returns all the sessions
*
* @return * @return
*/ */
Collection<ClientSession> getAllSessions(); Collection<ClientSession> getAllSessions();
@@ -129,24 +141,32 @@ public interface ISessionsStore {
/** /**
* Save the binding messageID, clientID - guid * Save the binding messageID, clientID - guid
* @param clientID the client ID *
* @param messageID the message ID * @param clientID
* @param guid the uuid of the message to mark as inflight. * the client ID
* */ * @param messageID
* the message ID
* @param guid
* the uuid of the message to mark as inflight.
*/
void inFlight(String clientID, int messageID, MessageGUID guid); void inFlight(String clientID, int messageID, MessageGUID guid);
/** /**
* Return the next valid packetIdentifier for the given client session. * Return the next valid packetIdentifier for the given client session.
* @param clientID the clientID requesting next packet id. *
* @param clientID
* the clientID requesting next packet id.
* @return the next valid id. * @return the next valid id.
* */ */
int nextPacketID(String clientID); int nextPacketID(String clientID);
/** /**
* List the guids for retained messages for the session * List the guids for retained messages for the session
* @param clientID the client ID owning the queue. *
* @param clientID
* the client ID owning the queue.
* @return the list of queue message UUIDs. * @return the list of queue message UUIDs.
* */ */
BlockingQueue<StoredMessage> queue(String clientID); BlockingQueue<StoredMessage> queue(String clientID);
void dropQueue(String clientID); void dropQueue(String clientID);
@@ -154,10 +174,12 @@ public interface ISessionsStore {
void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID); void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID);
/** /**
* @param clientID the client ID accessing the second phase. * @param clientID
* @param messageID the message ID that reached the second phase. * the client ID accessing the second phase.
* @param messageID
* the message ID that reached the second phase.
* @return the guid of message just acked. * @return the guid of message just acked.
* */ */
MessageGUID secondPhaseAcknowledged(String clientID, int messageID); MessageGUID secondPhaseAcknowledged(String clientID, int messageID);
MessageGUID mapToGuid(String clientID, int messageID); MessageGUID mapToGuid(String clientID, int messageID);
@@ -181,8 +203,7 @@ public interface ISessionsStore {
int getPendingPublishMessagesNo(String clientID); int getPendingPublishMessagesNo(String clientID);
/** /**
* Returns the number of second-phase ACK pending messages for the given * Returns the number of second-phase ACK pending messages for the given client ID
* client ID
* *
* @param clientID * @param clientID
* @return * @return
@@ -13,14 +13,16 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi; package io.moquette.spi;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Value object for GUIDs of messages. * Value object for GUIDs of messages.
* */ */
public class MessageGUID implements Serializable { public class MessageGUID implements Serializable {
private static final long serialVersionUID = 4315161987111542406L; private static final long serialVersionUID = 4315161987111542406L;
private final String guid; private final String guid;
@@ -30,13 +32,14 @@ public class MessageGUID implements Serializable {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
MessageGUID that = (MessageGUID) o; MessageGUID that = (MessageGUID) o;
return guid != null ? guid.equals(that.guid) : that.guid == null; return guid != null ? guid.equals(that.guid) : that.guid == null;
} }
@Override @Override
@@ -46,8 +49,6 @@ public class MessageGUID implements Serializable {
@Override @Override
public String toString() { public String toString() {
return "MessageGUID{" + return "MessageGUID{" + "guid='" + guid + '\'' + '}';
"guid='" + guid + '\'' +
'}';
} }
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -25,7 +26,6 @@ import io.netty.handler.codec.mqtt.MqttConnectMessage;
import io.netty.handler.codec.mqtt.MqttPublishMessage; import io.netty.handler.codec.mqtt.MqttPublishMessage;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -33,7 +33,6 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static io.moquette.logging.LoggingUtils.getInterceptorIds; import static io.moquette.logging.LoggingUtils.getInterceptorIds;
/** /**
@@ -61,6 +60,7 @@ final class BrokerInterceptor implements Interceptor {
/** /**
* Configures a broker interceptor, with a thread pool of one thread. * Configures a broker interceptor, with a thread pool of one thread.
*
* @param handlers * @param handlers
*/ */
public BrokerInterceptor(List<InterceptHandler> handlers) { public BrokerInterceptor(List<InterceptHandler> handlers) {
@@ -68,8 +68,7 @@ final class BrokerInterceptor implements Interceptor {
} }
/** /**
* Configures a broker interceptor using the pool size specified in the * Configures a broker interceptor using the pool size specified in the IConfig argument.
* IConfig argument.
*/ */
public BrokerInterceptor(IConfig props, List<InterceptHandler> handlers) { public BrokerInterceptor(IConfig props, List<InterceptHandler> handlers) {
this(Integer.parseInt(props.getProperty(BrokerConstants.BROKER_INTERCEPTOR_THREAD_POOL_SIZE, "1")), handlers); this(Integer.parseInt(props.getProperty(BrokerConstants.BROKER_INTERCEPTOR_THREAD_POOL_SIZE, "1")), handlers);
@@ -84,7 +83,8 @@ final class BrokerInterceptor implements Interceptor {
try { try {
LOG.info("Waiting for thread pool tasks to terminate..."); LOG.info("Waiting for thread pool tasks to terminate...");
executor.awaitTermination(10L, TimeUnit.SECONDS); executor.awaitTermination(10L, TimeUnit.SECONDS);
} catch (InterruptedException e) {} } catch (InterruptedException e) {
}
if (!executor.isTerminated()) { if (!executor.isTerminated()) {
LOG.warn("Forcing shutdown of interceptor thread pool..."); LOG.warn("Forcing shutdown of interceptor thread pool...");
executor.shutdownNow(); executor.shutdownNow();
@@ -94,9 +94,12 @@ final class BrokerInterceptor implements Interceptor {
@Override @Override
public void notifyClientConnected(final MqttConnectMessage msg) { public void notifyClientConnected(final MqttConnectMessage msg) {
for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) { for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) {
LOG.debug("Sending MQTT CONNECT message to interceptor. MqttClientId = {}, interceptorId = {}.", LOG.debug(
msg.payload().clientIdentifier(), handler.getID()); "Sending MQTT CONNECT message to interceptor. MqttClientId = {}, interceptorId = {}.",
msg.payload().clientIdentifier(),
handler.getID());
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onConnect(new InterceptConnectMessage(msg)); handler.onConnect(new InterceptConnectMessage(msg));
@@ -108,9 +111,14 @@ final class BrokerInterceptor implements Interceptor {
@Override @Override
public void notifyClientDisconnected(final String clientID, final String username) { public void notifyClientDisconnected(final String clientID, final String username) {
for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) { for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) {
LOG.debug("Notifying MQTT client disconnection to interceptor. MqttClientId = {}, username = {}, " + LOG.debug(
"interceptorId = {}.", clientID, username, handler.getID()); "Notifying MQTT client disconnection to interceptor. MqttClientId = {}, username = {}, "
+ "interceptorId = {}.",
clientID,
username,
handler.getID());
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onDisconnect(new InterceptDisconnectMessage(clientID, username)); handler.onDisconnect(new InterceptDisconnectMessage(clientID, username));
@@ -122,9 +130,14 @@ final class BrokerInterceptor implements Interceptor {
@Override @Override
public void notifyClientConnectionLost(final String clientID, final String username) { public void notifyClientConnectionLost(final String clientID, final String username) {
for (final InterceptHandler handler : this.handlers.get(InterceptConnectionLostMessage.class)) { for (final InterceptHandler handler : this.handlers.get(InterceptConnectionLostMessage.class)) {
LOG.debug("Notifying unexpected MQTT client disconnection to interceptor. MqttClientId = {}, " + LOG.debug(
"username = {}, interceptorId = {}.", clientID, username, handler.getID()); "Notifying unexpected MQTT client disconnection to interceptor. MqttClientId = {}, "
+ "username = {}, interceptorId = {}.",
clientID,
username,
handler.getID());
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onConnectionLost(new InterceptConnectionLostMessage(clientID, username)); handler.onConnectionLost(new InterceptConnectionLostMessage(clientID, username));
@@ -138,9 +151,15 @@ final class BrokerInterceptor implements Interceptor {
int messageId = msg.variableHeader().messageId(); int messageId = msg.variableHeader().messageId();
String topic = msg.variableHeader().topicName(); String topic = msg.variableHeader().topicName();
for (final InterceptHandler handler : this.handlers.get(InterceptPublishMessage.class)) { for (final InterceptHandler handler : this.handlers.get(InterceptPublishMessage.class)) {
LOG.debug("Notifying MQTT PUBLISH message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, " + LOG.debug(
"interceptorId = {}.", clientID, messageId, topic, handler.getID()); "Notifying MQTT PUBLISH message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, "
+ "interceptorId = {}.",
clientID,
messageId,
topic,
handler.getID());
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onPublish(new InterceptPublishMessage(msg, clientID, username)); handler.onPublish(new InterceptPublishMessage(msg, clientID, username));
@@ -152,9 +171,14 @@ final class BrokerInterceptor implements Interceptor {
@Override @Override
public void notifyTopicSubscribed(final Subscription sub, final String username) { public void notifyTopicSubscribed(final Subscription sub, final String username) {
for (final InterceptHandler handler : this.handlers.get(InterceptSubscribeMessage.class)) { for (final InterceptHandler handler : this.handlers.get(InterceptSubscribeMessage.class)) {
LOG.debug("Notifying MQTT SUBSCRIBE message to interceptor. MqttClientId = {}, topicFilter = {}, " + LOG.debug(
"interceptorId = {}.", sub.getClientId(), sub.getTopicFilter(), handler.getID()); "Notifying MQTT SUBSCRIBE message to interceptor. MqttClientId = {}, topicFilter = {}, "
+ "interceptorId = {}.",
sub.getClientId(),
sub.getTopicFilter(),
handler.getID());
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onSubscribe(new InterceptSubscribeMessage(sub, username)); handler.onSubscribe(new InterceptSubscribeMessage(sub, username));
@@ -166,9 +190,14 @@ final class BrokerInterceptor implements Interceptor {
@Override @Override
public void notifyTopicUnsubscribed(final String topic, final String clientID, final String username) { public void notifyTopicUnsubscribed(final String topic, final String clientID, final String username) {
for (final InterceptHandler handler : this.handlers.get(InterceptUnsubscribeMessage.class)) { for (final InterceptHandler handler : this.handlers.get(InterceptUnsubscribeMessage.class)) {
LOG.debug("Notifying MQTT UNSUBSCRIBE message to interceptor. MqttClientId = {}, topic = {}, " + LOG.debug(
"interceptorId = {}.", clientID, topic, handler.getID()); "Notifying MQTT UNSUBSCRIBE message to interceptor. MqttClientId = {}, topic = {}, "
+ "interceptorId = {}.",
clientID,
topic,
handler.getID());
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onUnsubscribe(new InterceptUnsubscribeMessage(topic, clientID, username)); handler.onUnsubscribe(new InterceptUnsubscribeMessage(topic, clientID, username));
@@ -180,10 +209,15 @@ final class BrokerInterceptor implements Interceptor {
@Override @Override
public void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg) { public void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg) {
for (final InterceptHandler handler : this.handlers.get(InterceptAcknowledgedMessage.class)) { for (final InterceptHandler handler : this.handlers.get(InterceptAcknowledgedMessage.class)) {
LOG.debug("Notifying MQTT ACK message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, " + LOG.debug(
"interceptorId = {}.", "Notifying MQTT ACK message to interceptor. MqttClientId = {}, messageId = {}, topic = {}, "
msg.getMsg().getClientID(), msg.getMsg().getMessageID(), msg.getTopic(), handler.getID()); + "interceptorId = {}.",
msg.getMsg().getClientID(),
msg.getMsg().getMessageID(),
msg.getTopic(),
handler.getID());
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
handler.onMessageAcknowledged(msg); handler.onMessageAcknowledged(msg);
@@ -195,8 +229,10 @@ final class BrokerInterceptor implements Interceptor {
@Override @Override
public void addInterceptHandler(InterceptHandler interceptHandler) { public void addInterceptHandler(InterceptHandler interceptHandler) {
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler); Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
LOG.info("Adding MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.", LOG.info(
interceptHandler.getID(), interceptedMessageTypes); "Adding MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.",
interceptHandler.getID(),
interceptedMessageTypes);
for (Class<?> interceptMessageType : interceptedMessageTypes) { for (Class<?> interceptMessageType : interceptedMessageTypes) {
this.handlers.get(interceptMessageType).add(interceptHandler); this.handlers.get(interceptMessageType).add(interceptHandler);
} }
@@ -205,15 +241,17 @@ final class BrokerInterceptor implements Interceptor {
@Override @Override
public void removeInterceptHandler(InterceptHandler interceptHandler) { public void removeInterceptHandler(InterceptHandler interceptHandler) {
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler); Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
LOG.info("Removing MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.", LOG.info(
interceptHandler.getID(), interceptedMessageTypes); "Removing MQTT message interceptor. InterceptorId = {}, handledMessageTypes = {}.",
interceptHandler.getID(),
interceptedMessageTypes);
for (Class<?> interceptMessageType : interceptedMessageTypes) { for (Class<?> interceptMessageType : interceptedMessageTypes) {
this.handlers.get(interceptMessageType).remove(interceptHandler); this.handlers.get(interceptMessageType).remove(interceptHandler);
} }
} }
private static Class<?>[] getInterceptedMessageTypes(InterceptHandler interceptHandler) { private static Class<?>[] getInterceptedMessageTypes(InterceptHandler interceptHandler) {
Class<?> interceptedMessageTypes[] = interceptHandler.getInterceptedMessageTypes(); Class<?>[] interceptedMessageTypes = interceptHandler.getInterceptedMessageTypes();
if (interceptedMessageTypes == null) { if (interceptedMessageTypes == null) {
return InterceptHandler.ALL_MESSAGE_TYPES; return InterceptHandler.ALL_MESSAGE_TYPES;
} }
@@ -13,10 +13,10 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
/** /**
@@ -24,6 +24,7 @@ import java.nio.ByteBuffer;
* @author andrea * @author andrea
*/ */
class DebugUtils { class DebugUtils {
static String payload2Str(ByteBuffer content) { static String payload2Str(ByteBuffer content) {
byte[] b = new byte[content.remaining()]; byte[] b = new byte[content.remaining()];
content.mark(); content.mark();
@@ -1,5 +1,5 @@
package io.moquette.spi.impl;
package io.moquette.spi.impl;
import io.moquette.spi.ClientSession; import io.moquette.spi.ClientSession;
import io.moquette.spi.IMessagesStore; import io.moquette.spi.IMessagesStore;
@@ -7,7 +7,6 @@ import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.*; import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@@ -28,8 +27,13 @@ class InternalRepublisher {
// fire as retained the message // fire as retained the message
Integer packetID = storedMsg.getQos() == MqttQoS.AT_MOST_ONCE ? null : targetSession.nextPacketId(); Integer packetID = storedMsg.getQos() == MqttQoS.AT_MOST_ONCE ? null : targetSession.nextPacketId();
if (packetID != null) { if (packetID != null) {
LOG.debug("Adding message to inflight zone. MqttClientId = {}, packetId = {}, messageId = {}, topic = {}.", LOG.debug(
targetSession.clientID, packetID, storedMsg.getMessageID(), storedMsg.getTopic()); "Adding message to inflight zone. "
+ "MqttClientId = {}, packetId = {}, messageId = {}, topic = {}.",
targetSession.clientID,
packetID,
storedMsg.getMessageID(),
storedMsg.getTopic());
targetSession.inFlightAckWaiting(storedMsg.getGuid(), packetID); targetSession.inFlightAckWaiting(storedMsg.getGuid(), packetID);
} }
MqttPublishMessage publishMsg = retainedPublish(storedMsg); MqttPublishMessage publishMsg = retainedPublish(storedMsg);
@@ -41,16 +45,18 @@ class InternalRepublisher {
} }
} }
void publishStored(ClientSession clientSession, BlockingQueue<IMessagesStore.StoredMessage> publishedEvents) { void publishStored(ClientSession clientSession, BlockingQueue<IMessagesStore.StoredMessage> publishedEvents) {
List<IMessagesStore.StoredMessage> storedPublishes = new ArrayList<>(); List<IMessagesStore.StoredMessage> storedPublishes = new ArrayList<>();
publishedEvents.drainTo(storedPublishes); publishedEvents.drainTo(storedPublishes);
for (IMessagesStore.StoredMessage pubEvt : storedPublishes) { for (IMessagesStore.StoredMessage pubEvt : storedPublishes) {
// put in flight zone // put in flight zone
LOG.debug("Adding message ot inflight zone. MqttClientId = {}, guid = {}, messageId = {}, topic = {}.", LOG.debug(
clientSession.clientID, pubEvt.getGuid(), pubEvt.getMessageID(), pubEvt.getTopic()); "Adding message ot inflight zone. MqttClientId = {}, guid = {}, messageId = {}, topic = {}.",
clientSession.clientID,
pubEvt.getGuid(),
pubEvt.getMessageID(),
pubEvt.getTopic());
clientSession.inFlightAckWaiting(pubEvt.getGuid(), pubEvt.getMessageID()); clientSession.inFlightAckWaiting(pubEvt.getGuid(), pubEvt.getMessageID());
MqttPublishMessage publishMsg = notRetainedPublish(pubEvt); MqttPublishMessage publishMsg = notRetainedPublish(pubEvt);
// set the PacketIdentifier only for QoS > 0 // set the PacketIdentifier only for QoS > 0
@@ -62,22 +68,43 @@ class InternalRepublisher {
} }
private MqttPublishMessage notRetainedPublish(IMessagesStore.StoredMessage storedMessage, Integer messageID) { private MqttPublishMessage notRetainedPublish(IMessagesStore.StoredMessage storedMessage, Integer messageID) {
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getMessage(), false, messageID); return createPublishForQos(
storedMessage.getTopic(),
storedMessage.getQos(),
storedMessage.getMessage(),
false,
messageID);
} }
private MqttPublishMessage notRetainedPublish(IMessagesStore.StoredMessage storedMessage) { private MqttPublishMessage notRetainedPublish(IMessagesStore.StoredMessage storedMessage) {
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getMessage(), false, 0); return createPublishForQos(
storedMessage.getTopic(),
storedMessage.getQos(),
storedMessage.getMessage(),
false,
0);
} }
private MqttPublishMessage retainedPublish(IMessagesStore.StoredMessage storedMessage) { private MqttPublishMessage retainedPublish(IMessagesStore.StoredMessage storedMessage) {
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getMessage(), true, 0); return createPublishForQos(
storedMessage.getTopic(),
storedMessage.getQos(),
storedMessage.getMessage(),
true,
0);
} }
private MqttPublishMessage retainedPublish(IMessagesStore.StoredMessage storedMessage, Integer packetID) { private MqttPublishMessage retainedPublish(IMessagesStore.StoredMessage storedMessage, Integer packetID) {
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getMessage(), true, packetID); return createPublishForQos(
storedMessage.getTopic(),
storedMessage.getQos(),
storedMessage.getMessage(),
true,
packetID);
} }
public static MqttPublishMessage createPublishForQos(String topic, MqttQoS qos, ByteBuf message, boolean retained, int messageId) { public static MqttPublishMessage createPublishForQos(String topic, MqttQoS qos, ByteBuf message, boolean retained,
int messageId) {
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0); MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0);
MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId); MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId);
return new MqttPublishMessage(fixedHeader, varHeader, message); return new MqttPublishMessage(fixedHeader, varHeader, message);
@@ -1,3 +1,4 @@
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.server.ConnectionDescriptorStore; import io.moquette.server.ConnectionDescriptorStore;
@@ -10,9 +11,7 @@ import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.*; import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import static io.moquette.spi.impl.ProtocolProcessor.lowerQosToTheSubscriptionDesired; import static io.moquette.spi.impl.ProtocolProcessor.lowerQosToTheSubscriptionDesired;
class MessagesPublisher { class MessagesPublisher {
@@ -35,7 +34,8 @@ class MessagesPublisher {
return notRetainedPublishWithMessageId(topic, qos, message, 0); return notRetainedPublishWithMessageId(topic, qos, message, 0);
} }
private static MqttPublishMessage notRetainedPublishWithMessageId(String topic, MqttQoS qos, ByteBuf message, int messageId) { private static MqttPublishMessage notRetainedPublishWithMessageId(String topic, MqttQoS qos, ByteBuf message,
int messageId) {
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, false, 0); MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, false, 0);
MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId); MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId);
return new MqttPublishMessage(fixedHeader, varHeader, message); return new MqttPublishMessage(fixedHeader, varHeader, message);
@@ -59,11 +59,16 @@ class MessagesPublisher {
boolean targetIsActive = this.connectionDescriptors.isConnected(sub.getClientId()); boolean targetIsActive = this.connectionDescriptors.isConnected(sub.getClientId());
//we need to retain because duplicate only copy r/w indexes and don't retain() causing refCnt = 0 // we need to retain because duplicate only copy r/w indexes and don't retain() causing
// refCnt = 0
ByteBuf message = origMessage.retainedDuplicate(); ByteBuf message = origMessage.retainedDuplicate();
if (targetIsActive) { if (targetIsActive) {
LOG.debug("Sending PUBLISH message to active subscriber. MessageId={}, CId={}, topicFilter={}, qos={}", LOG.debug(
pubMsg.getMessageID(), sub.getClientId(), sub.getTopicFilter(), qos); "Sending PUBLISH message to active subscriber. MessageId={}, CId={}, topicFilter={}, qos={}",
pubMsg.getMessageID(),
sub.getClientId(),
sub.getTopicFilter(),
qos);
MqttPublishMessage publishMsg = notRetainedPublish(topic, qos, message); MqttPublishMessage publishMsg = notRetainedPublish(topic, qos, message);
if (qos != MqttQoS.AT_MOST_ONCE) { if (qos != MqttQoS.AT_MOST_ONCE) {
// QoS 1 or 2 // QoS 1 or 2
@@ -75,8 +80,12 @@ class MessagesPublisher {
this.messageSender.sendPublish(targetSession, publishMsg); this.messageSender.sendPublish(targetSession, publishMsg);
} else { } else {
if (!targetSession.isCleanSession()) { if (!targetSession.isCleanSession()) {
LOG.debug("Storing pending PUBLISH inactive message. MessageId={}, CId={}, topicFilter={}, qos={}", LOG.debug(
pubMsg.getMessageID(), sub.getClientId(), sub.getTopicFilter(), qos); "Storing pending PUBLISH inactive message. MessageId={}, CId={}, topicFilter={}, qos={}",
pubMsg.getMessageID(),
sub.getClientId(),
sub.getTopicFilter(),
qos);
// store the message in targetSession queue to deliver // store the message in targetSession queue to deliver
targetSession.enqueue(pubMsg); targetSession.enqueue(pubMsg);
} }
@@ -1,3 +1,4 @@
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.server.ConnectionDescriptorStore; import io.moquette.server.ConnectionDescriptorStore;
@@ -6,7 +7,6 @@ import io.netty.handler.codec.mqtt.MqttPublishMessage;
import io.netty.handler.codec.mqtt.MqttQoS; import io.netty.handler.codec.mqtt.MqttQoS;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage; import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE; import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
@@ -24,8 +24,12 @@ class PersistentQueueMessageSender {
final int messageId = pubMessage.variableHeader().messageId(); final int messageId = pubMessage.variableHeader().messageId();
final String topicName = pubMessage.variableHeader().topicName(); final String topicName = pubMessage.variableHeader().topicName();
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("Sending PUBLISH message. MessageId={}, CId={}, topic={}, qos={}, payload={}", messageId, LOG.debug(
clientId, topicName, DebugUtils.payload2Str(pubMessage.payload())); "Sending PUBLISH message. MessageId={}, CId={}, topic={}, qos={}, payload={}",
messageId,
clientId,
topicName,
DebugUtils.payload2Str(pubMessage.payload()));
} else { } else {
LOG.info("Sending PUBLISH message. MessageId={}, CId={}, topic={}", messageId, clientId, topicName); LOG.info("Sending PUBLISH message. MessageId={}, CId={}, topic={}", messageId, clientId, topicName);
} }
@@ -35,13 +39,23 @@ class PersistentQueueMessageSender {
MqttQoS qos = pubMessage.fixedHeader().qosLevel(); MqttQoS qos = pubMessage.fixedHeader().qosLevel();
if (!messageDelivered && qos != AT_MOST_ONCE && !clientsession.isCleanSession()) { if (!messageDelivered && qos != AT_MOST_ONCE && !clientsession.isCleanSession()) {
LOG.warn( LOG.warn(
"The PUBLISH message could not be delivered. It will be stored. MessageId = {}, CId={}, topic = {}, qos = {}, cleanSession = {}.", "The PUBLISH message could not be delivered. It will be stored. "
messageId, clientId, topicName, qos, false); + "MessageId = {}, CId={}, topic = {}, qos = {}, cleanSession = {}.",
messageId,
clientId,
topicName,
qos,
false);
clientsession.enqueue(asStoredMessage(pubMessage)); clientsession.enqueue(asStoredMessage(pubMessage));
} else { } else {
LOG.warn( LOG.warn(
"The PUBLISH message could not be delivered. It will be discarded. MessageId = {}, CId={}, topic = {}, qos = {}, cleanSession = {}.", "The PUBLISH message could not be delivered. It will be discarded. "
messageId, clientId, topicName, qos, true); + "MessageId = {}, CId={}, topic = {}, qos = {}, cleanSession = {}.",
messageId,
clientId,
topicName,
qos,
true);
} }
} }
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.interception.InterceptHandler; import io.moquette.interception.InterceptHandler;
@@ -34,7 +35,6 @@ import io.netty.handler.codec.mqtt.*;
import io.netty.handler.timeout.IdleStateHandler; import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@@ -43,7 +43,6 @@ import java.util.UUID;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import static io.moquette.spi.impl.InternalRepublisher.createPublishForQos; import static io.moquette.spi.impl.InternalRepublisher.createPublishForQos;
import static io.moquette.spi.impl.Utils.messageId; import static io.moquette.spi.impl.Utils.messageId;
import static io.moquette.spi.impl.Utils.readBytesAndRewind; 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.*; import static io.netty.handler.codec.mqtt.MqttQoS.*;
/** /**
* Class responsible to handle the logic of MQTT protocol it's the director of * Class responsible to handle the logic of MQTT protocol it's the director of the protocol
* the protocol execution. * execution.
* *
* Used by the front facing class ProtocolProcessorBootstrapper. * Used by the front facing class ProtocolProcessorBootstrapper.
* *
@@ -62,6 +61,7 @@ import static io.netty.handler.codec.mqtt.MqttQoS.*;
public class ProtocolProcessor { public class ProtocolProcessor {
static final class WillMessage { static final class WillMessage {
private final String topic; private final String topic;
private final ByteBuffer payload; private final ByteBuffer payload;
private final boolean retained; private final boolean retained;
@@ -89,7 +89,6 @@ public class ProtocolProcessor {
public MqttQoS getQos() { public MqttQoS getQos() {
return qos; return qos;
} }
} }
private enum SubscriptionState { private enum SubscriptionState {
@@ -97,6 +96,7 @@ public class ProtocolProcessor {
} }
private class RunningSubscription { private class RunningSubscription {
final String clientID; final String clientID;
final long packetId; final long packetId;
@@ -107,13 +107,15 @@ public class ProtocolProcessor {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
RunningSubscription that = (RunningSubscription) o; 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);
} }
@Override @Override
@@ -148,49 +150,77 @@ public class ProtocolProcessor {
// maps clientID to Will testament, if specified on CONNECT // maps clientID to Will testament, if specified on CONNECT
private ConcurrentMap<String, WillMessage> m_willStore = new ConcurrentHashMap<>(); private ConcurrentMap<String, WillMessage> m_willStore = new ConcurrentHashMap<>();
ProtocolProcessor() {} 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);
} }
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator,
IAuthenticator authenticator, BrokerInterceptor interceptor) {
boolean allowAnonymous, init(
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor) { subscriptions,
init(subscriptions,storageService,sessionsStore,authenticator,allowAnonymous, allowZeroByteClientId, authorizator,interceptor,null); storageService,
sessionsStore,
authenticator,
allowAnonymous,
false,
authorizator,
interceptor,
null);
} }
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthenticator authenticator, IAuthorizator authorizator, BrokerInterceptor interceptor) {
boolean allowAnonymous, init(
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) { subscriptions,
init(new ConnectionDescriptorStore(sessionsStore), subscriptions, storageService, sessionsStore, authenticator, storageService,
allowAnonymous, allowZeroByteClientId, authorizator, interceptor, serverPort); 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 * @param subscriptions
* clients subscriptions. * the subscription store where are stored all the existing clients subscriptions.
* @param storageService the persistent store to use for save/load of messages * @param storageService
* for QoS1 and QoS2 handling. * 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 sessionsStore
* @param authenticator the authenticator used in connect messages. * the clients sessions store, used to persist subscriptions.
* @param allowAnonymous true connection to clients without credentials. * @param authenticator
* @param allowZeroByteClientId true to allow clients connect without a clientid * the authenticator used in connect messages.
* @param authorizator used to apply ACL policies to publishes and subscriptions. * @param allowAnonymous
* @param interceptor to notify events to an intercept handler * 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, void init(ConnectionDescriptorStore connectionDescriptors, SubscriptionsStore subscriptions,
ISessionsStore sessionsStore, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator,
boolean allowAnonymous, BrokerInterceptor interceptor, String serverPort) {
boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
LOG.info("Initializing MQTT protocol processor..."); LOG.info("Initializing MQTT protocol processor...");
this.connectionDescriptors = connectionDescriptors; this.connectionDescriptors = connectionDescriptors;
this.subscriptionInCourse = new ConcurrentHashMap<>(); this.subscriptionInCourse = new ConcurrentHashMap<>();
@@ -209,15 +239,36 @@ public class ProtocolProcessor {
LOG.info("Initializing messages publisher..."); LOG.info("Initializing messages publisher...");
final PersistentQueueMessageSender messageSender = new PersistentQueueMessageSender(this.connectionDescriptors); 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..."); LOG.info("Initializing QoS publish handlers...");
this.qos0PublishHandler = new Qos0PublishHandler(m_authorizator, subscriptions, m_messagesStore, this.qos0PublishHandler = new Qos0PublishHandler(
m_interceptor, this.messagesPublisher); m_authorizator,
this.qos1PublishHandler = new Qos1PublishHandler(m_authorizator, subscriptions, m_messagesStore, subscriptions,
m_interceptor, this.connectionDescriptors, m_server_port, this.messagesPublisher); m_messagesStore,
this.qos2PublishHandler = new Qos2PublishHandler(m_authorizator, subscriptions, m_messagesStore, m_interceptor,
m_interceptor, this.connectionDescriptors, m_sessionsStore, m_server_port, this.messagesPublisher); 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..."); LOG.info("Initializing internal republisher...");
this.internalRepublisher = new InternalRepublisher(messageSender); this.internalRepublisher = new InternalRepublisher(messageSender);
@@ -228,8 +279,8 @@ public class ProtocolProcessor {
String clientId = payload.clientIdentifier(); String clientId = payload.clientIdentifier();
LOG.info("Processing CONNECT message. CId = {}, username = {}", clientId, payload.userName()); LOG.info("Processing CONNECT message. CId = {}, username = {}", clientId, payload.userName());
if (msg.variableHeader().version() != MqttVersion.MQTT_3_1.protocolLevel() && if (msg.variableHeader().version() != MqttVersion.MQTT_3_1.protocolLevel()
msg.variableHeader().version() != MqttVersion.MQTT_3_1_1.protocolLevel()) { && msg.variableHeader().version() != MqttVersion.MQTT_3_1_1.protocolLevel()) {
MqttConnAckMessage badProto = connAck(CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION); MqttConnAckMessage badProto = connAck(CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION);
LOG.error("The MQTT protocol version is not valid. CId = {}", clientId); LOG.error("The MQTT protocol version is not valid. CId = {}", clientId);
@@ -250,8 +301,10 @@ public class ProtocolProcessor {
// Generating client id. // Generating client id.
clientId = UUID.randomUUID().toString().replace("-", ""); clientId = UUID.randomUUID().toString().replace("-", "");
LOG.info("The client has connected with a server generated identifier. CId = {}, username = {}", LOG.info(
clientId, payload.userName()); "The client has connected with a server generated identifier. CId = {}, username = {}",
clientId,
payload.userName());
} }
if (!login(channel, msg, clientId)) { if (!login(channel, msg, clientId)) {
@@ -259,11 +312,13 @@ public class ProtocolProcessor {
return; 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); ConnectionDescriptor existing = this.connectionDescriptors.addConnection(descriptor);
if (existing != null) { if (existing != null) {
LOG.info("The client ID is being used in an existing connection. It will be closed. CId = {}", LOG.info("The client ID is being used in an existing connection. It will be closed. CId = {}", clientId);
clientId);
existing.abort(); existing.abort();
return; return;
} }
@@ -289,7 +344,8 @@ public class ProtocolProcessor {
channel.close(); channel.close();
return; return;
} }
final boolean success = descriptor.assignState(ConnectionState.MESSAGES_REPUBLISHED, ConnectionState.ESTABLISHED); final boolean success = descriptor
.assignState(ConnectionState.MESSAGES_REPUBLISHED, ConnectionState.ESTABLISHED);
if (!success) { if (!success) {
channel.close(); channel.close();
} }
@@ -306,7 +362,12 @@ public class ProtocolProcessor {
} }
private MqttConnAckMessage connAck(MqttConnectReturnCode returnCode, boolean sessionPresent) { 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); MqttConnAckVariableHeader mqttConnAckVariableHeader = new MqttConnAckVariableHeader(returnCode, sessionPresent);
return new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader); return new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader);
} }
@@ -318,20 +379,25 @@ public class ProtocolProcessor {
if (msg.variableHeader().hasPassword()) { if (msg.variableHeader().hasPassword()) {
pwd = msg.payload().password().getBytes(); pwd = msg.payload().password().getBytes();
} else if (!this.allowAnonymous) { } 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); clientId);
failedCredentials(channel); failedCredentials(channel);
return false; return false;
} }
if (!m_authenticator.checkValid(clientId, msg.payload().userName(), pwd)) { if (!m_authenticator.checkValid(clientId, msg.payload().userName(), pwd)) {
LOG.error("The authenticator has rejected the MQTT credentials. CId = {}, username = {}, password = {}.", LOG.error(
clientId, msg.payload().userName(), pwd); "The authenticator has rejected the MQTT credentials. CId = {}, username = {}, password = {}.",
clientId,
msg.payload().userName(),
pwd);
failedCredentials(channel); failedCredentials(channel);
return false; return false;
} }
NettyUtils.userName(channel, msg.payload().userName()); NettyUtils.userName(channel, msg.payload().userName());
} else if (!this.allowAnonymous) { } 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); clientId);
failedCredentials(channel); failedCredentials(channel);
return false; return false;
@@ -376,20 +442,33 @@ public class ProtocolProcessor {
int idleTime = Math.round(keepAlive * 1.5f); int idleTime = Math.round(keepAlive * 1.5f);
setIdleTime(channel.pipeline(), idleTime); setIdleTime(channel.pipeline(), idleTime);
LOG.info("The connection has been configured. CId = {}, keepAlive = {}, cleanSession = {}, idleTime = {}.", LOG.info(
clientId, keepAlive, msg.variableHeader().isCleanSession(), idleTime); "The connection has been configured. CId = {}, keepAlive = {}, cleanSession = {}, idleTime = {}.",
clientId,
keepAlive,
msg.variableHeader().isCleanSession(),
idleTime);
} }
private void storeWillMessage(MqttConnectMessage msg, final String clientId) { private void storeWillMessage(MqttConnectMessage msg, final String clientId) {
// Handle will flag // Handle will flag
if (msg.variableHeader().isWillFlag()) { if (msg.variableHeader().isWillFlag()) {
MqttQoS willQos = MqttQoS.valueOf(msg.variableHeader().willQos()); MqttQoS willQos = MqttQoS.valueOf(msg.variableHeader().willQos());
LOG.info("Configuring MQTT last will and testament. CId = {}, willQos = {}, willTopic = {}, willRetain = {}.", LOG.info(
clientId, willQos, msg.payload().willTopic(), msg.variableHeader().isWillRetain()); "Configuring MQTT last will and testament. "
+ "CId = {}, willQos = {}, willTopic = {}, willRetain = {}.",
clientId,
willQos,
msg.payload().willTopic(),
msg.variableHeader().isWillRetain());
byte[] willPayload = msg.payload().willMessage().getBytes(); byte[] willPayload = msg.payload().willMessage().getBytes();
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(willPayload.length).put(willPayload).flip(); ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(willPayload.length).put(willPayload).flip();
// save the will testament in the clientID store // 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); m_willStore.put(clientId, will);
LOG.info("MQTT last will and testament has been configured. CId = {}.", clientId); LOG.info("MQTT last will and testament has been configured. CId = {}.", clientId);
} }
@@ -415,7 +494,8 @@ public class ProtocolProcessor {
} }
private boolean republish(ConnectionDescriptor descriptor, MqttConnectMessage msg, ClientSession clientSession) { 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) { if (!success) {
return false; return false;
} }
@@ -443,7 +523,7 @@ public class ProtocolProcessor {
/** /**
* Republish QoS1 and QoS2 messages stored into the session for the clientID. * Republish QoS1 and QoS2 messages stored into the session for the clientID.
* */ */
private void republishStoredInSession(ClientSession clientSession) { private void republishStoredInSession(ClientSession clientSession) {
LOG.info("Republishing stored publish events. CId = {}.", clientSession.clientID); LOG.info("Republishing stored publish events. CId = {}.", clientSession.clientID);
BlockingQueue<StoredMessage> publishedEvents = clientSession.queue(); BlockingQueue<StoredMessage> publishedEvents = clientSession.queue();
@@ -474,15 +554,20 @@ public class ProtocolProcessor {
ByteBuf payload = msg.payload(); ByteBuf payload = msg.payload();
byte[] payloadContent = readBytesAndRewind(payload); byte[] payloadContent = readBytesAndRewind(payload);
IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(payloadContent, IMessagesStore.StoredMessage stored = new IMessagesStore.StoredMessage(
msg.fixedHeader().qosLevel(), msg.variableHeader().topicName()); payloadContent,
msg.fixedHeader().qosLevel(),
msg.variableHeader().topicName());
stored.setRetained(msg.fixedHeader().isRetain()); stored.setRetained(msg.fixedHeader().isRetain());
stored.setMessageID(msg.variableHeader().messageId()); stored.setMessageID(msg.variableHeader().messageId());
return stored; return stored;
} }
private static IMessagesStore.StoredMessage asStoredMessage(WillMessage will) { 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()); pub.setRetained(will.isRetained());
return pub; return pub;
} }
@@ -490,8 +575,12 @@ public class ProtocolProcessor {
public void processPublish(Channel channel, MqttPublishMessage msg) { public void processPublish(Channel channel, MqttPublishMessage msg) {
final MqttQoS qos = msg.fixedHeader().qosLevel(); final MqttQoS qos = msg.fixedHeader().qosLevel();
final String clientId = NettyUtils.clientID(channel); final String clientId = NettyUtils.clientID(channel);
LOG.info("Processing PUBLISH message. CId = {}, topic = {}, messageId = {}, qos = {}.", LOG.info(
clientId, msg.variableHeader().topicName(), msg.variableHeader().messageId(), qos); "Processing PUBLISH message. CId = {}, topic = {}, messageId = {}, qos = {}.",
clientId,
msg.variableHeader().topicName(),
msg.variableHeader().messageId(),
qos);
switch (qos) { switch (qos) {
case AT_MOST_ONCE: case AT_MOST_ONCE:
this.qos0PublishHandler.receivedPublishQos0(channel, msg); this.qos0PublishHandler.receivedPublishQos0(channel, msg);
@@ -508,16 +597,17 @@ public class ProtocolProcessor {
} }
/** /**
* Intended usage is only for embedded versions of the broker, where the hosting application want to use the * Intended usage is only for embedded versions of the broker, where the hosting application
* broker to send a publish message. * want to use the broker to send a publish message. Inspired by {@link #processPublish} but
* Inspired by {@link #processPublish} but with some changes to avoid security check, and the handshake phases * with some changes to avoid security check, and the handshake phases for Qos1 and Qos2. It
* for Qos1 and Qos2. * also doesn't notifyTopicPublished because using internally the owner should already know
* It also doesn't notifyTopicPublished because using internally the owner should already know where * where it's publishing.
* it's publishing.
* *
* @param msg the message to publish. * @param msg
* @param clientId the clientID * the message to publish.
* */ * @param clientId
* the clientID
*/
public void internalPublish(MqttPublishMessage msg, final String clientId) { public void internalPublish(MqttPublishMessage msg, final String clientId) {
final MqttQoS qos = msg.fixedHeader().qosLevel(); final MqttQoS qos = msg.fixedHeader().qosLevel();
final String topic = msg.variableHeader().topicName(); final String topic = msg.variableHeader().topicName();
@@ -581,11 +671,14 @@ public class ProtocolProcessor {
} }
/** /**
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored message and publish * Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored
* to all interested subscribers. * message and publish to all interested subscribers.
* @param channel the channel of the incoming message. *
* @param msg the decoded pubrel message. * @param channel
* */ * the channel of the incoming message.
* @param msg
* the decoded pubrel message.
*/
public void processPubRel(Channel channel, MqttMessage msg) { public void processPubRel(Channel channel, MqttMessage msg) {
this.qos2PublishHandler.processPubRel(channel, msg); this.qos2PublishHandler.processPubRel(channel, msg);
} }
@@ -629,8 +722,7 @@ public class ProtocolProcessor {
if (existingDescriptor.doesNotUseChannel(channel)) { if (existingDescriptor.doesNotUseChannel(channel)) {
// another client saved it's descriptor, exit // another client saved it's descriptor, exit
LOG.warn("Another client is using the connection descriptor. Closing connection. CId = {}.", LOG.warn("Another client is using the connection descriptor. Closing connection. CId = {}.", clientID);
clientID);
existingDescriptor.abort(); existingDescriptor.abort();
return; return;
} }
@@ -669,7 +761,8 @@ public class ProtocolProcessor {
} }
private boolean removeSubscriptions(ConnectionDescriptor descriptor, String clientID) { 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) { if (!success) {
return false; return false;
} }
@@ -683,7 +776,8 @@ public class ProtocolProcessor {
} }
private boolean dropStoredMessages(ConnectionDescriptor descriptor, String clientID) { 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) { if (!success) {
return false; return false;
} }
@@ -697,7 +791,8 @@ public class ProtocolProcessor {
} }
private boolean cleanWillMessageAndNotifyInterceptor(ConnectionDescriptor descriptor, String clientID) { 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) { if (!success) {
return false; return false;
} }
@@ -726,10 +821,13 @@ public class ProtocolProcessor {
} }
/** /**
* Remove the clientID from topic subscription, if not previously subscribed, * Remove the clientID from topic subscription, if not previously subscribed, doesn't reply any
* doesn't reply any error. * error.
* @param channel the channel of the incoming message. *
* @param msg the decoded unsubscribe message. * @param channel
* the channel of the incoming message.
* @param msg
* the decoded unsubscribe message.
*/ */
public void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg) { public void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg) {
List<String> topics = msg.payload().topics(); List<String> topics = msg.payload().topics();
@@ -743,8 +841,11 @@ public class ProtocolProcessor {
if (!validTopic) { if (!validTopic) {
// close the connection, not valid topicFilter is a protocol violation // close the connection, not valid topicFilter is a protocol violation
channel.close(); channel.close();
LOG.error("The topic filter is not valid. CId = {}, topics = {}, badTopicFilter = {}.", LOG.error(
clientID, topics, topic); "The topic filter is not valid. CId = {}, topics = {}, badTopicFilter = {}.",
clientID,
topics,
topic);
return; return;
} }
@@ -770,18 +871,25 @@ public class ProtocolProcessor {
LOG.info("Processing SUBSCRIBE message. CId = {}, messageId = {}.", clientID, messageID); LOG.info("Processing SUBSCRIBE message. CId = {}, messageId = {}.", clientID, messageID);
RunningSubscription executionKey = new RunningSubscription(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) { if (currentStatus != null) {
LOG.warn("The client sent another SUBSCRIBE message while this one was being processed. " + LOG.warn(
"CId = {}, messageId = {}.", clientID, messageID); "The client sent another SUBSCRIBE message while this one was being processed. "
+ "CId = {}, messageId = {}.",
clientID,
messageID);
return; return;
} }
String username = NettyUtils.userName(channel); String username = NettyUtils.userName(channel);
List<MqttTopicSubscription> ackTopics = doVerify(clientID, username, msg); List<MqttTopicSubscription> ackTopics = doVerify(clientID, username, msg);
MqttSubAckMessage ackMessage = doAckMessageFromValidateFilters(ackTopics, messageID); MqttSubAckMessage ackMessage = doAckMessageFromValidateFilters(ackTopics, messageID);
if (!this.subscriptionInCourse.replace(executionKey, SubscriptionState.VERIFIED, SubscriptionState.STORED)) { if (!this.subscriptionInCourse.replace(executionKey, SubscriptionState.VERIFIED, SubscriptionState.STORED)) {
LOG.warn("The client sent another SUBSCRIBE message while the topic filters were being verified. " + LOG.warn(
"CId = {}, messageId = {}.", clientID, messageID); "The client sent another SUBSCRIBE message while the topic filters were being verified. "
+ "CId = {}, messageId = {}.",
clientID,
messageID);
return; return;
} }
@@ -826,11 +934,14 @@ public class ProtocolProcessor {
} }
/** /**
* @param clientID the clientID * @param clientID
* @param username the username * the clientID
* @param msg the subscribe message to verify * @param username
* the username
* @param msg
* the subscribe message to verify
* @return the list of verified topics for the given subscribe message. * @return the list of verified topics for the given subscribe message.
* */ */
private List<MqttTopicSubscription> doVerify(String clientID, String username, MqttSubscribeMessage msg) { private List<MqttTopicSubscription> doVerify(String clientID, String username, MqttSubscribeMessage msg) {
ClientSession clientSession = m_sessionsStore.sessionForClient(clientID); ClientSession clientSession = m_sessionsStore.sessionForClient(clientID);
List<MqttTopicSubscription> ackTopics = new ArrayList<>(); List<MqttTopicSubscription> ackTopics = new ArrayList<>();
@@ -839,18 +950,32 @@ public class ProtocolProcessor {
for (MqttTopicSubscription req : msg.payload().topicSubscriptions()) { for (MqttTopicSubscription req : msg.payload().topicSubscriptions()) {
if (!m_authorizator.canRead(req.topicName(), username, clientSession.clientID)) { if (!m_authorizator.canRead(req.topicName(), username, clientSession.clientID)) {
// send SUBACK with 0x80, the user hasn't credentials to read the topic // 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 = {}.", LOG.error(
clientID, username, messageId, req.topicName()); "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)); ackTopics.add(new MqttTopicSubscription(req.topicName(), FAILURE));
} else { } else {
MqttQoS qos; MqttQoS qos;
if (SubscriptionsStore.validate(req.topicName())) { if (SubscriptionsStore.validate(req.topicName())) {
LOG.info("The client will be subscribed to the topic. CId = {}, username = {}, messageId = {}, topic = {}.", LOG.info(
clientID, username, messageId, req.topicName()); "The client will be subscribed to the topic. "
+ "CId = {}, username = {}, messageId = {}, topic = {}.",
clientID,
username,
messageId,
req.topicName());
qos = req.qualityOfService(); qos = req.qualityOfService();
} else { } else {
LOG.error("The topic filter is not valid. CId = {}, username = {}, messageId = {}, topic = {}.", LOG.error(
clientID, username, messageId, req.topicName()); "The topic filter is not valid. CId = {}, username = {}, messageId = {}, topic = {}.",
clientID,
username,
messageId,
req.topicName());
qos = FAILURE; qos = FAILURE;
} }
ackTopics.add(new MqttTopicSubscription(req.topicName(), qos)); ackTopics.add(new MqttTopicSubscription(req.topicName(), qos));
@@ -861,7 +986,7 @@ public class ProtocolProcessor {
/** /**
* Create the SUBACK response from a list of topicFilters * Create the SUBACK response from a list of topicFilters
* */ */
private MqttSubAckMessage doAckMessageFromValidateFilters(List<MqttTopicSubscription> topicFilters, int messageId) { private MqttSubAckMessage doAckMessageFromValidateFilters(List<MqttTopicSubscription> topicFilters, int messageId) {
List<Integer> grantedQoSLevels = new ArrayList<>(); List<Integer> grantedQoSLevels = new ArrayList<>();
for (MqttTopicSubscription req : topicFilters) { for (MqttTopicSubscription req : topicFilters) {
@@ -874,12 +999,15 @@ public class ProtocolProcessor {
} }
private void publishRetainedMessagesInSession(final Subscription newSubscription, String username) { 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()); newSubscription.getTopicFilter());
// scans retained messages to be published to the new subscription // scans retained messages to be published to the new subscription
// TODO this is ugly, it does a linear scan on potential big dataset // TODO this is ugly, it does a linear scan on potential big dataset
Collection<IMessagesStore.StoredMessage> messages = m_messagesStore.searchMatching(new IMatchingCondition() { Collection<IMessagesStore.StoredMessage> messages = m_messagesStore.searchMatching(new IMatchingCondition() {
@Override @Override
public boolean match(String key) { public boolean match(String key) {
return SubscriptionsStore.matchTopics(key, newSubscription.getTopicFilter()); return SubscriptionsStore.matchTopics(key, newSubscription.getTopicFilter());
@@ -887,8 +1015,11 @@ public class ProtocolProcessor {
}); });
if (!messages.isEmpty()) { if (!messages.isEmpty()) {
LOG.info("Publishing retained messages. CId = {}, topics = {}, messagesNo = {}.", LOG.info(
newSubscription.getClientId(), newSubscription.getTopicFilter(), messages.size()); "Publishing retained messages. CId = {}, topics = {}, messagesNo = {}.",
newSubscription.getClientId(),
newSubscription.getTopicFilter(),
messages.size());
} }
ClientSession targetSession = m_sessionsStore.sessionForClient(newSubscription.getClientId()); ClientSession targetSession = m_sessionsStore.sessionForClient(newSubscription.getClientId());
this.internalRepublisher.publishRetained(targetSession, messages); this.internalRepublisher.publishRetained(targetSession, messages);
@@ -908,7 +1039,12 @@ public class ProtocolProcessor {
} else { } else {
// recreate a publish from stored publish in queue // recreate a publish from stored publish in queue
boolean retained = m_messagesStore.getMessageByGuid(msg.getGuid()) != null; 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); channel.write(pubMsg);
} }
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -35,7 +36,6 @@ import io.moquette.spi.security.IAuthenticator;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.text.ParseException; import java.text.ParseException;
@@ -68,17 +68,23 @@ public class ProtocolProcessorBootstrapper {
/** /**
* Initialize the processing part of the broker. * Initialize the processing part of the broker.
* @param props the properties carrier where some props like port end host could be loaded. *
* For the full list check of configurable properties check moquette.conf file. * @param props
* @param embeddedObservers a list of callbacks to be notified of certain events inside the broker. * the properties carrier where some props like port end host could be loaded. For
* Could be empty list of null. * the full list check of configurable properties check moquette.conf file.
* @param authenticator an implementation of the authenticator to be used, if null load that specified in config * @param embeddedObservers
* and fallback on the default one (permit all). * a list of callbacks to be notified of certain events inside the broker. Could be
* @param authorizator an implementation of the authorizator to be used, if null load that specified in config * empty list of null.
* and fallback on the default one (permit all). * @param authenticator
* @param server the serber to init. * an implementation of the authenticator to be used, if null load that specified in
* config and fallback on the default one (permit all).
* @param authorizator
* an implementation of the authorizator to be used, if null load that specified in
* config and fallback on the default one (permit all).
* @param server
* the serber to init.
* @return the processor created for the broker. * @return the processor created for the broker.
* */ */
public ProtocolProcessor init(IConfig props, List<? extends InterceptHandler> embeddedObservers, public ProtocolProcessor init(IConfig props, List<? extends InterceptHandler> embeddedObservers,
IAuthenticator authenticator, IAuthorizator authorizator, Server server) { IAuthenticator authenticator, IAuthorizator authorizator, Server server) {
subscriptions = new SubscriptionsStore(); subscriptions = new SubscriptionsStore();
@@ -136,8 +142,11 @@ public class ProtocolProcessorBootstrapper {
LOG.info("Parsing ACL file. Path = {}.", aclFilePath); LOG.info("Parsing ACL file. Path = {}.", aclFilePath);
authorizator = ACLFileParser.parse(resourceLoader.loadResource(aclFilePath)); authorizator = ACLFileParser.parse(resourceLoader.loadResource(aclFilePath));
} catch (ParseException pex) { } catch (ParseException pex) {
LOG.error("Unable to parse ACL file. Path = {}, cause = {}, errorMessage = {}.", aclFilePath, LOG.error(
pex.getCause(), pex.getMessage()); "Unable to parse ACL file. Path = {}, cause = {}, errorMessage = {}.",
aclFilePath,
pex.getCause(),
pex.getMessage());
} }
} else { } else {
authorizator = new PermitAllAuthorizator(); authorizator = new PermitAllAuthorizator();
@@ -149,9 +158,21 @@ public class ProtocolProcessorBootstrapper {
connectionDescriptors = new ConnectionDescriptorStore(m_sessionsStore); connectionDescriptors = new ConnectionDescriptorStore(m_sessionsStore);
LOG.info("Initializing MQTT protocol processor..."); LOG.info("Initializing MQTT protocol processor...");
boolean allowAnonymous = Boolean.parseBoolean(props.getProperty(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, "true")); boolean allowAnonymous = Boolean
boolean allowZeroByteClientId = Boolean.parseBoolean(props.getProperty(BrokerConstants.ALLOW_ZERO_BYTE_CLIENT_ID_PROPERTY_NAME, "false")); .parseBoolean(props.getProperty(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, "true"));
m_processor.init(connectionDescriptors, subscriptions, messagesStore, m_sessionsStore, authenticator, allowAnonymous, allowZeroByteClientId, authorizator, m_interceptor, props.getProperty(BrokerConstants.PORT_PROPERTY_NAME)); boolean allowZeroByteClientId = Boolean
.parseBoolean(props.getProperty(BrokerConstants.ALLOW_ZERO_BYTE_CLIENT_ID_PROPERTY_NAME, "false"));
m_processor.init(
connectionDescriptors,
subscriptions,
messagesStore,
m_sessionsStore,
authenticator,
allowAnonymous,
allowZeroByteClientId,
authorizator,
m_interceptor,
props.getProperty(BrokerConstants.PORT_PROPERTY_NAME));
return m_processor; return m_processor;
} }
@@ -165,38 +186,58 @@ public class ProtocolProcessorBootstrapper {
// check if method getInstance exists // check if method getInstance exists
Method method = clazz.getMethod("getInstance", new Class[]{}); Method method = clazz.getMethod("getInstance", new Class[]{});
try { try {
LOG.info("Invoking getInstance() method. ClassName = {}, interfaceName = {}.", className, LOG.info(
"Invoking getInstance() method. ClassName = {}, interfaceName = {}.",
className,
iface.getName()); iface.getName());
instance = (T) method.invoke(null, new Object[]{}); instance = (T) method.invoke(null, new Object[]{});
} catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) { } catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) {
LOG.error( LOG.error(
"Unable to invoke getInstance() method. ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.", "Unable to invoke getInstance() method. "
className, iface.getName(), ex.getCause(), ex.getMessage()); + "ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
className,
iface.getName(),
ex.getCause(),
ex.getMessage());
return null; return null;
} }
} catch (NoSuchMethodException nsmex) { } catch (NoSuchMethodException nsmex) {
try { try {
// check if constructor with constructor arg class parameter // check if constructor with constructor arg class parameter
// exists // exists
LOG.info("Invoking constructor with {} argument. ClassName = {}, interfaceName = {}.", LOG.info(
constructorArgClass.getName(), className, iface.getName()); "Invoking constructor with {} argument. ClassName = {}, interfaceName = {}.",
constructorArgClass.getName(),
className,
iface.getName());
instance = this.getClass().getClassLoader().loadClass(className).asSubclass(iface) instance = this.getClass().getClassLoader().loadClass(className).asSubclass(iface)
.getConstructor(constructorArgClass).newInstance(props); .getConstructor(constructorArgClass).newInstance(props);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) { } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
LOG.warn( LOG.warn(
"Unable to invoke constructor with {} argument. ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.", "Unable to invoke constructor with {} argument. "
constructorArgClass.getName(), className, iface.getName(), ex.getCause(), ex.getMessage()); + "ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
constructorArgClass.getName(),
className,
iface.getName(),
ex.getCause(),
ex.getMessage());
return null; return null;
} catch (NoSuchMethodException | InvocationTargetException e) { } catch (NoSuchMethodException | InvocationTargetException e) {
try { try {
LOG.info("Invoking default constructor. ClassName = {}, interfaceName = {}.", className, LOG.info(
"Invoking default constructor. ClassName = {}, interfaceName = {}.",
className,
iface.getName()); iface.getName());
// fallback to default constructor // fallback to default constructor
instance = this.getClass().getClassLoader().loadClass(className).asSubclass(iface).newInstance(); instance = this.getClass().getClassLoader().loadClass(className).asSubclass(iface).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) { } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
LOG.error( LOG.error(
"Unable to invoke default constructor. ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.", "Unable to invoke default constructor. "
className, iface.getName(), ex.getCause(), ex.getMessage()); + "ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
className,
iface.getName(),
ex.getCause(),
ex.getMessage());
return null; return null;
} }
} }
@@ -205,8 +246,12 @@ public class ProtocolProcessorBootstrapper {
return null; return null;
} catch (SecurityException ex) { } catch (SecurityException ex) {
LOG.error( LOG.error(
"Unable to load class due to a security violation. ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.", "Unable to load class due to a security violation. "
className, iface.getName(), ex.getCause(), ex.getMessage()); + "ClassName = {}, interfaceName = {}, cause = {}, errorMessage = {}.",
className,
iface.getName(),
ex.getCause(),
ex.getMessage());
return null; return null;
} }
@@ -1,3 +1,4 @@
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.server.netty.NettyUtils; import io.moquette.server.netty.NettyUtils;
@@ -9,9 +10,7 @@ import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttPublishMessage; import io.netty.handler.codec.mqtt.MqttPublishMessage;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage; import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
class Qos0PublishHandler extends QosPublishHandler { class Qos0PublishHandler extends QosPublishHandler {
@@ -24,8 +23,7 @@ class Qos0PublishHandler extends QosPublishHandler {
private final MessagesPublisher publisher; private final MessagesPublisher publisher;
public Qos0PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions, public Qos0PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions,
IMessagesStore messagesStore, BrokerInterceptor interceptor, IMessagesStore messagesStore, BrokerInterceptor interceptor, MessagesPublisher messagesPublisher) {
MessagesPublisher messagesPublisher) {
super(authorizator); super(authorizator);
this.subscriptions = subscriptions; this.subscriptions = subscriptions;
this.m_messagesStore = messagesStore; this.m_messagesStore = messagesStore;
@@ -48,12 +46,20 @@ class Qos0PublishHandler extends QosPublishHandler {
final int messageID = msg.variableHeader().messageId(); final int messageID = msg.variableHeader().messageId();
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.", LOG.trace(
clientID, topic, messageID, DebugUtils.payload2Str(toStoreMsg.getMessage()), "Sending publish message to subscribers. "
+ "MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
clientID,
topic,
messageID,
DebugUtils.payload2Str(toStoreMsg.getMessage()),
subscriptions.dumpTree()); subscriptions.dumpTree());
} else { } else {
LOG.info("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.", clientID, LOG.info(
topic, messageID); "Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
clientID,
topic,
messageID);
} }
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic); List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
@@ -1,3 +1,4 @@
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.server.ConnectionDescriptorStore; import io.moquette.server.ConnectionDescriptorStore;
@@ -14,14 +15,13 @@ import io.netty.handler.codec.mqtt.MqttPubAckMessage;
import io.netty.handler.codec.mqtt.MqttPublishMessage; import io.netty.handler.codec.mqtt.MqttPublishMessage;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage; import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from; import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE; import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
class Qos1PublishHandler extends QosPublishHandler { class Qos1PublishHandler extends QosPublishHandler {
private static final Logger LOG = LoggerFactory.getLogger(Qos1PublishHandler.class); private static final Logger LOG = LoggerFactory.getLogger(Qos1PublishHandler.class);
private final SubscriptionsStore subscriptions; private final SubscriptionsStore subscriptions;
@@ -32,8 +32,7 @@ class Qos1PublishHandler extends QosPublishHandler {
public Qos1PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions, public Qos1PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions,
IMessagesStore messagesStore, BrokerInterceptor interceptor, IMessagesStore messagesStore, BrokerInterceptor interceptor,
ConnectionDescriptorStore connectionDescriptors, ConnectionDescriptorStore connectionDescriptors, String brokerPort, MessagesPublisher messagesPublisher) {
String brokerPort, MessagesPublisher messagesPublisher) {
super(authorizator); super(authorizator);
this.subscriptions = subscriptions; this.subscriptions = subscriptions;
this.m_messagesStore = messagesStore; this.m_messagesStore = messagesStore;
@@ -57,12 +56,20 @@ class Qos1PublishHandler extends QosPublishHandler {
toStoreMsg.setClientID(clientID); toStoreMsg.setClientID(clientID);
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.", LOG.trace(
clientID, topic, messageID, DebugUtils.payload2Str(toStoreMsg.getMessage()), "Sending publish message to subscribers. "
+ "MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
clientID,
topic,
messageID,
DebugUtils.payload2Str(toStoreMsg.getMessage()),
subscriptions.dumpTree()); subscriptions.dumpTree());
} else { } else {
LOG.info("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.", clientID, LOG.info(
topic, messageID); "Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
clientID,
topic,
messageID);
} }
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic); List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
@@ -94,11 +101,17 @@ class Qos1PublishHandler extends QosPublishHandler {
try { try {
if (connectionDescriptors == null) { if (connectionDescriptors == null) {
throw new RuntimeException("Internal bad error, found connectionDescriptors to null while it should be initialized, somewhere it's overwritten!!"); throw new RuntimeException(
"Internal bad error, found connectionDescriptors to null while it should be initialized, "
+ "somewhere it's overwritten!!");
} }
LOG.debug("clientIDs are {}", connectionDescriptors); LOG.debug("clientIDs are {}", connectionDescriptors);
if (!connectionDescriptors.isConnected(clientId)) { if (!connectionDescriptors.isConnected(clientId)) {
throw new RuntimeException(String.format("Can't find a ConnectionDescriptor for client %s in cache %s", clientId, connectionDescriptors)); throw new RuntimeException(
String.format(
"Can't find a ConnectionDescriptor for client %s in cache %s",
clientId,
connectionDescriptors));
} }
connectionDescriptors.sendMessage(pubAckMessage, messageID, clientId); connectionDescriptors.sendMessage(pubAckMessage, messageID, clientId);
} catch (Throwable t) { } catch (Throwable t) {
@@ -1,3 +1,4 @@
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.moquette.server.ConnectionDescriptorStore; import io.moquette.server.ConnectionDescriptorStore;
@@ -13,9 +14,7 @@ import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.*; import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage; import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
import static io.moquette.spi.impl.Utils.messageId; import static io.moquette.spi.impl.Utils.messageId;
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from; import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
@@ -34,8 +33,8 @@ class Qos2PublishHandler extends QosPublishHandler {
public Qos2PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions, public Qos2PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions,
IMessagesStore messagesStore, BrokerInterceptor interceptor, IMessagesStore messagesStore, BrokerInterceptor interceptor,
ConnectionDescriptorStore connectionDescriptors, ConnectionDescriptorStore connectionDescriptors, ISessionsStore sessionsStore, String brokerPort,
ISessionsStore sessionsStore, String brokerPort, MessagesPublisher messagesPublisher) { MessagesPublisher messagesPublisher) {
super(authorizator); super(authorizator);
this.subscriptions = subscriptions; this.subscriptions = subscriptions;
this.m_messagesStore = messagesStore; this.m_messagesStore = messagesStore;
@@ -58,13 +57,20 @@ class Qos2PublishHandler extends QosPublishHandler {
toStoreMsg.setClientID(clientID); toStoreMsg.setClientID(clientID);
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, " + LOG.trace(
"payload = {}, subscriptionTree = {}.", "Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, "
clientID, topic, messageID, DebugUtils.payload2Str(toStoreMsg.getMessage()), + "payload = {}, subscriptionTree = {}.",
clientID,
topic,
messageID,
DebugUtils.payload2Str(toStoreMsg.getMessage()),
subscriptions.dumpTree()); subscriptions.dumpTree());
} else { } else {
LOG.info("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.", LOG.info(
clientID, topic, messageID); "Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
clientID,
topic,
messageID);
} }
// QoS2 // QoS2
@@ -87,9 +93,9 @@ class Qos2PublishHandler extends QosPublishHandler {
} }
/** /**
* Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored message and publish * Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored
* to all interested subscribers. * message and publish to all interested subscribers.
* */ */
void processPubRel(Channel channel, MqttMessage msg) { void processPubRel(Channel channel, MqttMessage msg) {
String clientID = NettyUtils.clientID(channel); String clientID = NettyUtils.clientID(channel);
int messageID = messageId(msg); int messageID = messageId(msg);
@@ -100,12 +106,20 @@ class Qos2PublishHandler extends QosPublishHandler {
List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic); List<Subscription> topicMatchingSubscriptions = subscriptions.matches(topic);
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.", LOG.debug(
clientID, topic, messageID, DebugUtils.payload2Str(evt.getMessage()), "Sending publish message to subscribers. "
+ "MqttClientId = {}, topic = {}, messageId = {}, payload = {}, subscriptionTree = {}.",
clientID,
topic,
messageID,
DebugUtils.payload2Str(evt.getMessage()),
subscriptions.dumpTree()); subscriptions.dumpTree());
} else { } else {
LOG.info("Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.", clientID, LOG.info(
topic, messageID); "Sending publish message to subscribers. MqttClientId = {}, topic = {}, messageId = {}.",
clientID,
topic,
messageID);
} }
this.publisher.publish2Subscribers(evt, topicMatchingSubscriptions); this.publisher.publish2Subscribers(evt, topicMatchingSubscriptions);
@@ -120,7 +134,6 @@ class Qos2PublishHandler extends QosPublishHandler {
sendPubComp(clientID, messageID); sendPubComp(clientID, messageID);
} }
private void sendPubRec(String clientID, int messageID) { private void sendPubRec(String clientID, int messageID) {
LOG.debug("Sending PUBREC message. MqttClientId = {}, messageId = {}.", clientID, messageID); LOG.debug("Sending PUBREC message. MqttClientId = {}, messageId = {}.", clientID, messageID);
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBREC, false, AT_MOST_ONCE, false, 0); MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBREC, false, AT_MOST_ONCE, false, 0);
@@ -1,8 +1,8 @@
package io.moquette.spi.impl; package io.moquette.spi.impl;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import io.moquette.server.netty.NettyUtils; import io.moquette.server.netty.NettyUtils;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
import io.netty.channel.Channel; import io.netty.channel.Channel;
@@ -21,7 +21,9 @@ abstract class QosPublishHandler {
String clientID = NettyUtils.clientID(channel); String clientID = NettyUtils.clientID(channel);
String username = NettyUtils.userName(channel); String username = NettyUtils.userName(channel);
if (!m_authorizator.canWrite(topic, username, clientID)) { if (!m_authorizator.canWrite(topic, username, clientID)) {
LOG.error("The MQTT client is not authorized to publish on topic. MqttClientId = {}, topic = {}.", clientID, LOG.error(
"The MQTT client is not authorized to publish on topic. MqttClientId = {}, topic = {}.",
clientID,
topic); topic);
return true; return true;
} }
@@ -1,9 +1,9 @@
package io.moquette.spi.impl; package io.moquette.spi.impl;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttMessage; import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader; import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader;
import java.util.Map; import java.util.Map;
/** /**
@@ -13,29 +13,32 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.*; import java.io.*;
import java.text.ParseException; import java.text.ParseException;
/** /**
* Parses the acl configuration file. * Parses the acl configuration file. If a line starts with # it's comment. Blank lines are skipped.
* If a line starts with # it's comment. * The format is "topic [read|write|readwrite] {topic name}"
* Blank lines are skipped. The format is "topic [read|write|readwrite] {topic name}"
* *
* @author andrea * @author andrea
* */ */
public class ACLFileParser { public class ACLFileParser {
private static final Logger LOG = LoggerFactory.getLogger(ACLFileParser.class); private static final Logger LOG = LoggerFactory.getLogger(ACLFileParser.class);
/** /**
* Parse the configuration from file. * Parse the configuration from file.
* @param file to parse *
* @param file
* to parse
* @return the collector of authorizations form reader passed into. * @return the collector of authorizations form reader passed into.
* @throws ParseException if the format is not compliant. * @throws ParseException
* if the format is not compliant.
*/ */
public static AuthorizationsCollector parse(File file) throws ParseException { public static AuthorizationsCollector parse(File file) throws ParseException {
if (file == null) { if (file == null) {
@@ -43,23 +46,33 @@ public class ACLFileParser {
return AuthorizationsCollector.emptyImmutableCollector(); return AuthorizationsCollector.emptyImmutableCollector();
} }
if (!file.exists()) { if (!file.exists()) {
LOG.warn(String.format("parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); LOG.warn(
String.format(
"parsing not existing file %s, so fallback on default configuration!",
file.getAbsolutePath()));
return AuthorizationsCollector.emptyImmutableCollector(); return AuthorizationsCollector.emptyImmutableCollector();
} }
try { try {
FileReader reader = new FileReader(file); FileReader reader = new FileReader(file);
return parse(reader); return parse(reader);
} catch (FileNotFoundException fex) { } catch (FileNotFoundException fex) {
LOG.warn(String.format("parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); LOG.warn(
String.format(
"parsing not existing file %s, so fallback on default configuration!",
file.getAbsolutePath()),
fex);
return AuthorizationsCollector.emptyImmutableCollector(); return AuthorizationsCollector.emptyImmutableCollector();
} }
} }
/** /**
* Parse the ACL configuration file * Parse the ACL configuration file
* @param reader to parse *
* @param reader
* to parse
* @return the collector of authorizations form reader passed into. * @return the collector of authorizations form reader passed into.
* @throws ParseException if the format is not compliant. * @throws ParseException
* if the format is not compliant.
*/ */
public static AuthorizationsCollector parse(Reader reader) throws ParseException { public static AuthorizationsCollector parse(Reader reader) throws ParseException {
if (reader == null) { if (reader == null) {
@@ -1,3 +1,4 @@
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import io.moquette.spi.security.IAuthenticator; import io.moquette.spi.security.IAuthenticator;
@@ -6,6 +7,7 @@ import io.moquette.spi.security.IAuthenticator;
* Created by andrea on 8/23/14. * Created by andrea on 8/23/14.
*/ */
public class AcceptAllAuthenticator implements IAuthenticator { public class AcceptAllAuthenticator implements IAuthenticator {
public boolean checkValid(String clientId, String username, byte[] password) { public boolean checkValid(String clientId, String username, byte[] password) {
return true; return true;
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import static io.moquette.spi.impl.security.Authorization.Permission.READWRITE; import static io.moquette.spi.impl.security.Authorization.Permission.READWRITE;
@@ -23,12 +24,13 @@ import static io.moquette.spi.impl.security.Authorization.Permission.READWRITE;
* @author andrea * @author andrea
*/ */
public class Authorization { public class Authorization {
protected final String topic; protected final String topic;
protected final Permission permission; protected final Permission permission;
/** /**
* Access rights * Access rights
* */ */
enum Permission { enum Permission {
READ, WRITE, READWRITE READ, WRITE, READWRITE
} }
@@ -48,13 +50,17 @@ public class Authorization {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
Authorization that = (Authorization) o; Authorization that = (Authorization) o;
if (permission != that.permission) return false; if (permission != that.permission)
if (!topic.equals(that.topic)) return false; return false;
if (!topic.equals(that.topic))
return false;
return true; return true;
} }
@@ -13,19 +13,19 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore; import io.moquette.spi.impl.subscriptions.SubscriptionsStore;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.text.ParseException; import java.text.ParseException;
import java.util.*; import java.util.*;
/** /**
* Used by the ACLFileParser to push all authorizations it finds. * Used by the ACLFileParser to push all authorizations it finds. ACLAuthorizator uses it in read
* ACLAuthorizator uses it in read mode to check it topics matches the ACLs. * mode to check it topics matches the ACLs.
* *
* Not thread safe. * Not thread safe.
* *
@@ -57,7 +57,8 @@ class AuthorizationsCollector implements IAuthorizator {
return; return;
} }
if (m_parsingUsersSpecificSection) { if (m_parsingUsersSpecificSection) {
//TODO in java 8 switch to m_userAuthorizations.putIfAbsent(m_currentUser, new ArrayList()); // TODO in java 8 switch to m_userAuthorizations.putIfAbsent(m_currentUser, new
// ArrayList());
if (!m_userAuthorizations.containsKey(m_currentUser)) { if (!m_userAuthorizations.containsKey(m_currentUser)) {
m_userAuthorizations.put(m_currentUser, new ArrayList<Authorization>()); m_userAuthorizations.put(m_currentUser, new ArrayList<Authorization>());
} }
@@ -1,3 +1,4 @@
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -6,14 +7,12 @@ import io.moquette.spi.security.IAuthenticator;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.sql.*; import java.sql.*;
/** /**
* Load user credentials from a SQL database. * Load user credentials from a SQL database. sql driver must be provided at runtime
* sql driver must be provided at runtime
* *
* @author mackristof * @author mackristof
*/ */
@@ -25,21 +24,25 @@ public class DBAuthenticator implements IAuthenticator {
private final MessageDigest messageDigest; private final MessageDigest messageDigest;
private final PreparedStatement preparedStatement; private final PreparedStatement preparedStatement;
public DBAuthenticator(IConfig conf) { public DBAuthenticator(IConfig conf) {
this(conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DRIVER, ""), this(
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DRIVER, ""),
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_URL, ""), conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_URL, ""),
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_QUERY, ""), conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_QUERY, ""),
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DIGEST, "")); conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DIGEST, ""));
} }
/** provide authenticator from SQL database /**
* @param driver : jdbc driver class like : "org.postgresql.Driver" * provide authenticator from SQL database
* @param jdbcUrl : jdbc url like : "jdbc:postgresql://host:port/dbname" *
* @param sqlQuery : sql query like : "SELECT PASSWORD FROM USER WHERE LOGIN=?" * @param driver
* @param digestMethod : password encoding algorithm : "MD5", "SHA-1", "SHA-256" * : jdbc driver class like : "org.postgresql.Driver"
* @param jdbcUrl
* : jdbc url like : "jdbc:postgresql://host:port/dbname"
* @param sqlQuery
* : sql query like : "SELECT PASSWORD FROM USER WHERE LOGIN=?"
* @param digestMethod
* : password encoding algorithm : "MD5", "SHA-1", "SHA-256"
*/ */
public DBAuthenticator(String driver, String jdbcUrl, String sqlQuery, String digestMethod) { public DBAuthenticator(String driver, String jdbcUrl, String sqlQuery, String digestMethod) {
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
@@ -21,6 +22,7 @@ import io.moquette.spi.security.IAuthorizator;
* @author andrea * @author andrea
*/ */
public class DenyAllAuthorizator implements IAuthorizator { public class DenyAllAuthorizator implements IAuthorizator {
@Override @Override
public boolean canWrite(String topic, String user, String client) { public boolean canWrite(String topic, String user, String client) {
return true; return true;
@@ -13,19 +13,23 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import io.moquette.server.config.FileResourceLoader; import io.moquette.server.config.FileResourceLoader;
/** /**
* Load user credentials from a text file. * Load user credentials from a text file. Each line of the file is formatted as
* Each line of the file is formatted as "[username]:[sha256(password)]". The username mustn't contains : char. * "[username]:[sha256(password)]". The username mustn't contains : char.
* *
* To encode your password from command line on Linux systems, you could use: * To encode your password from command line on Linux systems, you could use:
*
* <pre> * <pre>
* echo -n "yourpassword" | sha256sum * echo -n "yourpassword" | sha256sum
* </pre> * </pre>
* NB -n is important because echo append a newline by default at the of string. -n avoid this behaviour. *
* NB -n is important because echo append a newline by default at the of string. -n avoid this
* behaviour.
* *
* @author andrea * @author andrea
* @deprecated user {@link ResourceAuthenticator} instead * @deprecated user {@link ResourceAuthenticator} instead
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
@@ -21,6 +22,7 @@ import io.moquette.spi.security.IAuthorizator;
* @author andrea * @author andrea
*/ */
public class PermitAllAuthorizator implements IAuthorizator { public class PermitAllAuthorizator implements IAuthorizator {
@Override @Override
public boolean canWrite(String topic, String user, String client) { public boolean canWrite(String topic, String user, String client) {
return true; return true;
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.security; package io.moquette.spi.impl.security;
import io.moquette.server.config.IResourceLoader; import io.moquette.server.config.IResourceLoader;
@@ -20,7 +21,6 @@ import io.moquette.spi.security.IAuthenticator;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
@@ -31,14 +31,17 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* Load user credentials from a text resource. * Load user credentials from a text resource. Each line of the file is formatted as
* Each line of the file is formatted as "[username]:[sha256(password)]". The username mustn't contains : char. * "[username]:[sha256(password)]". The username mustn't contains : char.
* *
* To encode your password from command line on Linux systems, you could use: * To encode your password from command line on Linux systems, you could use:
*
* <pre> * <pre>
* echo -n "yourpassword" | sha256sum * echo -n "yourpassword" | sha256sum
* </pre> * </pre>
* NB -n is important because echo append a newline by default at the of string. -n avoid this behaviour. *
* NB -n is important because echo append a newline by default at the of string. -n avoid this
* behaviour.
* *
* @author andrea * @author andrea
*/ */
@@ -63,16 +66,15 @@ public class ResourceAuthenticator implements IAuthenticator {
reader = resourceLoader.loadResource(resourceName); reader = resourceLoader.loadResource(resourceName);
if (reader == null) { if (reader == null) {
LOG.warn(String.format("Parsing not existing %s %s", resourceLoader.getName(), resourceName)); LOG.warn(String.format("Parsing not existing %s %s", resourceLoader.getName(), resourceName));
} } else {
else {
parse(reader); parse(reader);
} }
} } catch (IResourceLoader.ResourceIsDirectoryException e) {
catch (IResourceLoader.ResourceIsDirectoryException e) {
LOG.warn(String.format("Trying to parse directory %s", resourceName)); LOG.warn(String.format("Trying to parse directory %s", resourceName));
} } catch (ParseException pex) {
catch (ParseException pex) { LOG.warn(
LOG.warn(String.format("Format error in parsing password %s %s", resourceLoader.getName(), resourceName), pex); String.format("Format error in parsing password %s %s", resourceLoader.getName(), resourceName),
pex);
} }
} }
@@ -13,16 +13,15 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISessionsStore.ClientTopicCouple;
import io.netty.handler.codec.mqtt.MqttQoS; import io.netty.handler.codec.mqtt.MqttQoS;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Maintain the information about which Topic a certain ClientID is subscribed * Maintain the information about which Topic a certain ClientID is subscribed and at which QoS
* and at which QoS
* *
* *
* @author andrea * @author andrea
@@ -67,14 +66,16 @@ public final class Subscription implements Serializable {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o)
if (o == null || getClass() != o.getClass()) return false; return true;
if (o == null || getClass() != o.getClass())
return false;
Subscription that = (Subscription) o; Subscription that = (Subscription) o;
if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) return false; if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null)
return false;
return !(topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null); return !(topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null);
} }
@Override @Override
@@ -86,8 +87,12 @@ public final class Subscription implements Serializable {
@Override @Override
public String toString() { public String toString() {
return String.format("[filter:%s, cliID: %s, qos: %s, active: %s]", this.topicFilter, this.clientId, return String.format(
this.requestedQos, this.active); "[filter:%s, cliID: %s, qos: %s, active: %s]",
this.topicFilter,
this.clientId,
this.requestedQos,
this.active);
} }
@Override @Override
@@ -13,13 +13,13 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISessionsStore.ClientTopicCouple;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.text.ParseException; import java.text.ParseException;
import java.util.*; import java.util.*;
import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingDeque;
@@ -33,6 +33,7 @@ import java.util.concurrent.atomic.AtomicReference;
public class SubscriptionsStore { public class SubscriptionsStore {
public static class NodeCouple { public static class NodeCouple {
final TreeNode root; final TreeNode root;
final TreeNode createdNode; final TreeNode createdNode;
@@ -44,21 +45,27 @@ public class SubscriptionsStore {
/** /**
* Check if the topic filter of the subscription is well formed * Check if the topic filter of the subscription is well formed
* @param topicFilter the filter to validate *
* @param topicFilter
* the filter to validate
* @return true if it's correct. * @return true if it's correct.
* */ */
public static boolean validate(String topicFilter) { public static boolean validate(String topicFilter) {
try { try {
parseTopic(topicFilter); parseTopic(topicFilter);
return true; return true;
} catch (ParseException pex) { } catch (ParseException pex) {
LOG.warn("The topic filter is malformed. TopicFilter = {}, cause = {}, errorMessage = {}.", topicFilter, LOG.warn(
pex.getCause(), pex.getMessage()); "The topic filter is malformed. TopicFilter = {}, cause = {}, errorMessage = {}.",
topicFilter,
pex.getCause(),
pex.getMessage());
return false; return false;
} }
} }
public interface IVisitor<T> { public interface IVisitor<T> {
void visit(TreeNode node, int deep); void visit(TreeNode node, int deep);
T getResult(); T getResult();
@@ -76,7 +83,8 @@ public class SubscriptionsStore {
subScriptionsStr += indentTabs + couple.toString() + "\n"; subScriptionsStr += indentTabs + couple.toString() + "\n";
} }
s += node.getToken() == null ? "" : node.getToken().toString(); s += node.getToken() == null ? "" : node.getToken().toString();
s += "\n" + (node.m_subscriptions.isEmpty() ? indentTabs : "") + subScriptionsStr /*+ "\n"*/; s += "\n" + (node.m_subscriptions.isEmpty() ? indentTabs : "")
+ subScriptionsStr /* + "\n" */;
} }
private String indentTabs(int deep) { private String indentTabs(int deep) {
@@ -99,9 +107,11 @@ public class SubscriptionsStore {
private volatile ISessionsStore m_sessionsStore; private volatile ISessionsStore m_sessionsStore;
/** /**
* Initialize the subscription tree with the list of subscriptions. * Initialize the subscription tree with the list of subscriptions. Maintained for compatibility
* Maintained for compatibility reasons. * reasons.
* @param sessionsStore to be used as backing store from the subscription store. *
* @param sessionsStore
* to be used as backing store from the subscription store.
*/ */
public void init(ISessionsStore sessionsStore) { public void init(ISessionsStore sessionsStore) {
LOG.info("Initializing subscriptions store..."); LOG.info("Initializing subscriptions store...");
@@ -113,7 +123,10 @@ public class SubscriptionsStore {
} }
for (ClientTopicCouple clientTopic : subscriptions) { for (ClientTopicCouple clientTopic : subscriptions) {
LOG.info("Re-subscribing client to topic. ClientId = {}, topicFilter = {}.", clientTopic.clientID, clientTopic.topicFilter); LOG.info(
"Re-subscribing client to topic. ClientId = {}, topicFilter = {}.",
clientTopic.clientID,
clientTopic.topicFilter);
add(clientTopic); add(clientTopic);
} }
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
@@ -123,7 +136,8 @@ public class SubscriptionsStore {
public void add(ClientTopicCouple newSubscription) { public void add(ClientTopicCouple newSubscription) {
/* /*
* The topic filters have already been validated at the ProtocolProcessor. We can assume they are valid. * The topic filters have already been validated at the ProtocolProcessor. We can assume
* they are valid.
*/ */
TreeNode oldRoot; TreeNode oldRoot;
NodeCouple couple; NodeCouple couple;
@@ -136,14 +150,16 @@ public class SubscriptionsStore {
LOG.debug("A subscription has been added. Root = {}, oldRoot = {}.", couple.root, oldRoot); LOG.debug("A subscription has been added. Root = {}, oldRoot = {}.", couple.root, oldRoot);
} }
protected NodeCouple recreatePath(String topic, final TreeNode oldRoot) { protected NodeCouple recreatePath(String topic, final TreeNode oldRoot) {
List<Token> tokens; List<Token> tokens;
try { try {
tokens = parseTopic(topic); tokens = parseTopic(topic);
} catch (ParseException ex) { } catch (ParseException ex) {
// TODO handle the parse exception // TODO handle the parse exception
LOG.error("The topic is malformed. Topic = {}, cause = {}, errorMessage = {}.", topic, ex.getCause(), LOG.error(
"The topic is malformed. Topic = {}, cause = {}, errorMessage = {}.",
topic,
ex.getCause(),
ex.getMessage()); ex.getMessage());
throw new IllegalArgumentException(ex.getMessage()); throw new IllegalArgumentException(ex.getMessage());
} }
@@ -174,7 +190,8 @@ public class SubscriptionsStore {
public void removeSubscription(String topic, String clientID) { public void removeSubscription(String topic, String clientID) {
/* /*
* The topic filters have already been validated at the ProtocolProcessor. We can assume they are valid. * The topic filters have already been validated at the ProtocolProcessor. We can assume
* they are valid.
*/ */
TreeNode oldRoot; TreeNode oldRoot;
NodeCouple couple; NodeCouple couple;
@@ -188,9 +205,11 @@ public class SubscriptionsStore {
} }
/** /**
* Visit the topics tree to remove matching subscriptions with clientID. * Visit the topics tree to remove matching subscriptions with clientID. It's a mutating
* It's a mutating structure operation so create a new subscription tree (partial or total). * structure operation so create a new subscription tree (partial or total).
* @param clientID the client ID to remove. *
* @param clientID
* the client ID to remove.
*/ */
public void removeForClient(String clientID) { public void removeForClient(String clientID) {
TreeNode oldRoot; TreeNode oldRoot;
@@ -202,13 +221,13 @@ public class SubscriptionsStore {
} while (!subscriptions.compareAndSet(oldRoot, newRoot)); } while (!subscriptions.compareAndSet(oldRoot, newRoot));
} }
/** /**
* Given a topic string return the clients subscriptions that matches it. * Given a topic string return the clients subscriptions that matches it. Topic string can't
* Topic string can't contain character # and + because they are reserved to * contain character # and + because they are reserved to listeners subscriptions, and not topic
* listeners subscriptions, and not topic publishing. * publishing.
* *
* @param topic to use fo searching matching subscriptions. * @param topic
* to use fo searching matching subscriptions.
* @return the list of matching subscriptions, or empty if not matching. * @return the list of matching subscriptions, or empty if not matching.
*/ */
public List<Subscription> matches(String topic) { public List<Subscription> matches(String topic) {
@@ -217,7 +236,11 @@ public class SubscriptionsStore {
tokens = parseTopic(topic); tokens = parseTopic(topic);
} catch (ParseException ex) { } catch (ParseException ex) {
// TODO handle the parse exception // TODO handle the parse exception
LOG.warn("The topic is malformed. Topic = {}, cause = {}, errorMessage = {}.", topic, ex.getCause(), ex.getMessage()); LOG.warn(
"The topic is malformed. Topic = {}, cause = {}, errorMessage = {}.",
topic,
ex.getCause(),
ex.getMessage());
return Collections.emptyList(); return Collections.emptyList();
} }
@@ -268,8 +291,11 @@ public class SubscriptionsStore {
/** /**
* Verify if the 2 topics matching respecting the rules of MQTT Appendix A * Verify if the 2 topics matching respecting the rules of MQTT Appendix A
* @param msgTopic the topic to match from the message *
* @param subscriptionTopic the topic filter of the subscription * @param msgTopic
* the topic to match from the message
* @param subscriptionTopic
* the topic filter of the subscription
* @return true if the two topics match. * @return true if the two topics match.
*/ */
// TODO reimplement with iterators or with queues // TODO reimplement with iterators or with queues
@@ -304,8 +330,12 @@ public class SubscriptionsStore {
return i == msgTokens.size(); return i == msgTokens.size();
} catch (ParseException ex) { } catch (ParseException ex) {
LOG.error( LOG.error(
"The message topic, the subscription topic or both are malformed. MsgTopic = {}, subscriptionTopic = {}, cause = {}, errorMessage = {}.", "The message topic, the subscription topic or both are malformed. "
msgTopic, subscriptionTopic, ex.getCause(), ex.getMessage()); + "MsgTopic = {}, subscriptionTopic = {}, cause = {}, errorMessage = {}.",
msgTopic,
subscriptionTopic,
ex.getCause(),
ex.getMessage());
throw new IllegalStateException(ex.getMessage()); throw new IllegalStateException(ex.getMessage());
} }
} }
@@ -330,13 +360,16 @@ public class SubscriptionsStore {
String s = splitted[i]; String s = splitted[i];
if (s.isEmpty()) { if (s.isEmpty()) {
// if (i != 0) { // if (i != 0) {
// throw new ParseException("Bad format of topic, expetec topic name between separators", i); // throw new ParseException("Bad format of topic, expetec topic name between
// separators", i);
// } // }
res.add(Token.EMPTY); res.add(Token.EMPTY);
} else if (s.equals("#")) { } else if (s.equals("#")) {
// check that multi is the last symbol // check that multi is the last symbol
if (i != splitted.length - 1) { if (i != splitted.length - 1) {
throw new ParseException("Bad format of topic, the multi symbol (#) has to be the last one after a separator", i); throw new ParseException(
"Bad format of topic, the multi symbol (#) has to be the last one after a separator",
i);
} }
res.add(Token.MULTI); res.add(Token.MULTI);
} else if (s.contains("#")) { } else if (s.contains("#")) {
@@ -13,11 +13,12 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
/** /**
* Internal use only class. * Internal use only class.
* */ */
public class Token { public class Token {
static final Token EMPTY = new Token(""); static final Token EMPTY = new Token("");
@@ -13,10 +13,10 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISessionsStore.ClientTopicCouple;
import java.util.*; import java.util.*;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
@@ -47,9 +47,8 @@ class TreeNode {
} }
/** /**
* Creates a shallow copy of the current node. * Creates a shallow copy of the current node. Copy the token and the children.
* Copy the token and the children. */
* */
TreeNode copy() { TreeNode copy() {
final TreeNode copy = new TreeNode(); final TreeNode copy = new TreeNode();
copy.m_children = new ArrayList<>(m_children); copy.m_children = new ArrayList<>(m_children);
@@ -59,8 +58,7 @@ class TreeNode {
} }
/** /**
* Search for children that has the specified token, if not found return * Search for children that has the specified token, if not found return null;
* null;
*/ */
TreeNode childWithToken(Token token) { TreeNode childWithToken(Token token) {
for (TreeNode child : m_children) { for (TreeNode child : m_children) {
@@ -131,7 +129,7 @@ class TreeNode {
/** /**
* Create a copied subtree rooted on this node but purged of clientID's subscriptions. * Create a copied subtree rooted on this node but purged of clientID's subscriptions.
* */ */
TreeNode removeClientSubscriptions(String clientID) { TreeNode removeClientSubscriptions(String clientID) {
// collect what to delete and then delete to avoid ConcurrentModification // collect what to delete and then delete to avoid ConcurrentModification
TreeNode newSubRoot = this.copy(); TreeNode newSubRoot = this.copy();
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.persistence; package io.moquette.spi.persistence;
import io.moquette.spi.IMatchingCondition; import io.moquette.spi.IMatchingCondition;
@@ -21,7 +22,6 @@ import io.moquette.spi.MessageGUID;
import org.mapdb.DB; import org.mapdb.DB;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
@@ -41,7 +41,6 @@ class MapDBMessagesStore implements IMessagesStore {
// maps guid to message, it's message store // maps guid to message, it's message store
private ConcurrentMap<MessageGUID, IMessagesStore.StoredMessage> m_persistentMessageStore; private ConcurrentMap<MessageGUID, IMessagesStore.StoredMessage> m_persistentMessageStore;
MapDBMessagesStore(DB db) { MapDBMessagesStore(DB db) {
m_db = db; m_db = db;
} }
@@ -83,10 +82,15 @@ class MapDBMessagesStore implements IMessagesStore {
assert storedMessage.getClientID() != null : "The message to be persisted must have a valid client ID"; assert storedMessage.getClientID() != null : "The message to be persisted must have a valid client ID";
MessageGUID guid = new MessageGUID(UUID.randomUUID().toString()); MessageGUID guid = new MessageGUID(UUID.randomUUID().toString());
storedMessage.setGuid(guid); storedMessage.setGuid(guid);
LOG.debug("Storing publish event. MqttClientId = {}, messageId = {}, guid = {}, topic = {}.", LOG.debug(
storedMessage.getClientID(), storedMessage.getMessageID(), guid, storedMessage.getTopic()); "Storing publish event. MqttClientId = {}, messageId = {}, guid = {}, topic = {}.",
storedMessage.getClientID(),
storedMessage.getMessageID(),
guid,
storedMessage.getTopic());
m_persistentMessageStore.put(guid, storedMessage); m_persistentMessageStore.put(guid, storedMessage);
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(MapDBSessionsStore.messageId2GuidsMapName(storedMessage.getClientID())); ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db
.getHashMap(MapDBSessionsStore.messageId2GuidsMapName(storedMessage.getClientID()));
messageIdToGuid.put(storedMessage.getMessageID(), guid); messageIdToGuid.put(storedMessage.getMessageID(), guid);
return guid; return guid;
} }
@@ -94,7 +98,8 @@ class MapDBMessagesStore implements IMessagesStore {
@Override @Override
public void dropMessagesInSession(String clientID) { public void dropMessagesInSession(String clientID) {
LOG.debug("Dropping stored messages. ClientId = {}.", clientID); LOG.debug("Dropping stored messages. ClientId = {}.", clientID);
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(MapDBSessionsStore.messageId2GuidsMapName(clientID)); ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db
.getHashMap(MapDBSessionsStore.messageId2GuidsMapName(clientID));
for (MessageGUID guid : messageIdToGuid.values()) { for (MessageGUID guid : messageIdToGuid.values()) {
removeStoredMessage(guid); removeStoredMessage(guid);
} }
@@ -105,8 +110,12 @@ class MapDBMessagesStore implements IMessagesStore {
// remove only the not retained and no more referenced // remove only the not retained and no more referenced
StoredMessage storedMessage = m_persistentMessageStore.get(guid); StoredMessage storedMessage = m_persistentMessageStore.get(guid);
if (!storedMessage.isRetained()) { if (!storedMessage.isRetained()) {
LOG.debug("Dropping stored message. ClientId = {}, messageId = {}, guid = {}, topic = {}.", LOG.debug(
storedMessage.getClientID(), storedMessage.getMessageID(), guid, storedMessage.getTopic()); "Dropping stored message. ClientId = {}, messageId = {}, guid = {}, topic = {}.",
storedMessage.getClientID(),
storedMessage.getMessageID(),
guid,
storedMessage.getTopic());
m_persistentMessageStore.remove(guid); m_persistentMessageStore.remove(guid);
} }
} }
@@ -23,14 +23,12 @@ import org.mapdb.DB;
import org.mapdb.DBMaker; import org.mapdb.DBMaker;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.Serializable; import java.io.Serializable;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static io.moquette.BrokerConstants.AUTOSAVE_INTERVAL_PROPERTY_NAME; import static io.moquette.BrokerConstants.AUTOSAVE_INTERVAL_PROPERTY_NAME;
import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME; import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME;
@@ -40,10 +38,11 @@ import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME;
public class MapDBPersistentStore { public class MapDBPersistentStore {
/** /**
* This is a DTO used to persist minimal status (clean session and activation status) of * This is a DTO used to persist minimal status (clean session and activation status) of a
* a session. * session.
* */ */
public static class PersistentSession implements Serializable { public static class PersistentSession implements Serializable {
private static final long serialVersionUID = 5052054783220481854L; private static final long serialVersionUID = 5052054783220481854L;
public final boolean cleanSession; public final boolean cleanSession;
@@ -69,8 +68,9 @@ public class MapDBPersistentStore {
/** /**
* Factory method to create message store backed by MapDB * Factory method to create message store backed by MapDB
*
* @return the message store instance. * @return the message store instance.
* */ */
public IMessagesStore messagesStore() { public IMessagesStore messagesStore() {
return m_messageStore; return m_messageStore;
} }
@@ -92,13 +92,20 @@ public class MapDBPersistentStore {
boolean fileNewlyCreated = tmpFile.createNewFile(); boolean fileNewlyCreated = tmpFile.createNewFile();
LOG.warn("Using {} MapDB store file. Path = {}.", fileNewlyCreated ? "fresh" : "existing", m_storePath); LOG.warn("Using {} MapDB store file. Path = {}.", fileNewlyCreated ? "fresh" : "existing", m_storePath);
} catch (IOException ex) { } catch (IOException ex) {
LOG.error("Unable to open MapDB store file. Path = {}, cause = {}, errorMessage = {}.", m_storePath, ex.getCause(), ex.getMessage()); LOG.error(
throw new RuntimeException("Can't create temp file for subscriptions storage [" + m_storePath + "]", ex); "Unable to open MapDB store file. Path = {}, cause = {}, errorMessage = {}.",
m_storePath,
ex.getCause(),
ex.getMessage());
throw new RuntimeException(
"Can't create temp file for subscriptions storage [" + m_storePath + "]",
ex);
} }
m_db = DBMaker.newFileDB(tmpFile).make(); m_db = DBMaker.newFileDB(tmpFile).make();
} }
LOG.info("Scheduling MapDB commit task..."); LOG.info("Scheduling MapDB commit task...");
m_scheduler.scheduleWithFixedDelay(new Runnable() { m_scheduler.scheduleWithFixedDelay(new Runnable() {
@Override @Override
public void run() { public void run() {
LOG.debug("Committing to MapDB..."); LOG.debug("Committing to MapDB...");
@@ -127,7 +134,8 @@ public class MapDBPersistentStore {
this.m_scheduler.shutdown(); this.m_scheduler.shutdown();
try { try {
m_scheduler.awaitTermination(10L, TimeUnit.SECONDS); m_scheduler.awaitTermination(10L, TimeUnit.SECONDS);
} catch (InterruptedException e) {} } catch (InterruptedException e) {
}
if (!m_scheduler.isTerminated()) { if (!m_scheduler.isTerminated()) {
LOG.warn("Forcing shutdown of MapDB commit tasks..."); LOG.warn("Forcing shutdown of MapDB commit tasks...");
m_scheduler.shutdown(); m_scheduler.shutdown();
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.persistence; package io.moquette.spi.persistence;
import io.moquette.spi.ClientSession; import io.moquette.spi.ClientSession;
@@ -25,7 +26,6 @@ import io.moquette.spi.persistence.MapDBPersistentStore.PersistentSession;
import org.mapdb.DB; import org.mapdb.DB;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*; import java.util.*;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -66,14 +66,18 @@ class MapDBSessionsStore implements ISessionsStore {
@Override @Override
public void addNewSubscription(Subscription newSubscription) { public void addNewSubscription(Subscription newSubscription) {
LOG.info("Adding new subscription. CId= {}, topics = {}.", newSubscription.getClientId(), LOG.info(
"Adding new subscription. CId= {}, topics = {}.",
newSubscription.getClientId(),
newSubscription.getTopicFilter()); newSubscription.getTopicFilter());
final String clientID = newSubscription.getClientId(); final String clientID = newSubscription.getClientId();
m_db.getHashMap("subscriptions_" + clientID).put(newSubscription.getTopicFilter(), newSubscription); m_db.getHashMap("subscriptions_" + clientID).put(newSubscription.getTopicFilter(), newSubscription);
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("The subscription has been added. CId= {}, topics = {}, clientSubscriptions = {}.", LOG.trace(
newSubscription.getClientId(), newSubscription.getTopicFilter(), "The subscription has been added. CId= {}, topics = {}, clientSubscriptions = {}.",
newSubscription.getClientId(),
newSubscription.getTopicFilter(),
m_db.getHashMap("subscriptions_" + clientID)); m_db.getHashMap("subscriptions_" + clientID));
} }
} }
@@ -86,8 +90,11 @@ class MapDBSessionsStore implements ISessionsStore {
} }
m_db.getHashMap("subscriptions_" + clientID).remove(topicFilter); m_db.getHashMap("subscriptions_" + clientID).remove(topicFilter);
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("The subscription has been removed. CId= {}, topics = {}, clientSubscriptions = {}.", LOG.debug(
clientID, topicFilter, m_db.getHashMap("subscriptions_" + clientID)); "The subscription has been removed. CId= {}, topics = {}, clientSubscriptions = {}.",
clientID,
topicFilter,
m_db.getHashMap("subscriptions_" + clientID));
} }
} }
@@ -96,7 +103,9 @@ class MapDBSessionsStore implements ISessionsStore {
LOG.info("Wiping subscriptions. CId= {}.", clientID); LOG.info("Wiping subscriptions. CId= {}.", clientID);
m_db.delete("subscriptions_" + clientID); m_db.delete("subscriptions_" + clientID);
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("The subscriptions have been removed. CId= {}, clientSubscriptions = {}.", clientID, LOG.debug(
"The subscriptions have been removed. CId= {}, clientSubscriptions = {}.",
clientID,
m_db.getHashMap("subscriptions_" + clientID)); m_db.getHashMap("subscriptions_" + clientID));
} }
} }
@@ -120,8 +129,7 @@ class MapDBSessionsStore implements ISessionsStore {
@Override @Override
public Subscription getSubscription(ClientTopicCouple couple) { public Subscription getSubscription(ClientTopicCouple couple) {
ConcurrentMap<String, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + couple.clientID); ConcurrentMap<String, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + couple.clientID);
LOG.info("Retrieving subscriptions. CId= {}, subscriptions = {}.", couple.clientID, LOG.info("Retrieving subscriptions. CId= {}, subscriptions = {}.", couple.clientID, clientSubscriptions);
clientSubscriptions);
return clientSubscriptions.get(couple.topicFilter); return clientSubscriptions.get(couple.topicFilter);
} }
@@ -147,7 +155,8 @@ class MapDBSessionsStore implements ISessionsStore {
if (m_persistentSessions.containsKey(clientID)) { if (m_persistentSessions.containsKey(clientID)) {
LOG.error( LOG.error(
"Unable to create a new session: the client ID is already in use. CId= {}, cleanSession = {}.", "Unable to create a new session: the client ID is already in use. CId= {}, cleanSession = {}.",
clientID, cleanSession); clientID,
cleanSession);
throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID); throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID);
} }
LOG.info("Creating new session. CId= {}, cleanSession = {}.", clientID, cleanSession); LOG.info("Creating new session. CId= {}, cleanSession = {}.", clientID, cleanSession);
@@ -169,7 +178,7 @@ class MapDBSessionsStore implements ISessionsStore {
@Override @Override
public Collection<ClientSession> getAllSessions() { public Collection<ClientSession> getAllSessions() {
Collection<ClientSession> result = new ArrayList<ClientSession>(); Collection<ClientSession> result = new ArrayList<>();
for (Map.Entry<String, PersistentSession> entry : m_persistentSessions.entrySet()) { for (Map.Entry<String, PersistentSession> entry : m_persistentSessions.entrySet()) {
result.add(new ClientSession(entry.getKey(), m_messagesStore, this, entry.getValue().cleanSession)); result.add(new ClientSession(entry.getKey(), m_messagesStore, this, entry.getValue().cleanSession));
} }
@@ -184,7 +193,7 @@ class MapDBSessionsStore implements ISessionsStore {
/** /**
* Return the next valid packetIdentifier for the given client session. * Return the next valid packetIdentifier for the given client session.
* */ */
@Override @Override
public int nextPacketID(String clientID) { public int nextPacketID(String clientID) {
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
@@ -268,7 +277,8 @@ class MapDBSessionsStore implements ISessionsStore {
inFlightForClient.remove(messageID); inFlightForClient.remove(messageID);
} }
Map<Integer, MessageGUID> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashMap<Integer, MessageGUID>()); Map<Integer, MessageGUID> messageIDs = Utils
.defaultGet(m_secondPhaseStore, clientID, new HashMap<Integer, MessageGUID>());
messageIDs.put(messageID, guid); messageIDs.put(messageID, guid);
m_secondPhaseStore.put(clientID, messageIDs); m_secondPhaseStore.put(clientID, messageIDs);
} }
@@ -278,7 +288,8 @@ class MapDBSessionsStore implements ISessionsStore {
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("Processing second phase ACK CId={}, messageId={}", clientID, messageID); LOG.debug("Processing second phase ACK CId={}, messageId={}", clientID, messageID);
} }
Map<Integer, MessageGUID> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, new HashMap<Integer, MessageGUID>()); Map<Integer, MessageGUID> messageIDs = Utils
.defaultGet(m_secondPhaseStore, clientID, new HashMap<Integer, MessageGUID>());
MessageGUID guid = messageIDs.remove(messageID); MessageGUID guid = messageIDs.remove(messageID);
m_secondPhaseStore.put(clientID, messageIDs); m_secondPhaseStore.put(clientID, messageIDs);
return guid; return guid;
@@ -307,8 +318,7 @@ class MapDBSessionsStore implements ISessionsStore {
} }
MessageGUID guid = clientEntries.get(messageID); MessageGUID guid = clientEntries.get(messageID);
if (guid == null) { if (guid == null) {
LOG.warn("The message ID does not have an associated GUID. CId= {}, messageId = {}.", clientID, LOG.warn("The message ID does not have an associated GUID. CId= {}, messageId = {}.", clientID, messageID);
messageID);
return null; return null;
} }
return m_messagesStore.getMessageByGuid(guid); return m_messagesStore.getMessageByGuid(guid);
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.security; package io.moquette.spi.security;
/** /**
@@ -13,14 +13,14 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.security; package io.moquette.spi.security;
/** /**
* ACL checker. * ACL checker.
* *
* Create an authorizator that matches topic names with same grammar of subscriptions. * Create an authorizator that matches topic names with same grammar of subscriptions. The # is
* The # is always a terminator and its the multilevel matcher. * always a terminator and its the multilevel matcher. The + sign is the single level matcher.
* The + sign is the single level matcher.
* *
* @author andrea * @author andrea
*/ */
@@ -28,11 +28,15 @@ public interface IAuthorizator {
/** /**
* Ask the implementation of the authorizator if the topic can be used in a publish. * Ask the implementation of the authorizator if the topic can be used in a publish.
* @param topic the topic to write to. *
* @param user the user * @param topic
* @param client the client * the topic to write to.
* @param user
* the user
* @param client
* the client
* @return true if the user from client can publish data on topic. * @return true if the user from client can publish data on topic.
* */ */
boolean canWrite(String topic, String user, String client); boolean canWrite(String topic, String user, String client);
boolean canRead(String topic, String user, String client); boolean canRead(String topic, String user, String client);
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.spi.security; package io.moquette.spi.security;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
+19 -17
View File
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette; package io.moquette;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
@@ -23,7 +24,6 @@ import io.netty.util.Attribute;
import io.netty.util.AttributeKey; import io.netty.util.AttributeKey;
import io.netty.util.AttributeMap; import io.netty.util.AttributeMap;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
/** /**
@@ -66,8 +66,7 @@ public class Utils {
} }
/** /**
* Decode the variable remaining length as defined in MQTT v3.1 specification * Decode the variable remaining length as defined in MQTT v3.1 specification (section 2.1).
* (section 2.1).
* *
* @return the decoded length or -1 if needed more data to decode the length field. * @return the decoded length or -1 if needed more data to decode the length field.
*/ */
@@ -87,11 +86,10 @@ public class Utils {
} }
/** /**
* Encode the value in the format defined in specification as variable length * Encode the value in the format defined in specification as variable length array.
* array.
* *
* @throws IllegalArgumentException if the value is not in the specification bounds * @throws IllegalArgumentException
* [0..268435455]. * if the value is not in the specification bounds [0..268435455].
*/ */
static ByteBuf encodeRemainingLength(int value) throws CorruptedFrameException { static ByteBuf encodeRemainingLength(int value) throws CorruptedFrameException {
if (value > MAX_LENGTH_LIMIT || value < 0) { if (value > MAX_LENGTH_LIMIT || value < 0) {
@@ -113,8 +111,8 @@ public class Utils {
} }
/** /**
* Load a string from the given buffer, reading first the two bytes of len * Load a string from the given buffer, reading first the two bytes of len and then the UTF-8
* and then the UTF-8 bytes of the string. * bytes of the string.
* *
* @return the decoded string or null if NEED_DATA * @return the decoded string or null if NEED_DATA
*/ */
@@ -123,8 +121,9 @@ public class Utils {
} }
/** /**
* Read a byte array from the buffer, use two bytes as length information followed by length bytes. * Read a byte array from the buffer, use two bytes as length information followed by length
* */ * bytes.
*/
static byte[] readFixedLengthContent(ByteBuf in) throws UnsupportedEncodingException { static byte[] readFixedLengthContent(ByteBuf in) throws UnsupportedEncodingException {
if (in.readableBytes() < 2) { if (in.readableBytes() < 2) {
return null; return null;
@@ -140,8 +139,7 @@ public class Utils {
} }
/** /**
* Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded * Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded string content.
* string content.
*/ */
public static ByteBuf encodeString(String str) { public static ByteBuf encodeString(String str) {
byte[] raw; byte[] raw;
@@ -170,10 +168,14 @@ public class Utils {
* Return the number of bytes to encode the given remaining length value * Return the number of bytes to encode the given remaining length value
*/ */
static int numBytesToEncode(int len) { static int numBytesToEncode(int len) {
if (0 <= len && len <= 127) return 1; if (0 <= len && len <= 127)
if (128 <= len && len <= 16383) return 2; return 1;
if (16384 <= len && len <= 2097151) return 3; if (128 <= len && len <= 16383)
if (2097152 <= len && len <= 268435455) return 4; return 2;
if (16384 <= len && len <= 2097151)
return 3;
if (2097152 <= len && len <= 268435455)
return 4;
throw new IllegalArgumentException("value shoul be in the range [0..268435455]"); throw new IllegalArgumentException("value shoul be in the range [0..268435455]");
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -22,11 +23,9 @@ import io.moquette.spi.security.IAuthenticator;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Properties; import java.util.Properties;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
@@ -34,6 +33,7 @@ import static org.junit.Assert.*;
* @author luca <[email protected]> * @author luca <[email protected]>
*/ */
public class ConfigurationClassLoaderTest implements IAuthenticator, IAuthorizator { public class ConfigurationClassLoaderTest implements IAuthenticator, IAuthorizator {
Server m_server; Server m_server;
IConfig m_config; IConfig m_config;
@@ -43,7 +43,6 @@ public class ConfigurationClassLoaderTest implements IAuthenticator, IAuthorizat
m_server.startServer(m_config); m_server.startServer(m_config);
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
m_server.stopServer(); m_server.stopServer();
@@ -13,13 +13,12 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.server.config.IConfig; import io.moquette.server.config.IConfig;
import java.io.File; import java.io.File;
import java.util.Properties; import java.util.Properties;
import static io.moquette.BrokerConstants.DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME; import static io.moquette.BrokerConstants.DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME;
import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME; import static io.moquette.BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME;
import static io.moquette.BrokerConstants.PORT_PROPERTY_NAME; import static io.moquette.BrokerConstants.PORT_PROPERTY_NAME;
@@ -31,6 +30,7 @@ import static org.junit.Assert.assertFalse;
* Created by andrea on 4/7/15. * Created by andrea on 4/7/15.
*/ */
public class IntegrationUtils { public class IntegrationUtils {
static String localMapDBPath() { static String localMapDBPath() {
String currentDir = System.getProperty("user.dir"); String currentDir = System.getProperty("user.dir");
return currentDir + File.separator + DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME; return currentDir + File.separator + DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME;
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import java.io.IOException; import java.io.IOException;
@@ -68,8 +69,7 @@ public class MQTTWebSocket {
ByteBuffer msg = ByteBuffer.wrap(new byte[]{0x10, // message type ByteBuffer msg = ByteBuffer.wrap(new byte[]{0x10, // message type
0x0C, // remaining lenght 12 bytes 0x0C, // remaining lenght 12 bytes
'M', 'Q','I','s','d','p', 'M', 'Q', 'I', 's', 'd', 'p', 0x03, // protocol version
0x03, //protocol version
0x32, // flags 0x32, // flags
0x02, 0x00// keepAlive Timer, 2 seconds 0x02, 0x00// keepAlive Timer, 2 seconds
}); });
@@ -13,12 +13,12 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.util.concurrent.*; import java.util.concurrent.*;
/** /**
@@ -27,6 +27,7 @@ import java.util.concurrent.*;
public class MessageCollector implements MqttCallback { public class MessageCollector implements MqttCallback {
private class ReceivedMessage { private class ReceivedMessage {
private final MqttMessage message; private final MqttMessage message;
private final String topic; private final String topic;
@@ -41,7 +42,7 @@ public class MessageCollector implements MqttCallback {
/** /**
* Return the message from the queue if not empty, else return null with wait period. * Return the message from the queue if not empty, else return null with wait period.
* */ */
public MqttMessage getMessageImmediate() { public MqttMessage getMessageImmediate() {
if (m_messages.isEmpty()) { if (m_messages.isEmpty()) {
return null; return null;
@@ -94,7 +95,7 @@ public class MessageCollector implements MqttCallback {
/** /**
* Invoked when the message sent to a server is ACKED (PUBACK or PUBCOMP by the server) * Invoked when the message sent to a server is ACKED (PUBACK or PUBCOMP by the server)
* */ */
@Override @Override
public void deliveryComplete(IMqttDeliveryToken token) { public void deliveryComplete(IMqttDeliveryToken token) {
// try { // try {
@@ -1,3 +1,4 @@
package io.moquette.server; package io.moquette.server;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -10,19 +11,18 @@ import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
import org.junit.*; import org.junit.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Properties; import java.util.Properties;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
* Created by mackristof on 13/05/2016. * Created by mackristof on 13/05/2016.
*/ */
public class ServerIntegrationDBAuthenticatorTest { public class ServerIntegrationDBAuthenticatorTest {
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationDBAuthenticatorTest.class); private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationDBAuthenticatorTest.class);
static MqttClientPersistence s_dataStore; static MqttClientPersistence s_dataStore;
@@ -35,8 +35,6 @@ public class ServerIntegrationDBAuthenticatorTest {
MessageCollector m_messagesCollector; MessageCollector m_messagesCollector;
IConfig m_config; IConfig m_config;
@BeforeClass @BeforeClass
public static void beforeTests() throws NoSuchAlgorithmException, SQLException, ClassNotFoundException { public static void beforeTests() throws NoSuchAlgorithmException, SQLException, ClassNotFoundException {
String tmpDir = System.getProperty("java.io.tmpdir"); String tmpDir = System.getProperty("java.io.tmpdir");
@@ -53,7 +51,6 @@ public class ServerIntegrationDBAuthenticatorTest {
m_server.startServer(m_config); m_server.startServer(m_config);
} }
private void stopServer() { private void stopServer() {
m_server.stopServer(); m_server.stopServer();
IntegrationUtils.cleanPersistenceFile(m_config); IntegrationUtils.cleanPersistenceFile(m_config);
@@ -111,7 +108,6 @@ public class ServerIntegrationDBAuthenticatorTest {
assertTrue(true); assertTrue(true);
} }
@Test @Test
public void connectWithWrongCredentials() { public void connectWithWrongCredentials() {
LOG.info("*** connectWithWrongCredentials ***"); LOG.info("*** connectWithWrongCredentials ***");
@@ -131,8 +127,6 @@ public class ServerIntegrationDBAuthenticatorTest {
} }
} }
assertTrue("must not be connected. cause : wrong password given to client", false); assertTrue("must not be connected. cause : wrong password given to client", false);
} }
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.server.netty.MessageBuilder; import io.moquette.server.netty.MessageBuilder;
@@ -28,11 +29,9 @@ import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Properties; import java.util.Properties;
import static org.junit.Assert.*; import static org.junit.Assert.*;
public class ServerIntegrationEmbeddedPublishTest { public class ServerIntegrationEmbeddedPublishTest {
@@ -89,12 +88,8 @@ public class ServerIntegrationEmbeddedPublishTest {
} }
private void internalPublishToWithQosAndRetained(String topic, MqttQoS qos, boolean retained) { private void internalPublishToWithQosAndRetained(String topic, MqttQoS qos, boolean retained) {
MqttPublishMessage message = MessageBuilder.publish() MqttPublishMessage message = MessageBuilder.publish().topicName(topic).retained(retained).qos(qos)
.topicName(topic) .payload("Hello world MQTT!!".getBytes()).build();
.retained(retained)
.qos(qos)
.payload("Hello world MQTT!!".getBytes())
.build();
m_server.internalPublish(message, "INTRPUBL"); m_server.internalPublish(message, "INTRPUBL");
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.server.config.IConfig; import io.moquette.server.config.IConfig;
@@ -23,11 +24,9 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
@@ -35,6 +34,7 @@ import static org.junit.Assert.*;
* @author andrea * @author andrea
*/ */
public class ServerIntegrationFuseTest { public class ServerIntegrationFuseTest {
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationPahoTest.class); private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationPahoTest.class);
Server m_server; Server m_server;
@@ -1,3 +1,4 @@
package io.moquette.server; package io.moquette.server;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -12,16 +13,15 @@ import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
import org.junit.*; import org.junit.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Properties; import java.util.Properties;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class ServerIntegrationHazelcastHandlerInterceptorTest { public class ServerIntegrationHazelcastHandlerInterceptorTest {
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationHazelcastHandlerInterceptorTest.class); private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationHazelcastHandlerInterceptorTest.class);
static MqttClientPersistence s_dataStore; static MqttClientPersistence s_dataStore;
@@ -55,7 +55,9 @@ public class ServerIntegrationHazelcastHandlerInterceptorTest{
private Properties addHazelCastConf(Properties properties, int port, String hazelcastConfigurationFile) { private Properties addHazelCastConf(Properties properties, int port, String hazelcastConfigurationFile) {
properties.put(BrokerConstants.PORT_PROPERTY_NAME, port); properties.put(BrokerConstants.PORT_PROPERTY_NAME, port);
properties.put(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME, HazelcastInterceptHandler.class.getCanonicalName()); properties.put(
BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME,
HazelcastInterceptHandler.class.getCanonicalName());
properties.put(BrokerConstants.HAZELCAST_CONFIGURATION, hazelcastConfigurationFile); properties.put(BrokerConstants.HAZELCAST_CONFIGURATION, hazelcastConfigurationFile);
return properties; return properties;
} }
@@ -65,14 +67,18 @@ public class ServerIntegrationHazelcastHandlerInterceptorTest{
String dbPath = IntegrationUtils.localMapDBPath(); String dbPath = IntegrationUtils.localMapDBPath();
IntegrationUtils.cleanPersistenceFile(dbPath); IntegrationUtils.cleanPersistenceFile(dbPath);
final Properties configProps = addHazelCastConf(IntegrationUtils.prepareTestClusterProperties(1883), final Properties configProps = addHazelCastConf(
1883, "config/hazelcast.xml"); IntegrationUtils.prepareTestClusterProperties(1883),
1883,
"config/hazelcast.xml");
m_config_1883 = new MemoryConfig(configProps); m_config_1883 = new MemoryConfig(configProps);
server1883 = startServer(1883, m_config_1883); server1883 = startServer(1883, m_config_1883);
final Properties configProps1884 = addHazelCastConf(IntegrationUtils.prepareTestClusterProperties(1884), final Properties configProps1884 = addHazelCastConf(
1883, "config/hazelcast.xml"); IntegrationUtils.prepareTestClusterProperties(1884),
1883,
"config/hazelcast.xml");
m_config_1884 = new MemoryConfig(configProps1884); m_config_1884 = new MemoryConfig(configProps1884);
server1884 = startServer(1884, m_config_1884); server1884 = startServer(1884, m_config_1884);
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.server.config.IConfig; import io.moquette.server.config.IConfig;
@@ -22,11 +23,9 @@ import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
import org.junit.*; import org.junit.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Properties; import java.util.Properties;
import static org.junit.Assert.*; import static org.junit.Assert.*;
public class ServerIntegrationPahoTest { public class ServerIntegrationPahoTest {
@@ -114,7 +113,6 @@ public class ServerIntegrationPahoTest {
assertEquals("/topic", m_messagesCollector.getTopic()); assertEquals("/topic", m_messagesCollector.getTopic());
} }
@Test @Test
public void testCleanSession_maintainClientSubscriptions() throws Exception { public void testCleanSession_maintainClientSubscriptions() throws Exception {
LOG.info("*** testCleanSession_maintainClientSubscriptions ***"); LOG.info("*** testCleanSession_maintainClientSubscriptions ***");
@@ -134,7 +132,6 @@ public class ServerIntegrationPahoTest {
assertEquals("/topic", m_messagesCollector.getTopic()); assertEquals("/topic", m_messagesCollector.getTopic());
} }
@Test @Test
public void testCleanSession_maintainClientSubscriptions_againstClientDestruction() throws Exception { public void testCleanSession_maintainClientSubscriptions_againstClientDestruction() throws Exception {
LOG.info("*** testCleanSession_maintainClientSubscriptions_againstClientDestruction ***"); LOG.info("*** testCleanSession_maintainClientSubscriptions_againstClientDestruction ***");
@@ -152,9 +149,9 @@ public class ServerIntegrationPahoTest {
} }
/** /**
* Check that after a client has connected with clean session false, subscribed * Check that after a client has connected with clean session false, subscribed to some topic
* to some topic and exited, if it reconnects with clean session true, the m_server * and exited, if it reconnects with clean session true, the m_server correctly cleanup every
* correctly cleanup every previous subscription * previous subscription
*/ */
@Test @Test
public void testCleanSession_correctlyClientSubscriptions() throws Exception { public void testCleanSession_correctlyClientSubscriptions() throws Exception {
@@ -283,7 +280,6 @@ public class ServerIntegrationPahoTest {
assertEquals("Hello MQTT", m_messagesCollector.waitMessage(1).toString()); assertEquals("Hello MQTT", m_messagesCollector.waitMessage(1).toString());
} }
@Test @Test
public void checkReceivePublishedMessage_after_a_reconnect_with_notCleanSession() throws Exception { public void checkReceivePublishedMessage_after_a_reconnect_with_notCleanSession() throws Exception {
LOG.info("*** checkReceivePublishedMessage_after_a_reconnect_with_notCleanSession ***"); LOG.info("*** checkReceivePublishedMessage_after_a_reconnect_with_notCleanSession ***");
@@ -383,11 +379,9 @@ public class ServerIntegrationPahoTest {
} }
/** /**
* subscriber A connect and subscribe on "a/b" QoS 1 * subscriber A connect and subscribe on "a/b" QoS 1 subscriber B connect and subscribe on "a/+"
* subscriber B connect and subscribe on "a/+" BUT with QoS 2 * BUT with QoS 2 publisher connects and send a message "hello" on "a/b" subscriber A must
* publisher connects and send a message "hello" on "a/b" * receive a notification with QoS1 subscriber B must receive a notification with QoS2
* subscriber A must receive a notification with QoS1
* subscriber B must receive a notification with QoS2
*/ */
@Test @Test
public void checkSubscribersGetCorrectQosNotifications() throws Exception { public void checkSubscribersGetCorrectQosNotifications() throws Exception {
@@ -410,7 +404,6 @@ public class ServerIntegrationPahoTest {
subscriberB.connect(); subscriberB.connect();
subscriberB.subscribe("a/+", 2); subscriberB.subscribe("a/+", 2);
m_client.connect(); m_client.connect();
m_client.publish("a/b", "Hello world MQTT!!".getBytes(), 2, false); m_client.publish("a/b", "Hello world MQTT!!".getBytes(), 2, false);
@@ -430,7 +423,8 @@ public class ServerIntegrationPahoTest {
LOG.info("*** testSubcriptionDoesntStayActiveAfterARestart ***"); LOG.info("*** testSubcriptionDoesntStayActiveAfterARestart ***");
String tmpDir = System.getProperty("java.io.tmpdir"); String tmpDir = System.getProperty("java.io.tmpdir");
// clientForSubscribe1 connect and subscribe to /topic QoS2 // clientForSubscribe1 connect and subscribe to /topic QoS2
MqttClientPersistence dsSubscriberA = new MqttDefaultFilePersistence(tmpDir + File.separator + "clientForSubscribe1"); MqttClientPersistence dsSubscriberA = new MqttDefaultFilePersistence(
tmpDir + File.separator + "clientForSubscribe1");
MqttClient clientForSubscribe1 = new MqttClient("tcp://localhost:1883", "clientForSubscribe1", dsSubscriberA); MqttClient clientForSubscribe1 = new MqttClient("tcp://localhost:1883", "clientForSubscribe1", dsSubscriberA);
MessageCollector cbSubscriber1 = new MessageCollector(); MessageCollector cbSubscriber1 = new MessageCollector();
@@ -445,7 +439,8 @@ public class ServerIntegrationPahoTest {
startServer(); startServer();
// clientForSubscribe2 connect and subscribe to /topic QoS2 // clientForSubscribe2 connect and subscribe to /topic QoS2
MqttClientPersistence dsSubscriberB = new MqttDefaultFilePersistence(tmpDir + File.separator + "clientForSubscribe2"); MqttClientPersistence dsSubscriberB = new MqttDefaultFilePersistence(
tmpDir + File.separator + "clientForSubscribe2");
MqttClient clientForSubscribe2 = new MqttClient("tcp://localhost:1883", "clientForSubscribe2", dsSubscriberB); MqttClient clientForSubscribe2 = new MqttClient("tcp://localhost:1883", "clientForSubscribe2", dsSubscriberB);
MessageCollector cbSubscriber2 = new MessageCollector(); MessageCollector cbSubscriber2 = new MessageCollector();
clientForSubscribe2.setCallback(cbSubscriber2); clientForSubscribe2.setCallback(cbSubscriber2);
@@ -453,7 +448,8 @@ public class ServerIntegrationPahoTest {
clientForSubscribe2.subscribe("topic", 0); clientForSubscribe2.subscribe("topic", 0);
// clientForPublish publish on /topic with QoS2 a message // clientForPublish publish on /topic with QoS2 a message
MqttClientPersistence dsSubscriberPUB = new MqttDefaultFilePersistence(tmpDir + File.separator + "clientForPublish"); MqttClientPersistence dsSubscriberPUB = new MqttDefaultFilePersistence(
tmpDir + File.separator + "clientForPublish");
MqttClient clientForPublish = new MqttClient("tcp://localhost:1883", "clientForPublish", dsSubscriberPUB); MqttClient clientForPublish = new MqttClient("tcp://localhost:1883", "clientForPublish", dsSubscriberPUB);
clientForPublish.connect(); clientForPublish.connect();
clientForPublish.publish("topic", "Hello".getBytes(), 2, true); clientForPublish.publish("topic", "Hello".getBytes(), 2, true);
@@ -572,10 +568,9 @@ public class ServerIntegrationPahoTest {
} }
/** /**
* subscriber connect and subscribe on "topic" * subscriber connect and subscribe on "topic" subscriber disconnects publisher connects and
* subscriber disconnects * send two message "hello1" "hello2" to "topic" subscriber connects again and receive "hello1"
* publisher connects and send two message "hello1" "hello2" to "topic" * "hello2"
* subscriber connects again and receive "hello1" "hello2"
*/ */
@Test @Test
public void checkQoS2SubscriberDisconnectReceivePersistedPublishes() throws Exception { public void checkQoS2SubscriberDisconnectReceivePersistedPublishes() throws Exception {
@@ -605,9 +600,8 @@ public class ServerIntegrationPahoTest {
} }
/** /**
* subscriber connect and subscribe on "a/b" QoS 1 and "a/+" QoS 2 * subscriber connect and subscribe on "a/b" QoS 1 and "a/+" QoS 2 publisher connects and send a
* publisher connects and send a message "hello" on "a/b" * message "hello" on "a/b" subscriber must receive only a single message not twice
* subscriber must receive only a single message not twice
*/ */
@Test @Test
public void checkSinglePublishOnOverlappingSubscriptions() throws Exception { public void checkSinglePublishOnOverlappingSubscriptions() throws Exception {
@@ -634,7 +628,6 @@ public class ServerIntegrationPahoTest {
assertNull(msg); assertNull(msg);
} }
protected MqttClient createClient(String clientName, String storeSuffix) throws MqttException { protected MqttClient createClient(String clientName, String storeSuffix) throws MqttException {
return createClient(clientName, storeSuffix, null); return createClient(clientName, storeSuffix, null);
} }
@@ -642,7 +635,8 @@ public class ServerIntegrationPahoTest {
protected MqttClient createClient(String clientName, String storeSuffix, MessageCollector cb) throws MqttException { protected MqttClient createClient(String clientName, String storeSuffix, MessageCollector cb) throws MqttException {
String tmpDir = System.getProperty("java.io.tmpdir"); String tmpDir = System.getProperty("java.io.tmpdir");
// clientX connect and subscribe to /topic QoS2 // clientX connect and subscribe to /topic QoS2
MqttClientPersistence dsClient = new MqttDefaultFilePersistence(tmpDir + File.separator + storeSuffix + clientName); MqttClientPersistence dsClient = new MqttDefaultFilePersistence(
tmpDir + File.separator + storeSuffix + clientName);
MqttClient client = new MqttClient("tcp://localhost:1883", clientName, dsClient); MqttClient client = new MqttClient("tcp://localhost:1883", clientName, dsClient);
if (cb != null) { if (cb != null) {
client.setCallback(cb); client.setCallback(cb);
@@ -13,8 +13,8 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server;
package io.moquette.server;
import io.moquette.server.config.IConfig; import io.moquette.server.config.IConfig;
import io.moquette.server.config.MemoryConfig; import io.moquette.server.config.MemoryConfig;
@@ -29,11 +29,9 @@ import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Properties; import java.util.Properties;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
/** /**
@@ -13,10 +13,10 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -27,13 +27,11 @@ import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException; import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.Properties; import java.util.Properties;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
import org.eclipse.paho.client.mqttv3.IMqttClient; import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttClient;
@@ -53,6 +51,7 @@ import org.slf4j.LoggerFactory;
* *
* <p> * <p>
* Create certificates needed for client authentication * Create certificates needed for client authentication
*
* <pre> * <pre>
* # generate server certificate chain (valid for 10000 days) * # generate server certificate chain (valid for 10000 days)
* keytool -genkeypair -alias signedtestserver -dname cn=moquette.eclipse.org -keyalg RSA -keysize 2048 -keystore signedserverkeystore.jks -keypass passw0rdsrv -storepass passw0rdsrv -validity 10000 * keytool -genkeypair -alias signedtestserver -dname cn=moquette.eclipse.org -keyalg RSA -keysize 2048 -keystore signedserverkeystore.jks -keypass passw0rdsrv -storepass passw0rdsrv -validity 10000
@@ -87,9 +86,11 @@ import org.slf4j.LoggerFactory;
* keytool -importcert -trustcacerts -noprompt -alias signedtestserver_sub -keystore unsignedclientkeystore.jks -keypass passw0rd -storepass passw0rd * keytool -importcert -trustcacerts -noprompt -alias signedtestserver_sub -keystore unsignedclientkeystore.jks -keypass passw0rd -storepass passw0rd
* </pre> * </pre>
* </p> * </p>
*
* @author andrea / konradm * @author andrea / konradm
*/ */
public class ServerIntegrationSSLClientAuthTest { public class ServerIntegrationSSLClientAuthTest {
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationSSLClientAuthTest.class); private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationSSLClientAuthTest.class);
Server m_server; Server m_server;
@@ -173,14 +174,14 @@ public class ServerIntegrationSSLClientAuthTest {
// actual a "Broken pipe" is thrown, this is not very specific. // actual a "Broken pipe" is thrown, this is not very specific.
try { try {
m_client.connect(options); m_client.connect(options);
}catch(MqttException e) } catch (MqttException e) {
{
e.printStackTrace(); e.printStackTrace();
throw e; throw e;
} }
} }
private SSLSocketFactory configureSSLSocketFactory(String keystore) throws KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, IOException, CertificateException, KeyStoreException { private SSLSocketFactory configureSSLSocketFactory(String keystore) throws KeyManagementException,
NoSuchAlgorithmException, UnrecoverableKeyException, IOException, CertificateException, KeyStoreException {
KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ks = KeyStore.getInstance("JKS");
InputStream jksInputStream = getClass().getClassLoader().getResourceAsStream(keystore); InputStream jksInputStream = getClass().getClassLoader().getResourceAsStream(keystore);
ks.load(jksInputStream, "passw0rd".toCharArray()); ks.load(jksInputStream, "passw0rd".toCharArray());
@@ -13,10 +13,10 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -27,13 +27,11 @@ import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException; import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.Properties; import java.util.Properties;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
import org.eclipse.paho.client.mqttv3.IMqttClient; import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttClient;
@@ -55,6 +53,7 @@ import org.slf4j.LoggerFactory;
* @author andrea * @author andrea
*/ */
public class ServerIntegrationSSLTest { public class ServerIntegrationSSLTest {
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationSSLTest.class); private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationSSLTest.class);
Server m_server; Server m_server;
@@ -146,23 +145,23 @@ public class ServerIntegrationSSLTest {
m_client.disconnect(); m_client.disconnect();
} }
/** /**
* keystore generated into test/resources with command: * keystore generated into test/resources with command:
* *
* keytool -keystore clientkeystore.jks -alias testclient -genkey -keyalg RSA * keytool -keystore clientkeystore.jks -alias testclient -genkey -keyalg RSA -> mandatory to
* -> mandatory to put the name surname * put the name surname -> password is passw0rd -> type yes at the end
* -> password is passw0rd
* -> type yes at the end
* *
* to generate the crt file from the keystore * to generate the crt file from the keystore -- keytool -certreq -alias testclient -keystore
* -- keytool -certreq -alias testclient -keystore clientkeystore.jks -file testclient.csr * clientkeystore.jks -file testclient.csr
* *
* keytool -export -alias testclient -keystore clientkeystore.jks -file testclient.crt * keytool -export -alias testclient -keystore clientkeystore.jks -file testclient.crt
* *
* to import an existing certificate: * to import an existing certificate: keytool -keystore clientkeystore.jks -import -alias
* keytool -keystore clientkeystore.jks -import -alias testclient -file testclient.crt -trustcacerts * testclient -file testclient.crt -trustcacerts
*/ */
private SSLSocketFactory configureSSLSocketFactory() throws KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, IOException, CertificateException, KeyStoreException { private SSLSocketFactory configureSSLSocketFactory() throws KeyManagementException, NoSuchAlgorithmException,
UnrecoverableKeyException, IOException, CertificateException, KeyStoreException {
KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ks = KeyStore.getInstance("JKS");
InputStream jksInputStream = getClass().getClassLoader().getResourceAsStream("clientkeystore.jks"); InputStream jksInputStream = getClass().getClassLoader().getResourceAsStream("clientkeystore.jks");
ks.load(jksInputStream, "passw0rd".toCharArray()); ks.load(jksInputStream, "passw0rd".toCharArray());
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
@@ -25,21 +26,19 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
* Integration test to check the function of Moquette with a WebSocket channel. * Integration test to check the function of Moquette with a WebSocket channel.
* *
* @author andrea * @author andrea
*/ */
public class ServerIntegrationWebSocketTest { public class ServerIntegrationWebSocketTest {
private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationWebSocketTest.class); private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationWebSocketTest.class);
Server m_server; Server m_server;
@@ -49,7 +48,8 @@ public class ServerIntegrationWebSocketTest {
protected void startServer() throws IOException { protected void startServer() throws IOException {
m_server = new Server(); m_server = new Server();
final Properties configProps = IntegrationUtils.prepareTestProperties(); final Properties configProps = IntegrationUtils.prepareTestProperties();
configProps.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.WEBSOCKET_PORT)); configProps
.put(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.WEBSOCKET_PORT));
m_config = new MemoryConfig(configProps); m_config = new MemoryConfig(configProps);
m_server.startServer(m_config); m_server.startServer(m_config);
} }
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.server.config.IConfig; import io.moquette.server.config.IConfig;
@@ -26,7 +27,6 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.util.Properties; import java.util.Properties;
import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.*; import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.*;
@@ -37,6 +37,7 @@ import static org.junit.Assert.*;
* @author andrea * @author andrea
*/ */
public class ServerLowlevelMessagesIntegrationTests { public class ServerLowlevelMessagesIntegrationTests {
private static final Logger LOG = LoggerFactory.getLogger(ServerLowlevelMessagesIntegrationTests.class); private static final Logger LOG = LoggerFactory.getLogger(ServerLowlevelMessagesIntegrationTests.class);
static MqttClientPersistence s_dataStore; static MqttClientPersistence s_dataStore;
Server m_server; Server m_server;
@@ -78,10 +79,11 @@ public class ServerLowlevelMessagesIntegrationTests {
MqttConnectMessage connectMessage = createConnectMessage("FAKECLNT", keepAlive); MqttConnectMessage connectMessage = createConnectMessage("FAKECLNT", keepAlive);
/*ConnectMessage connectMessage = new ConnectMessage(); /*
connectMessage.setProtocolVersion((byte) 3); * ConnectMessage connectMessage = new ConnectMessage();
connectMessage.setClientID("FAKECLNT"); * connectMessage.setProtocolVersion((byte) 3); connectMessage.setClientID("FAKECLNT");
connectMessage.setKeepAlive(keepAlive);*/ * connectMessage.setKeepAlive(keepAlive);
*/
m_client.sendMessage(connectMessage); m_client.sendMessage(connectMessage);
// wait 2 times the keepAlive // wait 2 times the keepAlive
@@ -91,9 +93,13 @@ public class ServerLowlevelMessagesIntegrationTests {
} }
private static MqttConnectMessage createConnectMessage(String clientID, int keepAlive) { private static MqttConnectMessage createConnectMessage(String clientID, int keepAlive) {
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
MqttConnectVariableHeader mqttConnectVariableHeader = MqttMessageType.CONNECT,
new MqttConnectVariableHeader( false,
MqttQoS.AT_MOST_ONCE,
false,
0);
MqttConnectVariableHeader mqttConnectVariableHeader = new MqttConnectVariableHeader(
MqttVersion.MQTT_3_1.protocolName(), MqttVersion.MQTT_3_1.protocolName(),
MqttVersion.MQTT_3_1.protocolLevel(), MqttVersion.MQTT_3_1.protocolLevel(),
false, false,
@@ -13,6 +13,7 @@
* *
* You may elect to redistribute this code under either of these licenses. * You may elect to redistribute this code under either of these licenses.
*/ */
package io.moquette.server; package io.moquette.server;
import io.moquette.server.config.IConfig; import io.moquette.server.config.IConfig;
@@ -23,7 +24,6 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Properties; import java.util.Properties;
@@ -88,7 +88,6 @@ public class ServerRestartIntegrationTest {
IntegrationUtils.cleanPersistenceFile(m_config); IntegrationUtils.cleanPersistenceFile(m_config);
} }
@Test @Test
public void checkRestartCleanSubscriptionTree() throws Exception { public void checkRestartCleanSubscriptionTree() throws Exception {
// subscribe to /topic // subscribe to /topic
@@ -118,7 +117,6 @@ public class ServerRestartIntegrationTest {
assertNull(m_messageCollector.waitMessage(1)); assertNull(m_messageCollector.waitMessage(1));
} }
@Test @Test
public void checkDontPublishInactiveClientsAfterServerRestart() throws Exception { public void checkDontPublishInactiveClientsAfterServerRestart() throws Exception {
IMqttClient conn = subscribeAndPublish("/topic"); IMqttClient conn = subscribeAndPublish("/topic");
@@ -166,7 +164,7 @@ public class ServerRestartIntegrationTest {
/** /**
* Connect subscribe to topic and publish on the same topic * Connect subscribe to topic and publish on the same topic
* */ */
private IMqttClient subscribeAndPublish(String topic) throws Exception { private IMqttClient subscribeAndPublish(String topic) throws Exception {
IMqttClient client = new MqttClient("tcp://localhost:1883", "SubPub"); IMqttClient client = new MqttClient("tcp://localhost:1883", "SubPub");
MessageCollector collector = new MessageCollector(); MessageCollector collector = new MessageCollector();

Some files were not shown because too many files have changed in this diff Show More