Files
go-sms-V2/internal/protocol/cmpp/header.go
T

123 lines
3.3 KiB
Go

// header.go CMPP 2.0 消息头(12 字节):Total_Length + Command_ID + Sequence_ID,
// 统一大端序;Command_ID 常量按中国移动 CMPP 2.0 规范定义(Day 31:连接/心跳;
// Submit/Deliver 见 Day 32)。
package cmpp
import (
"encoding/binary"
"errors"
"fmt"
"io"
)
// CommandID CMPP 命令字(请求 + 高位 0x80 的响应)。
type CommandID uint32
// CMPP 2.0 命令常量。
const (
CmdConnect CommandID = 0x00000001 // 连接请求
CmdConnectResp CommandID = 0x80000001
CmdTerminate CommandID = 0x00000002 // 断开
CmdTerminateResp CommandID = 0x80000002
CmdSubmit CommandID = 0x00000004 // 提交短信(Day 32)
CmdSubmitResp CommandID = 0x80000004
CmdDeliver CommandID = 0x00000005 // 回执/上行下发(Day 32)
CmdDeliverResp CommandID = 0x80000005
CmdActiveTest CommandID = 0x00000008 // 链路检测(心跳)
CmdActiveTestResp CommandID = 0x80000008
)
// String 命令可读名(日志用)。
func (id CommandID) String() string {
switch id {
case CmdConnect:
return "connect"
case CmdConnectResp:
return "connect_resp"
case CmdTerminate:
return "terminate"
case CmdTerminateResp:
return "terminate_resp"
case CmdSubmit:
return "submit"
case CmdSubmitResp:
return "submit_resp"
case CmdDeliver:
return "deliver"
case CmdDeliverResp:
return "deliver_resp"
case CmdActiveTest:
return "active_test"
case CmdActiveTestResp:
return "active_test_resp"
}
return fmt.Sprintf("cmd_0x%08x", uint32(id))
}
// Header CMPP 消息头。
type Header struct {
TotalLength uint32 // 消息总长(含头)
CommandID CommandID
SequenceID uint32
}
// HeaderLen 消息头固定长度。
const HeaderLen = 12
// ErrBadHeader 非法消息头。
var ErrBadHeader = errors.New("cmpp: 非法消息头")
// MaxPacketLength 单包上限(防恶意超大包,CMPP 实务 1KB~4KB;Deliver 最大约 500B)。
const MaxPacketLength = 64 * 1024
// Marshal 编码消息头。
func (h *Header) Marshal() []byte {
b := make([]byte, HeaderLen)
binary.BigEndian.PutUint32(b[0:4], h.TotalLength)
binary.BigEndian.PutUint32(b[4:8], uint32(h.CommandID))
binary.BigEndian.PutUint32(b[8:12], h.SequenceID)
return b
}
// ParseHeader 从字节解析消息头。
func ParseHeader(b []byte) (*Header, error) {
if len(b) < HeaderLen {
return nil, ErrBadHeader
}
h := &Header{
TotalLength: binary.BigEndian.Uint32(b[0:4]),
CommandID: CommandID(binary.BigEndian.Uint32(b[4:8])),
SequenceID: binary.BigEndian.Uint32(b[8:12]),
}
if h.TotalLength < HeaderLen || h.TotalLength > MaxPacketLength {
return nil, fmt.Errorf("%w: total_length=%d", ErrBadHeader, h.TotalLength)
}
return h, nil
}
// ReadPacket 从流读一个完整 CMPP 包:先读 12 字节头,再读包体;返回头与体。
func ReadPacket(r io.Reader) (*Header, []byte, error) {
head := make([]byte, HeaderLen)
if _, err := io.ReadFull(r, head); err != nil {
return nil, nil, err
}
h, err := ParseHeader(head)
if err != nil {
return nil, nil, err
}
body := make([]byte, h.TotalLength-HeaderLen)
if _, err := io.ReadFull(r, body); err != nil {
return nil, nil, err
}
return h, body, nil
}
// WritePacket 写一个完整包(头+体)。
func WritePacket(w io.Writer, h *Header, body []byte) error {
h.TotalLength = uint32(HeaderLen + len(body))
if _, err := w.Write(append(h.Marshal(), body...)); err != nil {
return err
}
return nil
}