session.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. package modem
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "strings"
  9. "sync"
  10. "time"
  11. )
  12. type Transport interface {
  13. io.ReadWriteCloser
  14. Drain() error
  15. ResetInputBuffer() error
  16. SetReadTimeout(time.Duration) error
  17. }
  18. type SessionOptions struct {
  19. ReadTimeout time.Duration
  20. CommandTimeout time.Duration
  21. MaxURCs int
  22. }
  23. func (options SessionOptions) withDefaults() SessionOptions {
  24. if options.ReadTimeout <= 0 {
  25. options.ReadTimeout = 100 * time.Millisecond
  26. }
  27. if options.CommandTimeout <= 0 {
  28. options.CommandTimeout = 3 * time.Second
  29. }
  30. if options.MaxURCs <= 0 {
  31. options.MaxURCs = 256
  32. }
  33. return options
  34. }
  35. // Session serializes commands for one physical AT port. Reading is intentionally
  36. // performed under the same mutex as writing: this prevents two callers from
  37. // consuming each other's responses while still allowing interleaved URCs to be
  38. // separated and queued.
  39. type Session struct {
  40. mu sync.Mutex
  41. transport Transport
  42. options SessionOptions
  43. readBuf []byte
  44. urcs []string
  45. closed bool
  46. poisoned bool
  47. }
  48. // PoisonedClient is implemented by Session. A poisoned session has hit a
  49. // transport-fatal error (a failed write/drain/read or a closed serial line);
  50. // the underlying fd is wedged and every subsequent command reuses the corpse.
  51. // AT-level failures (CommandError, command timeout) do NOT poison — the
  52. // transport is still healthy there, so reopening would only destroy a good
  53. // session over a transient +CME ERROR.
  54. type PoisonedClient interface {
  55. Poisoned() bool
  56. }
  57. func NewSession(transport Transport, options SessionOptions) (*Session, error) {
  58. if transport == nil {
  59. return nil, errors.New("modem: transport is required")
  60. }
  61. options = options.withDefaults()
  62. if err := transport.SetReadTimeout(options.ReadTimeout); err != nil {
  63. return nil, fmt.Errorf("set serial read timeout: %w", err)
  64. }
  65. return &Session{
  66. transport: transport,
  67. options: options,
  68. }, nil
  69. }
  70. // Poisoned reports whether this session has hit a transport-fatal error and
  71. // should be discarded rather than reused. It is safe to call concurrently.
  72. func (session *Session) Poisoned() bool {
  73. session.mu.Lock()
  74. defer session.mu.Unlock()
  75. return session.poisoned || session.closed
  76. }
  77. func (session *Session) Execute(ctx context.Context, command string) (Response, error) {
  78. command, err := normalizeATCommand(command)
  79. if err != nil {
  80. return Response{}, err
  81. }
  82. ctx, cancel := session.commandContext(ctx)
  83. defer cancel()
  84. session.mu.Lock()
  85. defer session.mu.Unlock()
  86. if session.closed {
  87. return Response{}, ErrSessionClosed
  88. }
  89. return session.executeLocked(ctx, command)
  90. }
  91. // ExecutePrompt executes the controlled two-phase AT+CMGS transaction. It does
  92. // not release the session mutex between the command, the '>' prompt, the
  93. // payload terminator, and the final result.
  94. func (session *Session) ExecutePrompt(
  95. ctx context.Context,
  96. command string,
  97. payload []byte,
  98. ) (Response, error) {
  99. command, err := normalizeATCommand(command)
  100. if err != nil {
  101. return Response{}, err
  102. }
  103. if !strings.HasPrefix(strings.ToUpper(command), "AT+CMGS=") {
  104. return Response{}, errors.New("modem: prompt command must be AT+CMGS")
  105. }
  106. if len(payload) > 8192 {
  107. return Response{}, errors.New("modem: prompt payload exceeds 8192 bytes")
  108. }
  109. if bytes.IndexByte(payload, 0x1a) >= 0 || bytes.IndexByte(payload, 0x1b) >= 0 {
  110. return Response{}, errors.New("modem: prompt payload contains a terminator")
  111. }
  112. ctx, cancel := session.commandContext(ctx)
  113. defer cancel()
  114. session.mu.Lock()
  115. defer session.mu.Unlock()
  116. if session.closed {
  117. return Response{}, ErrSessionClosed
  118. }
  119. return session.executePromptLocked(ctx, command, payload)
  120. }
  121. func (session *Session) commandContext(ctx context.Context) (context.Context, context.CancelFunc) {
  122. if ctx == nil {
  123. ctx = context.Background()
  124. }
  125. if _, ok := ctx.Deadline(); ok || session.options.CommandTimeout <= 0 {
  126. return context.WithCancel(ctx)
  127. }
  128. return context.WithTimeout(ctx, session.options.CommandTimeout)
  129. }
  130. func (session *Session) executeLocked(ctx context.Context, command string) (Response, error) {
  131. started := time.Now()
  132. response := Response{Command: command}
  133. if err := ctx.Err(); err != nil {
  134. return response, err
  135. }
  136. if err := writeAll(session.transport, []byte(command+"\r")); err != nil {
  137. session.poisonLocked()
  138. return response, fmt.Errorf("write %s: %w", command, err)
  139. }
  140. if err := session.transport.Drain(); err != nil {
  141. session.poisonLocked()
  142. return response, fmt.Errorf("drain %s: %w", command, err)
  143. }
  144. return session.readFinalLocked(ctx, started, command, "", response)
  145. }
  146. // poisonLocked marks the session unusable after a transport-fatal error. Held
  147. // under session.mu by the caller; idempotent.
  148. func (session *Session) poisonLocked() {
  149. session.poisoned = true
  150. }
  151. func (session *Session) executePromptLocked(
  152. ctx context.Context,
  153. command string,
  154. payload []byte,
  155. ) (Response, error) {
  156. started := time.Now()
  157. response := Response{Command: command}
  158. if err := ctx.Err(); err != nil {
  159. return response, err
  160. }
  161. if err := writeAll(session.transport, []byte(command+"\r")); err != nil {
  162. session.poisonLocked()
  163. return response, fmt.Errorf("write %s: %w", command, err)
  164. }
  165. if err := session.transport.Drain(); err != nil {
  166. session.poisonLocked()
  167. return response, fmt.Errorf("drain %s: %w", command, err)
  168. }
  169. if err := session.waitPromptLocked(ctx, command, &response); err != nil {
  170. response.Duration = time.Since(started)
  171. return response, session.normalizeReadError(command, err)
  172. }
  173. if err := ctx.Err(); err != nil {
  174. session.abortPromptLocked()
  175. response.Duration = time.Since(started)
  176. return response, err
  177. }
  178. if err := writeAll(session.transport, payload); err != nil {
  179. session.poisonLocked()
  180. session.abortPromptLocked()
  181. response.Duration = time.Since(started)
  182. return response, fmt.Errorf("write %s payload: %w", command, err)
  183. }
  184. if err := writeAll(session.transport, []byte{0x1a}); err != nil {
  185. session.poisonLocked()
  186. session.abortPromptLocked()
  187. response.Duration = time.Since(started)
  188. return response, fmt.Errorf("terminate %s payload: %w", command, err)
  189. }
  190. if err := session.transport.Drain(); err != nil {
  191. session.poisonLocked()
  192. response.Duration = time.Since(started)
  193. return response, fmt.Errorf("drain %s payload: %w", command, err)
  194. }
  195. return session.readFinalLocked(ctx, started, command, string(payload), response)
  196. }
  197. func (session *Session) readFinalLocked(
  198. ctx context.Context,
  199. started time.Time,
  200. command string,
  201. payloadEcho string,
  202. response Response,
  203. ) (Response, error) {
  204. expectedPrefix := expectedResponsePrefix(command)
  205. for {
  206. line, err := session.readLineLocked(ctx)
  207. if err != nil {
  208. response.Duration = time.Since(started)
  209. return response, session.normalizeReadError(command, err)
  210. }
  211. line = strings.TrimSpace(strings.Trim(line, "\x00"))
  212. if line == "" || strings.EqualFold(line, command) ||
  213. (payloadEcho != "" && line == payloadEcho) {
  214. continue
  215. }
  216. if isFinalResult(line) {
  217. response.Final = line
  218. response.Duration = time.Since(started)
  219. if response.OK() {
  220. return response, nil
  221. }
  222. return response, &CommandError{
  223. Command: command,
  224. Final: line,
  225. Lines: append([]string(nil), response.Lines...),
  226. }
  227. }
  228. if isURC(line) && !strings.HasPrefix(strings.ToUpper(line), expectedPrefix) {
  229. response.URCs = append(response.URCs, line)
  230. session.enqueueURCLocked(line)
  231. continue
  232. }
  233. response.Lines = append(response.Lines, line)
  234. }
  235. }
  236. func (session *Session) waitPromptLocked(
  237. ctx context.Context,
  238. command string,
  239. response *Response,
  240. ) error {
  241. expectedPrefix := expectedResponsePrefix(command)
  242. for {
  243. if index := promptIndex(session.readBuf); index >= 0 {
  244. prefix := string(session.readBuf[:index])
  245. session.readBuf = session.readBuf[index+1:]
  246. for len(session.readBuf) > 0 &&
  247. (session.readBuf[0] == ' ' || session.readBuf[0] == '\t') {
  248. session.readBuf = session.readBuf[1:]
  249. }
  250. for _, line := range strings.FieldsFunc(prefix, func(character rune) bool {
  251. return character == '\r' || character == '\n'
  252. }) {
  253. if err := session.consumePromptLineLocked(
  254. command,
  255. expectedPrefix,
  256. line,
  257. response,
  258. ); err != nil {
  259. return err
  260. }
  261. }
  262. return nil
  263. }
  264. if line, ok := popLine(&session.readBuf); ok {
  265. if err := session.consumePromptLineLocked(
  266. command,
  267. expectedPrefix,
  268. line,
  269. response,
  270. ); err != nil {
  271. return err
  272. }
  273. continue
  274. }
  275. if err := ctx.Err(); err != nil {
  276. return err
  277. }
  278. buffer := make([]byte, 1024)
  279. count, err := session.transport.Read(buffer)
  280. if count > 0 {
  281. session.readBuf = append(session.readBuf, buffer[:count]...)
  282. continue
  283. }
  284. if err != nil {
  285. if errors.Is(err, io.EOF) && session.closed {
  286. return ErrSessionClosed
  287. }
  288. session.poisonLocked()
  289. return fmt.Errorf("read serial prompt: %w", err)
  290. }
  291. }
  292. }
  293. func promptIndex(buffer []byte) int {
  294. for index, character := range buffer {
  295. if character != '>' {
  296. continue
  297. }
  298. if index == 0 || buffer[index-1] == '\r' || buffer[index-1] == '\n' {
  299. return index
  300. }
  301. }
  302. return -1
  303. }
  304. func (session *Session) consumePromptLineLocked(
  305. command string,
  306. expectedPrefix string,
  307. line string,
  308. response *Response,
  309. ) error {
  310. line = strings.TrimSpace(strings.Trim(line, "\x00"))
  311. if line == "" || strings.EqualFold(line, command) {
  312. return nil
  313. }
  314. if isFinalResult(line) {
  315. response.Final = line
  316. if response.OK() {
  317. return fmt.Errorf("%w: %s", ErrPromptNotReceived, command)
  318. }
  319. return &CommandError{
  320. Command: command,
  321. Final: line,
  322. Lines: append([]string(nil), response.Lines...),
  323. }
  324. }
  325. if isURC(line) && !strings.HasPrefix(strings.ToUpper(line), expectedPrefix) {
  326. response.URCs = append(response.URCs, line)
  327. session.enqueueURCLocked(line)
  328. return nil
  329. }
  330. response.Lines = append(response.Lines, line)
  331. return nil
  332. }
  333. func (session *Session) normalizeReadError(command string, err error) error {
  334. if errors.Is(err, context.DeadlineExceeded) ||
  335. errors.Is(err, context.Canceled) {
  336. _ = session.transport.ResetInputBuffer()
  337. session.readBuf = nil
  338. if errors.Is(err, context.DeadlineExceeded) {
  339. return fmt.Errorf("%w: %s", ErrCommandTimeout, command)
  340. }
  341. }
  342. return err
  343. }
  344. func (session *Session) abortPromptLocked() {
  345. _ = writeAll(session.transport, []byte{0x1b})
  346. _ = session.transport.Drain()
  347. _ = session.transport.ResetInputBuffer()
  348. session.readBuf = nil
  349. }
  350. // WaitURC waits for an unsolicited result matching predicate. Non-matching URCs
  351. // remain queued for another consumer.
  352. func (session *Session) WaitURC(
  353. ctx context.Context,
  354. predicate func(string) bool,
  355. ) (string, error) {
  356. if predicate == nil {
  357. return "", errors.New("modem: URC predicate is required")
  358. }
  359. if ctx == nil {
  360. ctx = context.Background()
  361. }
  362. session.mu.Lock()
  363. defer session.mu.Unlock()
  364. if session.closed {
  365. return "", ErrSessionClosed
  366. }
  367. for index, line := range session.urcs {
  368. if predicate(line) {
  369. session.urcs = append(session.urcs[:index], session.urcs[index+1:]...)
  370. return line, nil
  371. }
  372. }
  373. for {
  374. line, err := session.readLineLocked(ctx)
  375. if err != nil {
  376. return "", err
  377. }
  378. line = strings.TrimSpace(strings.Trim(line, "\x00"))
  379. if line == "" {
  380. continue
  381. }
  382. if predicate(line) {
  383. return line, nil
  384. }
  385. session.enqueueURCLocked(line)
  386. }
  387. }
  388. func (session *Session) enqueueURCLocked(line string) {
  389. if len(session.urcs) >= session.options.MaxURCs {
  390. copy(session.urcs, session.urcs[1:])
  391. session.urcs[len(session.urcs)-1] = line
  392. return
  393. }
  394. session.urcs = append(session.urcs, line)
  395. }
  396. func (session *Session) readLineLocked(ctx context.Context) (string, error) {
  397. for {
  398. if line, ok := popLine(&session.readBuf); ok {
  399. return line, nil
  400. }
  401. if err := ctx.Err(); err != nil {
  402. return "", err
  403. }
  404. buffer := make([]byte, 1024)
  405. count, err := session.transport.Read(buffer)
  406. if count > 0 {
  407. session.readBuf = append(session.readBuf, buffer[:count]...)
  408. continue
  409. }
  410. if err != nil {
  411. if errors.Is(err, io.EOF) && session.closed {
  412. return "", ErrSessionClosed
  413. }
  414. session.poisonLocked()
  415. return "", fmt.Errorf("read serial response: %w", err)
  416. }
  417. }
  418. }
  419. func popLine(buffer *[]byte) (string, bool) {
  420. data := *buffer
  421. for index, character := range data {
  422. if character != '\r' && character != '\n' {
  423. continue
  424. }
  425. line := string(data[:index])
  426. next := index + 1
  427. for next < len(data) && (data[next] == '\r' || data[next] == '\n') {
  428. next++
  429. }
  430. *buffer = data[next:]
  431. return line, true
  432. }
  433. return "", false
  434. }
  435. func normalizeATCommand(command string) (string, error) {
  436. command = strings.TrimSpace(command)
  437. if command == "" {
  438. return "", errors.New("modem: AT command is empty")
  439. }
  440. if len(command) > 512 {
  441. return "", errors.New("modem: AT command exceeds 512 bytes")
  442. }
  443. if strings.ContainsAny(command, "\r\n\x00") {
  444. return "", errors.New("modem: AT command contains a control delimiter")
  445. }
  446. if !strings.HasPrefix(strings.ToUpper(command), "AT") {
  447. return "", errors.New("modem: command must start with AT")
  448. }
  449. return command, nil
  450. }
  451. func expectedResponsePrefix(command string) string {
  452. upper := strings.ToUpper(strings.TrimSpace(command))
  453. if strings.HasPrefix(upper, "AT+CUSD=") {
  454. // +CUSD is asynchronous even when it arrives before the command's OK.
  455. return "\x00"
  456. }
  457. body := strings.TrimPrefix(upper, "AT")
  458. if body == "" || body == "I" {
  459. return "\x00"
  460. }
  461. end := len(body)
  462. for index, character := range body {
  463. if character == '?' || character == '=' || character == ',' {
  464. end = index
  465. break
  466. }
  467. }
  468. name := body[:end]
  469. if name == "" {
  470. return "\x00"
  471. }
  472. return name + ":"
  473. }
  474. func isFinalResult(line string) bool {
  475. upper := strings.ToUpper(strings.TrimSpace(line))
  476. return upper == "OK" ||
  477. upper == "ERROR" ||
  478. upper == "NO CARRIER" ||
  479. upper == "BUSY" ||
  480. upper == "NO ANSWER" ||
  481. strings.HasPrefix(upper, "+CME ERROR:") ||
  482. strings.HasPrefix(upper, "+CMS ERROR:")
  483. }
  484. func isURC(line string) bool {
  485. upper := strings.ToUpper(strings.TrimSpace(line))
  486. if upper == "RING" ||
  487. upper == "RDY" ||
  488. upper == "CALL READY" ||
  489. upper == "SMS READY" ||
  490. upper == "PB DONE" {
  491. return true
  492. }
  493. for _, prefix := range []string{
  494. "+CMTI:",
  495. "+CMT:",
  496. "+CDS:",
  497. "+CREG:",
  498. "+CGREG:",
  499. "+CEREG:",
  500. "+CUSD:",
  501. "+CLIP:",
  502. "+CRING:",
  503. "+QIND:",
  504. "+QIURC:",
  505. "+QSIMSTAT:",
  506. "+QUSIM:",
  507. "+QNWINFO:",
  508. } {
  509. if strings.HasPrefix(upper, prefix) {
  510. return true
  511. }
  512. }
  513. return false
  514. }
  515. func writeAll(writer io.Writer, payload []byte) error {
  516. for len(payload) > 0 {
  517. count, err := writer.Write(payload)
  518. if err != nil {
  519. return err
  520. }
  521. if count <= 0 {
  522. return io.ErrShortWrite
  523. }
  524. if count > len(payload) {
  525. return io.ErrShortWrite
  526. }
  527. payload = payload[count:]
  528. }
  529. return nil
  530. }
  531. func (session *Session) Close() error {
  532. session.mu.Lock()
  533. defer session.mu.Unlock()
  534. if session.closed {
  535. return nil
  536. }
  537. session.closed = true
  538. return session.transport.Close()
  539. }