fix alamos can't connect to MQTT with empty password

This commit is contained in:
Jonas Leder 2026-10-11 10:02:33 +02:00
commit 79cba3e340

View file

@ -1,17 +1,77 @@
package mqttserver
import (
"bytes"
"os"
"github.com/wind-c/comqtt/v2/mqtt"
"github.com/wind-c/comqtt/v2/mqtt/hooks/auth"
"github.com/wind-c/comqtt/v2/mqtt/listeners"
"github.com/wind-c/comqtt/v2/mqtt/packets"
"jonasled.dev/jonasled/fms32-pro-mqtt/log"
)
// connectCompatHook works around overly strict CONNECT validation in comqtt.
type connectCompatHook struct {
mqtt.HookBase
}
func (h *connectCompatHook) ID() string {
return "connect-compat"
}
func (h *connectCompatHook) Provides(b byte) bool {
return bytes.Contains([]byte{mqtt.OnPacketRead}, []byte{b})
}
func (h *connectCompatHook) OnPacketRead(cl *mqtt.Client, pk packets.Packet) (packets.Packet, error) {
if pk.FixedHeader.Type != packets.Connect {
return pk, nil
}
// MQTT allows a zero-length password, but comqtt rejects it with a protocol violation
if pk.Connect.PasswordFlag && len(pk.Connect.Password) == 0 {
pk.Connect.PasswordFlag = false
}
return pk, nil
}
// mapV3ConnackCodes makes sure MQTT 3.x clients only receive CONNACK return codes valid for their
// protocol version (0x00-0x05). Unmapped codes are sent as MQTT 5 reason codes, which clients like
// HiveMQ reject with "wrong return code".
func mapV3ConnackCodes() {
codes := map[packets.Code]packets.Code{
packets.ErrUnspecifiedError: packets.Err3ClientIdentifierNotValid, // persistent session without client id
packets.ErrProtocolViolationProtocolName: packets.Err3UnsupportedProtocolVersion,
packets.ErrProtocolViolationProtocolVersion: packets.Err3UnsupportedProtocolVersion,
packets.ErrClientIdentifierTooLong: packets.Err3ClientIdentifierNotValid,
packets.ErrProtocolViolationReservedBit: packets.Err3ServerUnavailable,
packets.ErrProtocolViolationPasswordTooLong: packets.ErrMalformedUsernameOrPassword,
packets.ErrProtocolViolationUsernameTooLong: packets.ErrMalformedUsernameOrPassword,
packets.ErrProtocolViolationUsernameNoFlag: packets.ErrMalformedUsernameOrPassword,
packets.ErrProtocolViolationPasswordNoFlag: packets.ErrMalformedUsernameOrPassword,
packets.ErrProtocolViolationFlagNoPassword: packets.ErrMalformedUsernameOrPassword,
packets.ErrProtocolViolationWillFlagNoPayload: packets.Err3ServerUnavailable,
packets.ErrProtocolViolationWillFlagSurplusRetain: packets.Err3ServerUnavailable,
packets.ErrProtocolViolationQosOutOfRange: packets.Err3ServerUnavailable,
packets.ErrQosNotSupported: packets.Err3ServerUnavailable,
packets.ErrRetainNotSupported: packets.Err3ServerUnavailable,
packets.ErrNotAuthorized: packets.Err3NotAuthorized,
}
for v5, v3 := range codes {
if _, ok := packets.V5CodesToV3[v5]; !ok {
packets.V5CodesToV3[v5] = v3
}
}
}
func Start() {
mapV3ConnackCodes()
server := mqtt.New(nil)
_ = server.AddHook(new(connectCompatHook), nil)
_ = server.AddHook(new(auth.AllowHook), nil)
if os.Getenv("MQTT_LISTEN") == "" {