Search in sources :

Example 1 with MqttFixedHeader

use of com.swiftmq.impl.mqtt.v311.netty.handler.codec.mqtt.MqttFixedHeader in project swiftmq-ce by iitsoftware.

the class MQTTConnection method visit.

@Override
public void visit(POConnect po) {
    if (closed || protocolInvalid)
        return;
    if (ctx.traceSpace.enabled)
        ctx.traceSpace.trace(ctx.mqttSwiftlet.getName(), toString() + ", visit, po=" + po + " ...");
    if (nConnectPackets > 0) {
        protocolInvalid = true;
        initiateClose("protocol error, multiple connect packets");
        return;
    }
    nConnectPackets++;
    connectMessage = po.getMessage();
    MqttConnectVariableHeader variableConnectHeader = connectMessage.variableHeader();
    MqttConnectPayload payload = connectMessage.payload();
    clientId = payload.clientIdentifier();
    if (clientId == null || clientId.length() == 0) {
        if (!variableConnectHeader.isCleanSession())
            rc = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;
        else
            clientId = UUID.randomUUID().toString();
    }
    if (rc == null) {
        String password = null;
        if (variableConnectHeader.hasUserName())
            username = payload.userName();
        if (variableConnectHeader.hasPassword())
            password = new String(payload.passwordInBytes());
        try {
            ctx.authSwiftlet.verifyHostLogin(username, remoteHostname);
            String pwd = ctx.authSwiftlet.getPassword(username);
            if (password == pwd || password != null && password.equals(pwd)) {
                rc = MqttConnectReturnCode.CONNECTION_ACCEPTED;
                activeLogin = ctx.authSwiftlet.createActiveLogin(username, "MQTT");
                activeLogin.setClientId(clientId);
                authenticated = true;
            } else
                throw new AuthenticationException("invalid password");
            keepaliveInterval = (long) ((double) (variableConnectHeader.keepAliveTimeSeconds() * 1000.0) * 1.5);
            if (keepaliveInterval > 0) {
                ctx.timerSwiftlet.addTimerListener(keepaliveInterval, this);
            }
            if (variableConnectHeader.isWillFlag())
                will = new Will(payload.willTopic(), variableConnectHeader.willQos(), variableConnectHeader.isWillRetain(), payload.willMessageInBytes());
            cleanSession = variableConnectHeader.isCleanSession();
            if (!cleanSession) {
                ctx.sessionRegistry.associateSession(clientId, this);
            } else {
                ctx.sessionRegistry.removeSession(clientId);
                MQTTSession session = new MQTTSession(ctx, clientId, false);
                session.associate(this);
                associated(session);
            }
            hasLastWill = variableConnectHeader.isWillFlag();
            lastWillRetain = variableConnectHeader.isWillRetain();
            lastWillQoS = MqttQoS.valueOf(variableConnectHeader.willQos());
            lastWillTopic = payload.willTopic();
            lastWillPayload = new ByteBuf(payload.willMessageInBytes());
            try {
                usage.getProperty("client-id").setValue(clientId);
                usage.getProperty("username").setValue(username);
                usage.getProperty("mqtt-protlevel").setValue(variableConnectHeader.version());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (AuthenticationException e) {
            rc = MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD;
        } catch (ResourceLimitException e) {
            rc = MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED;
        }
    }
    MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, connectMessage.fixedHeader().isDup(), connectMessage.fixedHeader().qosLevel(), connectMessage.fixedHeader().isRetain(), 2);
    MqttConnAckVariableHeader variableHeader = new MqttConnAckVariableHeader(rc, false);
    connAckMessage = new MqttConnAckMessage(fixedHeader, variableHeader);
    if (rc != MqttConnectReturnCode.CONNECTION_ACCEPTED) {
        protocolInvalid = true;
        initiateClose("not authenticated");
    }
    if (ctx.traceSpace.enabled)
        ctx.traceSpace.trace(ctx.mqttSwiftlet.getName(), toString() + ", visit, po=" + po + " done");
}
Also used : MQTTSession(com.swiftmq.impl.mqtt.session.MQTTSession) AuthenticationException(com.swiftmq.swiftlet.auth.AuthenticationException) ByteBuf(com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf) AuthenticationException(com.swiftmq.swiftlet.auth.AuthenticationException) ResourceLimitException(com.swiftmq.swiftlet.auth.ResourceLimitException) ResourceLimitException(com.swiftmq.swiftlet.auth.ResourceLimitException)

Example 2 with MqttFixedHeader

use of com.swiftmq.impl.mqtt.v311.netty.handler.codec.mqtt.MqttFixedHeader in project swiftmq-ce by iitsoftware.

the class MqttEncoder method encodeConnectMessage.

private static com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf encodeConnectMessage(MqttConnectMessage message) {
    int payloadBufferSize = 0;
    MqttFixedHeader mqttFixedHeader = message.fixedHeader();
    MqttConnectVariableHeader variableHeader = message.variableHeader();
    MqttConnectPayload payload = message.payload();
    MqttVersion mqttVersion = MqttVersion.fromProtocolNameAndLevel(variableHeader.name(), (byte) variableHeader.version());
    // as MQTT 3.1 & 3.1.1 spec, If the User Name Flag is set to 0, the Password Flag MUST be set to 0
    if (!variableHeader.hasUserName() && variableHeader.hasPassword()) {
        throw new DecoderException("Without a username, the password MUST be not set");
    }
    // Client id
    String clientIdentifier = payload.clientIdentifier();
    if (!isValidClientId(mqttVersion, clientIdentifier)) {
        throw new MqttIdentifierRejectedException("invalid clientIdentifier: " + clientIdentifier);
    }
    byte[] clientIdentifierBytes = encodeStringUtf8(clientIdentifier);
    payloadBufferSize += 2 + clientIdentifierBytes.length;
    // Will topic and message
    String willTopic = payload.willTopic();
    byte[] willTopicBytes = willTopic != null ? encodeStringUtf8(willTopic) : com.swiftmq.impl.mqtt.v311.netty.util.internal.EmptyArrays.EMPTY_BYTES;
    byte[] willMessage = payload.willMessageInBytes();
    byte[] willMessageBytes = willMessage != null ? willMessage : com.swiftmq.impl.mqtt.v311.netty.util.internal.EmptyArrays.EMPTY_BYTES;
    if (variableHeader.isWillFlag()) {
        payloadBufferSize += 2 + willTopicBytes.length;
        payloadBufferSize += 2 + willMessageBytes.length;
    }
    String userName = payload.userName();
    byte[] userNameBytes = userName != null ? encodeStringUtf8(userName) : com.swiftmq.impl.mqtt.v311.netty.util.internal.EmptyArrays.EMPTY_BYTES;
    if (variableHeader.hasUserName()) {
        payloadBufferSize += 2 + userNameBytes.length;
    }
    byte[] password = payload.passwordInBytes();
    byte[] passwordBytes = password != null ? password : EmptyArrays.EMPTY_BYTES;
    if (variableHeader.hasPassword()) {
        payloadBufferSize += 2 + passwordBytes.length;
    }
    // Fixed header
    byte[] protocolNameBytes = mqttVersion.protocolNameBytes();
    int variableHeaderBufferSize = 2 + protocolNameBytes.length + 4;
    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);
    com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf buf = new com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(mqttFixedHeader));
    writeVariableLengthInt(buf, variablePartSize);
    buf.writeShort(protocolNameBytes.length);
    buf.writeBytes(protocolNameBytes);
    buf.writeByte(variableHeader.version());
    buf.writeByte(getConnVariableHeaderFlag(variableHeader));
    buf.writeShort(variableHeader.keepAliveTimeSeconds());
    // Payload
    buf.writeShort(clientIdentifierBytes.length);
    buf.writeBytes(clientIdentifierBytes, 0, clientIdentifierBytes.length);
    if (variableHeader.isWillFlag()) {
        buf.writeShort(willTopicBytes.length);
        buf.writeBytes(willTopicBytes, 0, willTopicBytes.length);
        buf.writeShort(willMessageBytes.length);
        buf.writeBytes(willMessageBytes, 0, willMessageBytes.length);
    }
    if (variableHeader.hasUserName()) {
        buf.writeShort(userNameBytes.length);
        buf.writeBytes(userNameBytes, 0, userNameBytes.length);
    }
    if (variableHeader.hasPassword()) {
        buf.writeShort(passwordBytes.length);
        buf.writeBytes(passwordBytes, 0, passwordBytes.length);
    }
    return buf;
}
Also used : ByteBuf(com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf) DecoderException(com.swiftmq.impl.mqtt.v311.netty.handler.codec.DecoderException) ByteBuf(com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf)

Example 3 with MqttFixedHeader

use of com.swiftmq.impl.mqtt.v311.netty.handler.codec.mqtt.MqttFixedHeader in project swiftmq-ce by iitsoftware.

the class MQTTSession method visit.

@Override
public void visit(POSendMessage po) {
    if (ctx.traceSpace.enabled)
        ctx.traceSpace.trace(ctx.mqttSwiftlet.getName(), toString() + ", visit, po=" + po + " ...");
    try {
        BytesMessageImpl jmsMessage = (BytesMessageImpl) po.getJmsMessage();
        jmsMessage.reset();
        MqttQoS qos = po.getQos();
        String topicName = topicNameTranslateReverse(po.getTopicName());
        byte[] b = new byte[(int) jmsMessage.getBodyLength()];
        jmsMessage.readBytes(b);
        ByteBuf byteBuf = new ByteBuf(b);
        byteBuf.reset();
        int packetId = -1;
        if (qos != MqttQoS.AT_MOST_ONCE) {
            if (pid == 65535)
                pid = 1;
            packetId = pid++;
            outboundPackets.put(packetId, po);
        }
        mqttConnection.getOutboundQueue().enqueue(new MqttPublishMessage(new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, false, 0), new MqttPublishVariableHeader(topicName, packetId), byteBuf));
        if (qos == MqttQoS.AT_MOST_ONCE) {
            po.getTransaction().commit();
            po.getSubscription().restart();
        } else
            addReplay(packetId, new MqttPublishMessage(new MqttFixedHeader(MqttMessageType.PUBLISH, true, qos, false, 0), new MqttPublishVariableHeader(topicName, packetId), byteBuf));
        incMsgsReceived(1);
    } catch (QueueTransactionClosedException qtc) {
    } catch (Exception e) {
        mqttConnection.initiateClose("send message: exception=" + e);
    }
    if (ctx.traceSpace.enabled)
        ctx.traceSpace.trace(ctx.mqttSwiftlet.getName(), toString() + ", visit, po=" + po + " done");
}
Also used : QueueTransactionClosedException(com.swiftmq.swiftlet.queue.QueueTransactionClosedException) BytesMessageImpl(com.swiftmq.jms.BytesMessageImpl) ByteBuf(com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf) EntityAddException(com.swiftmq.mgmt.EntityAddException) QueueTransactionClosedException(com.swiftmq.swiftlet.queue.QueueTransactionClosedException)

Example 4 with MqttFixedHeader

use of com.swiftmq.impl.mqtt.v311.netty.handler.codec.mqtt.MqttFixedHeader in project swiftmq-ce by iitsoftware.

the class MqttEncoder method encodeSubscribeMessage.

private static com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf encodeSubscribeMessage(MqttSubscribeMessage message) {
    int variableHeaderBufferSize = 2;
    int payloadBufferSize = 0;
    MqttFixedHeader mqttFixedHeader = message.fixedHeader();
    MqttMessageIdVariableHeader variableHeader = message.variableHeader();
    MqttSubscribePayload payload = message.payload();
    for (MqttTopicSubscription topic : payload.topicSubscriptions()) {
        String topicName = topic.topicName();
        byte[] topicNameBytes = encodeStringUtf8(topicName);
        payloadBufferSize += 2 + topicNameBytes.length;
        payloadBufferSize += 1;
    }
    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);
    com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf buf = new com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(mqttFixedHeader));
    writeVariableLengthInt(buf, variablePartSize);
    // Variable Header
    int messageId = variableHeader.messageId();
    buf.writeShort(messageId);
    // Payload
    for (MqttTopicSubscription topic : payload.topicSubscriptions()) {
        String topicName = topic.topicName();
        byte[] topicNameBytes = encodeStringUtf8(topicName);
        buf.writeShort(topicNameBytes.length);
        buf.writeBytes(topicNameBytes, 0, topicNameBytes.length);
        buf.writeByte(topic.qualityOfService().value());
    }
    return buf;
}
Also used : ByteBuf(com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf) ByteBuf(com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf)

Example 5 with MqttFixedHeader

use of com.swiftmq.impl.mqtt.v311.netty.handler.codec.mqtt.MqttFixedHeader in project swiftmq-ce by iitsoftware.

the class MqttEncoder method encodeUnsubscribeMessage.

private static com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf encodeUnsubscribeMessage(MqttUnsubscribeMessage message) {
    int variableHeaderBufferSize = 2;
    int payloadBufferSize = 0;
    MqttFixedHeader mqttFixedHeader = message.fixedHeader();
    MqttMessageIdVariableHeader variableHeader = message.variableHeader();
    MqttUnsubscribePayload payload = message.payload();
    for (String topicName : payload.topics()) {
        byte[] topicNameBytes = encodeStringUtf8(topicName);
        payloadBufferSize += 2 + topicNameBytes.length;
    }
    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);
    com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf buf = new com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(mqttFixedHeader));
    writeVariableLengthInt(buf, variablePartSize);
    // Variable Header
    int messageId = variableHeader.messageId();
    buf.writeShort(messageId);
    // Payload
    for (String topicName : payload.topics()) {
        byte[] topicNameBytes = encodeStringUtf8(topicName);
        buf.writeShort(topicNameBytes.length);
        buf.writeBytes(topicNameBytes, 0, topicNameBytes.length);
    }
    return buf;
}
Also used : ByteBuf(com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf) ByteBuf(com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf)

Aggregations

ByteBuf (com.swiftmq.impl.mqtt.v311.netty.buffer.ByteBuf)9 BytesMessageImpl (com.swiftmq.jms.BytesMessageImpl)2 MQTTSession (com.swiftmq.impl.mqtt.session.MQTTSession)1 DecoderException (com.swiftmq.impl.mqtt.v311.netty.handler.codec.DecoderException)1 MqttFixedHeader (com.swiftmq.impl.mqtt.v311.netty.handler.codec.mqtt.MqttFixedHeader)1 EntityAddException (com.swiftmq.mgmt.EntityAddException)1 AuthenticationException (com.swiftmq.swiftlet.auth.AuthenticationException)1 ResourceLimitException (com.swiftmq.swiftlet.auth.ResourceLimitException)1 QueueTransactionClosedException (com.swiftmq.swiftlet.queue.QueueTransactionClosedException)1