205 lines
5.1 KiB
Go
205 lines
5.1 KiB
Go
// server.go SMPP 3.4 服务端(Day 47:客户接入)。bind_transceiver 握手(明文密码
|
|
// 常数时间比对)→submit_sm 提交→enquire_link/unbind 链路维护。
|
|
package smpp
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// ServerConfig 服务端配置。
|
|
type ServerConfig struct {
|
|
Addr string // 监听地址(:27775;空=不启用)
|
|
LoginTimeout time.Duration // bind 握手超时(默认 30s)
|
|
IdleTimeout time.Duration // 读空闲超时(默认 120s)
|
|
}
|
|
|
|
func (c *ServerConfig) withDefaults() {
|
|
if c.LoginTimeout <= 0 {
|
|
c.LoginTimeout = 30 * time.Second
|
|
}
|
|
if c.IdleTimeout <= 0 {
|
|
c.IdleTimeout = 120 * time.Second
|
|
}
|
|
}
|
|
|
|
// DataCodingUCS2 UCS-2 编码标识。
|
|
const DataCodingUCS2 uint8 = 0x08
|
|
|
|
// ServerHandler 业务回调(由 access 服务实现)。
|
|
type ServerHandler interface {
|
|
// Bind 鉴权(system_id+password);返回命令状态码(0=OK)。
|
|
Bind(systemID, password, clientIP string) Status
|
|
// SubmitSM 提交:返回 message_id 与状态码(0=受理成功)。
|
|
SubmitSM(systemID, srcAddr, destAddr, content string, registeredDelivery uint8) (string, Status)
|
|
}
|
|
|
|
// Server SMPP TCP 服务端。
|
|
type Server struct {
|
|
cfg ServerConfig
|
|
h ServerHandler
|
|
|
|
mu sync.Mutex
|
|
ln net.Listener
|
|
conns map[net.Conn]struct{}
|
|
done chan struct{}
|
|
}
|
|
|
|
// NewServer 构造。
|
|
func NewServer(cfg ServerConfig, h ServerHandler) *Server {
|
|
cfg.withDefaults()
|
|
return &Server{cfg: cfg, h: h, conns: map[net.Conn]struct{}{}, done: make(chan struct{})}
|
|
}
|
|
|
|
// Addr 实际监听地址。
|
|
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("smpp server: 监听失败: %w", err)
|
|
}
|
|
s.mu.Lock()
|
|
s.ln = ln
|
|
s.mu.Unlock()
|
|
defer 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("smpp server: accept 退出: %w", err)
|
|
}
|
|
}
|
|
s.mu.Lock()
|
|
s.conns[conn] = struct{}{}
|
|
s.mu.Unlock()
|
|
go s.handleConn(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()
|
|
}
|
|
}
|
|
|
|
func (s *Server) dropConn(conn net.Conn) {
|
|
s.mu.Lock()
|
|
delete(s.conns, conn)
|
|
s.mu.Unlock()
|
|
_ = conn.Close()
|
|
}
|
|
|
|
// handleConn 单连接会话。
|
|
func (s *Server) handleConn(conn net.Conn) {
|
|
defer s.dropConn(conn)
|
|
ip := remoteIP(conn)
|
|
|
|
// ---- bind 握手 ----
|
|
_ = conn.SetReadDeadline(time.Now().Add(s.cfg.LoginTimeout))
|
|
h, body, err := ReadPDU(conn)
|
|
if err != nil || h.CommandID != CmdBindTransceiver {
|
|
return
|
|
}
|
|
systemID, password, _, perr := ParseBind(body)
|
|
status := StatusBindFail
|
|
if perr == nil {
|
|
status = s.h.Bind(systemID, password, ip)
|
|
}
|
|
_ = WritePDU(conn, &Header{CommandID: CmdBindTransceiverResp, Status: status, SequenceNo: h.SequenceNo},
|
|
BindResp("go-sms"))
|
|
if status != StatusOK {
|
|
return
|
|
}
|
|
|
|
// ---- 会话循环 ----
|
|
for {
|
|
_ = conn.SetReadDeadline(time.Now().Add(s.cfg.IdleTimeout))
|
|
h, body, err := ReadPDU(conn)
|
|
if err != nil {
|
|
return
|
|
}
|
|
switch h.CommandID {
|
|
case CmdSubmitSM:
|
|
s.handleSubmit(conn, h, body, systemID)
|
|
case CmdEnquireLink:
|
|
_ = WritePDU(conn, &Header{CommandID: CmdEnquireLinkResp, Status: StatusOK, SequenceNo: h.SequenceNo}, nil)
|
|
case CmdUnbind:
|
|
_ = WritePDU(conn, &Header{CommandID: CmdUnbindResp, Status: StatusOK, SequenceNo: h.SequenceNo}, nil)
|
|
return
|
|
default:
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// handleSubmit 解析并受理 submit_sm。
|
|
func (s *Server) handleSubmit(conn net.Conn, h *Header, body []byte, systemID string) {
|
|
req, err := ParseSubmitSMReq(body)
|
|
if err != nil {
|
|
_ = WritePDU(conn, &Header{CommandID: CmdSubmitSMResp, Status: StatusSysErr, SequenceNo: h.SequenceNo}, SubmitResp(""))
|
|
return
|
|
}
|
|
// 编码说明:仅 data_coding=8(UCS2) 明确解码;data_coding=0(MC 缺省)存在编码歧义
|
|
// (Latin-1/GBK 均可能,国内通道惯例多为 GBK),无法可靠自动判别——保守按原样字节
|
|
// 受理,待真实 SMPP 客户接入后按通道方约定扩展(P2,Day52 编码复盘记录)。
|
|
content := string(req.ShortMessage)
|
|
if req.DataCoding == DataCodingUCS2 {
|
|
content, _ = decodeUCS2(req.ShortMessage)
|
|
}
|
|
messageID, status := s.h.SubmitSM(systemID, req.SourceAddr, req.DestAddr, content, req.RegisteredDelivery)
|
|
_ = WritePDU(conn, &Header{CommandID: CmdSubmitSMResp, Status: status, SequenceNo: h.SequenceNo}, SubmitResp(messageID))
|
|
}
|
|
|
|
// decodeUCS2 大端 UCS-2 → UTF-8。
|
|
func decodeUCS2(b []byte) (string, error) {
|
|
out := make([]rune, 0, len(b)/2)
|
|
for i := 0; i+1 < len(b); i += 2 {
|
|
out = append(out, rune(uint16(b[i])<<8|uint16(b[i+1])))
|
|
}
|
|
return string(out), nil
|
|
}
|
|
|
|
// remoteIP 对端 IP(去端口)。
|
|
func remoteIP(conn net.Conn) string {
|
|
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
|
|
return addr.IP.String()
|
|
}
|
|
return conn.RemoteAddr().String()
|
|
}
|