400 lines
13 KiB
Go
400 lines
13 KiB
Go
// server.go CMPP 2.0 服务端(Day 47:客户接入)。平台作为 ISMG 侧接受企业客户
|
|
// TCP 长连接:Connect 鉴权(复用 VerifyAuth)→Submit 提交(合包前入口)→
|
|
// ActiveTest/Terminate 链路维护。业务逻辑经 ServerHandler 回调注入(access 服务)。
|
|
package cmpp
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"sync"
|
|
"time"
|
|
|
|
"go-sms/internal/pkg/logger"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// ServerConfig 服务端配置。
|
|
type ServerConfig struct {
|
|
Addr string // 监听地址(:17890;空=不启用)
|
|
LoginTimeout time.Duration // Connect 握手超时(默认 30s)
|
|
IdleTimeout time.Duration // 读空闲超时(默认 120s;≥2 个心跳周期)
|
|
}
|
|
|
|
func (c *ServerConfig) withDefaults() {
|
|
if c.LoginTimeout <= 0 {
|
|
c.LoginTimeout = 30 * time.Second
|
|
}
|
|
if c.IdleTimeout <= 0 {
|
|
c.IdleTimeout = 120 * time.Second
|
|
}
|
|
}
|
|
|
|
// ConnectStatus CMPP 2.0 Connect_Resp 状态码。
|
|
const (
|
|
ConnectOK byte = 0 // 成功
|
|
ConnectBadPack byte = 1 // 结构非法
|
|
ConnectBadAuth byte = 2 // 账号密码错误
|
|
ConnectBadVer byte = 3 // 版本过高
|
|
ConnectBadIP byte = 4 // 非法 IP(Day47 扩展语义:白名单拒绝)
|
|
ConnectDisabled byte = 5 // 账号停用(Day47 扩展语义)
|
|
ConnectTooMany byte = 8 // 连接数超限(Day62 扩展语义:保留码 0x8,CMPP 无专用码)
|
|
)
|
|
|
|
// SubmitResultCode Submit_Resp Result 业务码(CMPP 2.0:0 成功;8~10 链路/流量;自定义 11+)。
|
|
const (
|
|
SubmitOK byte = 0
|
|
SubmitBadStruct byte = 1 // 包结构错误
|
|
SubmitFlowCtrl byte = 8 // Day62:单链限速(标准语义:流量控制错,客户端应退避)
|
|
SubmitBadCode byte = 9 // Day47 自定义:通道号前缀不匹配
|
|
SubmitRejected byte = 10 // Day47 自定义:业务拒绝(校验/余额/审核)
|
|
)
|
|
|
|
// ServerHandler 业务回调(由 access 服务实现)。
|
|
type ServerHandler interface {
|
|
// Connect 鉴权:sourceAddr+CMPP authenticator;返回 ConnectResp 状态码。
|
|
Connect(sourceAddr string, ts uint32, authenticator []byte, clientIP string) byte
|
|
// Submit 短信提交:返回平台分配 MsgID 与 Result(0=受理成功)。
|
|
// content=已解码正文(长短信片已剥 6B 拼接 UDH);udh 非 nil=长短信片
|
|
// (拼接头信息,由接入层聚合合并为一条逻辑短信——批次 2278141 修复);
|
|
// msgFmt=CMPP 编码(Day 70 计费口径分流:UCS2=8 按 2B/码元)。
|
|
Submit(sourceAddr, srcID string, dest []string, content string,
|
|
udh *UDHInfo, registeredDelivery uint8, msgFmt uint8) (msgID uint64, result byte)
|
|
}
|
|
|
|
// ConnLimiter 可选接口(Day 62):账号级最大连接数(≤0=不限)。
|
|
// access 服务实现——读 account_config.cmpp_max_conns,0 回退服务端系统默认。
|
|
type ConnLimiter interface {
|
|
ConnLimit(sourceAddr string) int
|
|
}
|
|
|
|
// ISMGSecretSource 可选接口(Issue#3 加固):提供账号共享密钥——ConnectResp 的
|
|
// AuthenticatorISMG=MD5(Status+AuthenticatorSource+shared_secret) 按规范掺入;
|
|
// 不实现=空串(旧口径,严格校验 ISMG 的客户端会判失败)。
|
|
type ISMGSecretSource interface {
|
|
ISMGSecret(sourceAddr string) string
|
|
}
|
|
|
|
// SubmitRateLimiter 可选接口(Day 62):账号级单链提交限速 条/s(≤0=不限)。
|
|
type SubmitRateLimiter interface {
|
|
SubmitRateLimit(sourceAddr string) int
|
|
}
|
|
|
|
// rateWindow 单链 1s 窗口限速(Day 62;仅会话 goroutine 串行访问,无需加锁)。
|
|
type rateWindow struct {
|
|
limit int // 窗口上限(0=不限)
|
|
start time.Time // 当前窗口起点
|
|
count int // 窗口内已放行条数
|
|
}
|
|
|
|
// allow 窗口内放行至 limit 条(0=不限)。
|
|
func (rw *rateWindow) allow(now time.Time) bool {
|
|
if rw.limit <= 0 {
|
|
return true
|
|
}
|
|
if now.Sub(rw.start) >= time.Second {
|
|
rw.start, rw.count = now, 0
|
|
}
|
|
if rw.count >= rw.limit {
|
|
return false
|
|
}
|
|
rw.count++
|
|
return true
|
|
}
|
|
|
|
// session 已鉴权客户会话(Day 61:Deliver 下发目标)。
|
|
// 写互斥:会话循环应答(Submit_Resp/ActiveTest_Resp)与 PushDeliver 并发写
|
|
// 同一 TCP 连接,裸并发会交错粘包——所有下行统一经 write 加锁。
|
|
type session struct {
|
|
conn net.Conn
|
|
account string // 注册后回填(SourceAddr;Deliver 目标键)
|
|
mu sync.Mutex
|
|
seq uint32 // Deliver 序号(连接内单调递增)
|
|
rate rateWindow // Day 62:单链提交限速窗口
|
|
}
|
|
|
|
// write 加锁写一个完整 PDU。
|
|
func (ss *session) write(h *Header, body []byte) error {
|
|
ss.mu.Lock()
|
|
defer ss.mu.Unlock()
|
|
return WritePacket(ss.conn, h, body)
|
|
}
|
|
|
|
// nextSeq 连接内 Deliver 序号自增。
|
|
func (ss *session) nextSeq() uint32 {
|
|
ss.seq++
|
|
return ss.seq
|
|
}
|
|
|
|
// Server CMPP TCP 服务端。
|
|
type Server struct {
|
|
cfg ServerConfig
|
|
h ServerHandler
|
|
|
|
mu sync.Mutex
|
|
ln net.Listener
|
|
conns map[net.Conn]struct{}
|
|
sessions map[string][]*session // sourceAddr → 活跃会话(Deliver 下发目标)
|
|
done chan struct{}
|
|
}
|
|
|
|
// NewServer 构造。
|
|
func NewServer(cfg ServerConfig, h ServerHandler) *Server {
|
|
cfg.withDefaults()
|
|
return &Server{cfg: cfg, h: h, conns: map[net.Conn]struct{}{},
|
|
sessions: map[string][]*session{}, done: make(chan struct{})}
|
|
}
|
|
|
|
// Addr 实际监听地址(Listen 后有效;测试用 :0 端口)。
|
|
func (s *Server) Addr() string {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.ln == nil {
|
|
return ""
|
|
}
|
|
return s.ln.Addr().String()
|
|
}
|
|
|
|
// ListenAndServe 阻塞监听直至 ctx 结束或 Close。
|
|
func (s *Server) ListenAndServe(ctx context.Context) error {
|
|
ln, err := net.Listen("tcp", s.cfg.Addr)
|
|
if err != nil {
|
|
return fmt.Errorf("cmpp server: 监听失败: %w", err)
|
|
}
|
|
s.mu.Lock()
|
|
s.ln = ln
|
|
s.mu.Unlock()
|
|
defer func() { _ = ln.Close() }()
|
|
|
|
go func() {
|
|
select {
|
|
case <-ctx.Done():
|
|
s.Close()
|
|
case <-s.done:
|
|
}
|
|
}()
|
|
|
|
for {
|
|
conn, err := ln.Accept()
|
|
if err != nil {
|
|
select {
|
|
case <-s.done:
|
|
return nil // 主动关闭
|
|
default:
|
|
return fmt.Errorf("cmpp server: accept 退出: %w", err)
|
|
}
|
|
}
|
|
s.mu.Lock()
|
|
s.conns[conn] = struct{}{}
|
|
s.mu.Unlock()
|
|
go s.handleConn(ctx, conn)
|
|
}
|
|
}
|
|
|
|
// Close 关闭监听与全部客户连接。
|
|
func (s *Server) Close() {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
select {
|
|
case <-s.done:
|
|
return
|
|
default:
|
|
close(s.done)
|
|
}
|
|
if s.ln != nil {
|
|
_ = s.ln.Close()
|
|
}
|
|
for c := range s.conns {
|
|
_ = c.Close()
|
|
}
|
|
}
|
|
|
|
// dropConn 连接退出登记(顺带注销会话)。
|
|
func (s *Server) dropConn(conn net.Conn, ss *session) {
|
|
s.mu.Lock()
|
|
delete(s.conns, conn)
|
|
if ss != nil {
|
|
s.unregisterSessionLocked(ss.sourceAddr(), ss)
|
|
}
|
|
s.mu.Unlock()
|
|
_ = conn.Close()
|
|
}
|
|
|
|
// sourceAddr 反查会话账号(注册时记名;零值见 registerSession)。
|
|
func (ss *session) sourceAddr() string { return ss.account }
|
|
|
|
// registerSessionBounded 会话登记+连接数上限原子检查(Day 62)。
|
|
// 检查与追加同持 s.mu,防并发 Connect 超卖名额;超限返回 false 且不登记。
|
|
// maxConns ≤0 =不限(直接登记)。
|
|
func (s *Server) registerSessionBounded(sourceAddr string, ss *session, maxConns int) bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if maxConns > 0 && len(s.sessions[sourceAddr]) >= maxConns {
|
|
return false
|
|
}
|
|
ss.account = sourceAddr
|
|
s.sessions[sourceAddr] = append(s.sessions[sourceAddr], ss)
|
|
return true
|
|
}
|
|
|
|
// unregisterSessionLocked 会话注销(调用方持锁)。
|
|
func (s *Server) unregisterSessionLocked(sourceAddr string, ss *session) {
|
|
list := s.sessions[sourceAddr]
|
|
for i, cur := range list {
|
|
if cur == ss {
|
|
s.sessions[sourceAddr] = append(list[:i], list[i+1:]...)
|
|
break
|
|
}
|
|
}
|
|
if len(s.sessions[sourceAddr]) == 0 {
|
|
delete(s.sessions, sourceAddr)
|
|
}
|
|
}
|
|
|
|
// PushDeliver 向账号全部活跃连接下发 Deliver(状态报告/上行消息)。
|
|
// 返回实际送达连接数;账号离线返回 0(尽力而为口径:离线不缓存,P1 离线补推)。
|
|
// 任一连接写失败即拆除该连接(由 dropConn 兜底回收,此处仅触发关闭)。
|
|
func (s *Server) PushDeliver(sourceAddr string, d *Deliver) int {
|
|
body, err := MarshalDeliver(d)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
s.mu.Lock()
|
|
list := append([]*session(nil), s.sessions[sourceAddr]...)
|
|
s.mu.Unlock()
|
|
sent := 0
|
|
for _, ss := range list {
|
|
if werr := ss.write(&Header{CommandID: CmdDeliver, SequenceID: ss.nextSeq()}, body); werr == nil {
|
|
sent++
|
|
} else {
|
|
// 写失败:连接已不可用,主动拆除(会话注销由 dropConn 完成)。
|
|
_ = ss.conn.Close()
|
|
}
|
|
}
|
|
return sent
|
|
}
|
|
|
|
// handleConn 单连接会话:首包 Connect(超时断)→循环 Submit/ActiveTest/Terminate。
|
|
func (s *Server) handleConn(ctx context.Context, conn net.Conn) {
|
|
ss := &session{conn: conn}
|
|
defer s.dropConn(conn, ss)
|
|
ip := remoteIP(conn)
|
|
// Issue#3 联调补盲:TCP 到达即留痕(此前 Connect 成功零日志,客户「连没连上」不可追溯;
|
|
// 配合 scripts/cmpp-capture.sh 抓包分析双通道定位)。
|
|
logger.L().Info("cmpp_conn_accepted", zap.String("client_ip", ip))
|
|
|
|
// ---- Connect 握手 ----
|
|
_ = conn.SetReadDeadline(time.Now().Add(s.cfg.LoginTimeout))
|
|
h, body, err := ReadPacket(conn)
|
|
if err != nil || h.CommandID != CmdConnect {
|
|
return // 非 Connect 首包/超时:直接断
|
|
}
|
|
sourceAddr, authenticator, ts, perr := ParseConnect(body)
|
|
status := ConnectBadPack
|
|
if perr == nil {
|
|
status = s.h.Connect(sourceAddr, ts, authenticator, ip)
|
|
}
|
|
// Issue#3 加固:按客户端 Connect.Version 协商应答布局(≥0x30 回 3.0 的
|
|
// 1B Status/18B;否则 2.0 的 4B Status/21B)——版本字节在包体 offset 22。
|
|
ver := byte(0x20)
|
|
if len(body) >= 23 && body[22] >= 0x30 {
|
|
ver = body[22]
|
|
}
|
|
// Issue#3 加固:ISMG 鉴权串按规范掺 shared_secret(可选接口;不实现=空串)。
|
|
smsSecret := ""
|
|
if ss, ok := s.h.(ISMGSecretSource); ok {
|
|
smsSecret = ss.ISMGSecret(sourceAddr)
|
|
}
|
|
// Day 62:鉴权通过后先占会话名额(账号级连接数上限,可选接口;持锁原子
|
|
// 检查+登记防并发超卖),超限回保留码 0x8 后断链。
|
|
if status == ConnectOK {
|
|
maxConns := 0
|
|
if cl, ok := s.h.(ConnLimiter); ok {
|
|
maxConns = cl.ConnLimit(sourceAddr)
|
|
}
|
|
if !s.registerSessionBounded(sourceAddr, ss, maxConns) {
|
|
logger.L().Warn("cmpp_conn_limit_rejected",
|
|
zap.String("source_addr", sourceAddr), zap.Int("max_conns", maxConns))
|
|
status = ConnectTooMany
|
|
}
|
|
}
|
|
resp := &ConnectResp{Status: status, Secret: smsSecret,
|
|
AuthenticatorClient: authenticator, ClientVersion: ver}
|
|
if werr := WritePacket(conn, &Header{CommandID: CmdConnectResp, SequenceID: h.SequenceID}, resp.Marshal()); werr != nil {
|
|
return
|
|
}
|
|
if status != ConnectOK {
|
|
return // 鉴权失败/连接超限:应答后断链
|
|
}
|
|
// Day 62:账号级单链限速(可选接口;窗口超限 Submit 回 result=8 流量控制)。
|
|
if rl, ok := s.h.(SubmitRateLimiter); ok {
|
|
ss.rate.limit = rl.SubmitRateLimit(sourceAddr)
|
|
}
|
|
// Issue#3 联调补盲:Connect 成功留痕(账号/IP/客户端声明版本——与抓包时间线互证)。
|
|
logger.L().Info("cmpp_conn_ok",
|
|
zap.String("source_addr", sourceAddr), zap.String("client_ip", ip),
|
|
zap.Uint8("ver", ver))
|
|
|
|
// ---- 会话循环 ----
|
|
for {
|
|
_ = conn.SetReadDeadline(time.Now().Add(s.cfg.IdleTimeout))
|
|
h, body, err := ReadPacket(conn)
|
|
if err != nil {
|
|
return
|
|
}
|
|
switch h.CommandID {
|
|
case CmdSubmit:
|
|
s.handleSubmit(ss, h, body, sourceAddr)
|
|
case CmdActiveTest:
|
|
_ = ss.write(&Header{CommandID: CmdActiveTestResp, SequenceID: h.SequenceID}, ActiveTestResp(0))
|
|
case CmdDeliverResp:
|
|
// Day 61:客户端对下发的 Deliver 的应答——按规范吸收即可(序号对账 P1)。
|
|
case CmdTerminate:
|
|
_ = ss.write(&Header{CommandID: CmdTerminateResp, SequenceID: h.SequenceID}, nil)
|
|
return
|
|
default:
|
|
return // 未知命令:保守断链
|
|
}
|
|
}
|
|
}
|
|
|
|
// handleSubmit 解析并受理 Submit。
|
|
func (s *Server) handleSubmit(ss *session, h *Header, body []byte, sourceAddr string) {
|
|
// Day 62:单链限速——1s 窗口超限回 result=8(流量控制错),客户端按协议退避重试。
|
|
if !ss.rate.allow(time.Now()) {
|
|
_ = ss.write(&Header{CommandID: CmdSubmitResp, SequenceID: h.SequenceID},
|
|
(&SubmitResp{Result: SubmitFlowCtrl}).Marshal())
|
|
return
|
|
}
|
|
req, err := ParseSubmitReq(body)
|
|
if err != nil {
|
|
_ = ss.write(&Header{CommandID: CmdSubmitResp, SequenceID: h.SequenceID},
|
|
(&SubmitResp{Result: SubmitBadStruct}).Marshal())
|
|
return
|
|
}
|
|
// 长短信片(批次 2278141 修复):TP_udhi=1 时先按字节剥离 6B 拼接 UDH
|
|
// 再解码——原实现整包解码,UDH 头被当正文成片首乱码且拼接信息丢失;
|
|
// 非拼接形态(其它 IEI)原样透传,行为不变。
|
|
raw, udh := req.Content, (*UDHInfo)(nil)
|
|
if req.TPUdhi == 1 {
|
|
udh, raw = ParseUDH(req.Content)
|
|
}
|
|
content, cerr := DecodeContent(raw, req.MsgFmt)
|
|
if cerr != nil {
|
|
_ = ss.write(&Header{CommandID: CmdSubmitResp, SequenceID: h.SequenceID},
|
|
(&SubmitResp{Result: SubmitBadStruct}).Marshal())
|
|
return
|
|
}
|
|
msgID, result := s.h.Submit(sourceAddr, req.SrcID, req.DestTerminalIDs, content, udh, req.RegisteredDelivery, req.MsgFmt)
|
|
_ = ss.write(&Header{CommandID: CmdSubmitResp, SequenceID: h.SequenceID},
|
|
(&SubmitResp{MsgID: msgID, Result: result}).Marshal())
|
|
}
|
|
|
|
// remoteIP 对端 IP(去端口)。
|
|
func remoteIP(conn net.Conn) string {
|
|
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
|
|
return addr.IP.String()
|
|
}
|
|
return conn.RemoteAddr().String()
|
|
}
|