增加转发开关

This commit is contained in:
2026-06-05 20:03:52 +08:00
parent bfdf57cd72
commit fb1971da72
15 changed files with 615 additions and 16 deletions
+6 -2
View File
@@ -32,6 +32,10 @@ var defaultMeshtasticPSK = []byte{
0xCF, 0x4E, 0x69, 0x01,
}
type Options struct {
AllowEncryptedForwarding bool
}
type serviceEnvelope struct {
Packet *meshPacket
ChannelID string
@@ -115,7 +119,7 @@ type telemetryInfo struct {
// MQTTPP 处理一个 MQTT 原始 payload,返回合规状态、原始数据和解码后的记录。
// 第一个返回值表示数据是否合规;第二个返回值在不合规时为 nil;第三个返回值是解码结果记录。
func MQTTPP(topic string, raw []byte, key []byte) (bool, []byte, map[string]any) {
func MQTTPP(topic string, raw []byte, key []byte, opts Options) (bool, []byte, map[string]any) {
env, err := parseServiceEnvelope(raw)
if err != nil {
@@ -127,7 +131,7 @@ func MQTTPP(topic string, raw []byte, key []byte) (bool, []byte, map[string]any)
//解码失败
return false, nil, map[string]any{"topic": topic, "error": err.Error(), "payload_len": len(raw)}
}
if record["type"] == "encrypted_packet" {
if record["type"] == "encrypted_packet" && !opts.AllowEncryptedForwarding {
record["error"] = "cannot be decrypted"
return false, nil, record
}
+48
View File
@@ -0,0 +1,48 @@
package mqtpp
import (
"testing"
"google.golang.org/protobuf/encoding/protowire"
)
func TestMQTTPPEncryptedPacketDefaultRejected(t *testing.T) {
raw := encryptedServiceEnvelopeTestPayload()
valid, payload, record := MQTTPP("msh/test", raw, nil, Options{})
if valid {
t.Fatalf("valid = true, want false")
}
if payload != nil {
t.Fatalf("payload = %v, want nil", payload)
}
if record["type"] != "encrypted_packet" {
t.Fatalf("type = %v, want encrypted_packet", record["type"])
}
if record["error"] != "cannot be decrypted" {
t.Fatalf("error = %v, want cannot be decrypted", record["error"])
}
}
func TestMQTTPPEncryptedPacketAllowed(t *testing.T) {
raw := encryptedServiceEnvelopeTestPayload()
valid, payload, record := MQTTPP("msh/test", raw, nil, Options{AllowEncryptedForwarding: true})
if !valid {
t.Fatalf("valid = false, want true: %+v", record)
}
if string(payload) != string(raw) {
t.Fatalf("payload = %v, want raw payload", payload)
}
if record["type"] != "encrypted_packet" {
t.Fatalf("type = %v, want encrypted_packet", record["type"])
}
if record["error"] != nil {
t.Fatalf("error = %v, want nil", record["error"])
}
}
func encryptedServiceEnvelopeTestPayload() []byte {
packet := protowire.AppendTag(nil, 5, protowire.BytesType)
packet = protowire.AppendBytes(packet, []byte{1, 2, 3, 4})
envelope := protowire.AppendTag(nil, 1, protowire.BytesType)
return protowire.AppendBytes(envelope, packet)
}