port_linux.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. //go:build linux
  2. package serialtransport
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "strings"
  10. "sync/atomic"
  11. "time"
  12. "golang.org/x/sys/unix"
  13. "hth/internal/protocol"
  14. )
  15. var (
  16. ErrShortWrite = errors.New("short serial write")
  17. ErrDisconnected = errors.New("serial disconnected")
  18. ErrTimeout = errors.New("serial timeout")
  19. ErrAlreadyLocked = errors.New("serial device exclusively locked")
  20. ErrUnexpectedRx = errors.New("unexpected serial bytes before request")
  21. )
  22. type Port struct {
  23. path string
  24. f atomic.Pointer[os.File]
  25. parser *protocol.StreamParser
  26. interByte time.Duration
  27. locked atomic.Bool
  28. }
  29. func (p *Port) file() *os.File {
  30. if p == nil {
  31. return nil
  32. }
  33. return p.f.Load()
  34. }
  35. func Open(path string, interByte time.Duration) (*Port, error) {
  36. f, err := os.OpenFile(path, os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
  37. if err != nil {
  38. return nil, err
  39. }
  40. fd := int(f.Fd())
  41. locked := false
  42. // PTYs are multiplexed test/sim nodes; flock is reserved for real serial
  43. // devices so a second hthd cannot steal /dev/ttyUSB*. Linux flock on a pts
  44. // slave races the keep-open fd and reconnect Open.
  45. if !strings.HasPrefix(path, "/dev/pts/") {
  46. if err := FlockExclusive(fd); err != nil {
  47. f.Close()
  48. if err == unix.EWOULDBLOCK || err == unix.EAGAIN {
  49. return nil, ErrAlreadyLocked
  50. }
  51. return nil, fmt.Errorf("flock: %w", err)
  52. }
  53. locked = true
  54. }
  55. if !strings.HasPrefix(path, "/dev/pts/") {
  56. if err := Configure1152008N1(fd); err != nil {
  57. if locked {
  58. Funlock(fd)
  59. }
  60. f.Close()
  61. return nil, err
  62. }
  63. } else if err := ConfigurePTYRaw(fd); err != nil {
  64. f.Close()
  65. return nil, err
  66. }
  67. p := &Port{
  68. path: path,
  69. parser: protocol.NewStreamParser(protocol.DefaultMaxPayload, interByte),
  70. interByte: interByte,
  71. }
  72. p.f.Store(f)
  73. p.locked.Store(locked)
  74. _ = p.Flush()
  75. return p, nil
  76. }
  77. func (p *Port) Path() string { return p.path }
  78. func (p *Port) Flush() error {
  79. f := p.file()
  80. if f == nil {
  81. return ErrDisconnected
  82. }
  83. p.parser.Reset()
  84. if strings.HasPrefix(p.path, "/dev/pts/") {
  85. return nil
  86. }
  87. if err := unix.IoctlSetInt(int(f.Fd()), unix.TCFLSH, unix.TCIOFLUSH); err != nil {
  88. return fmt.Errorf("tcflush: %w", err)
  89. }
  90. return nil
  91. }
  92. // RejectUnexpected fails closed if any residual protocol bytes are waiting.
  93. // It drains until EAGAIN/deadline, feeding each chunk to an isolated parser.
  94. // A complete late frame, half-frame, leftover header, or any unexplained
  95. // residual bytes mark the stream untrusted.
  96. func (p *Port) RejectUnexpected() error {
  97. f := p.file()
  98. if f == nil {
  99. return ErrDisconnected
  100. }
  101. if p.parser != nil && p.parser.Buffered() > 0 {
  102. left := p.parser.Buffered()
  103. p.parser.Reset()
  104. return fmt.Errorf("%w: parser leftover %d bytes", ErrUnexpectedRx, left)
  105. }
  106. drain := protocol.NewStreamParser(protocol.DefaultMaxPayload, p.interByte)
  107. buf := make([]byte, 256)
  108. deadline := time.Now().Add(20 * time.Millisecond)
  109. total := 0
  110. for time.Now().Before(deadline) {
  111. remain := time.Until(deadline)
  112. if remain <= 0 {
  113. break
  114. }
  115. slice := 2 * time.Millisecond
  116. if remain < slice {
  117. slice = remain
  118. }
  119. _ = f.SetReadDeadline(time.Now().Add(slice))
  120. n, err := f.Read(buf)
  121. if n > 0 {
  122. total += n
  123. parsed := drain.Push(buf[:n], time.Now())
  124. for _, fr := range parsed {
  125. p.parser.Reset()
  126. if fr.Err != nil {
  127. return fmt.Errorf("%w: untrusted residual parse: %v (%d bytes)", ErrUnexpectedRx, fr.Err, total)
  128. }
  129. if len(fr.Raw) > 0 {
  130. return fmt.Errorf("%w: late frame (%d bytes)", ErrUnexpectedRx, total)
  131. }
  132. }
  133. }
  134. if err != nil {
  135. if errors.Is(err, os.ErrDeadlineExceeded) {
  136. if n == 0 {
  137. break
  138. }
  139. continue
  140. }
  141. if errors.Is(err, io.EOF) {
  142. if total > 0 || drain.Buffered() > 0 {
  143. p.parser.Reset()
  144. return fmt.Errorf("%w: eof with residual %d bytes", ErrUnexpectedRx, total)
  145. }
  146. if isDisconnect(err) && !strings.HasPrefix(p.path, "/dev/pts/") {
  147. return ErrDisconnected
  148. }
  149. break
  150. }
  151. if isDisconnect(err) && !strings.HasPrefix(p.path, "/dev/pts/") {
  152. return ErrDisconnected
  153. }
  154. if n == 0 {
  155. break
  156. }
  157. }
  158. }
  159. if drain.Buffered() > 0 {
  160. p.parser.Reset()
  161. return fmt.Errorf("%w: half-frame leftover %d bytes after %d drained", ErrUnexpectedRx, drain.Buffered(), total)
  162. }
  163. if total > 0 {
  164. p.parser.Reset()
  165. return fmt.Errorf("%w: %d residual bytes", ErrUnexpectedRx, total)
  166. }
  167. return nil
  168. }
  169. func (p *Port) Interrupt() {
  170. f := p.file()
  171. if f == nil {
  172. return
  173. }
  174. _ = f.SetDeadline(time.Now())
  175. }
  176. func (p *Port) Close() error {
  177. if p == nil {
  178. return nil
  179. }
  180. f := p.f.Swap(nil)
  181. if f == nil {
  182. return nil
  183. }
  184. fd := int(f.Fd())
  185. _ = f.SetDeadline(time.Now())
  186. if p.locked.Swap(false) {
  187. _ = Funlock(fd)
  188. }
  189. return f.Close()
  190. }
  191. func (p *Port) Write(ctx context.Context, b []byte) (int, error) {
  192. f := p.file()
  193. if f == nil {
  194. return 0, ErrDisconnected
  195. }
  196. if err := p.RejectUnexpected(); err != nil {
  197. return 0, err
  198. }
  199. want := len(b)
  200. toWrite := b
  201. if capn := testWriteCap.Load(); capn > 0 && int(capn) < want {
  202. toWrite = b[:capn]
  203. }
  204. deadline, ok := ctx.Deadline()
  205. if ok {
  206. _ = f.SetWriteDeadline(deadline)
  207. } else {
  208. _ = f.SetWriteDeadline(time.Now().Add(2 * time.Second))
  209. }
  210. n, err := f.Write(toWrite)
  211. if n < want {
  212. return n, ErrShortWrite
  213. }
  214. if testForceErr.Swap(false) && err == nil {
  215. err = errors.New("injected full-write error")
  216. }
  217. if err != nil {
  218. if isDisconnect(err) {
  219. return n, ErrDisconnected
  220. }
  221. return n, err
  222. }
  223. return n, nil
  224. }
  225. func (p *Port) ReadFrame(ctx context.Context) (protocol.Frame, []byte, error) {
  226. f, raw, _, _, err := p.ReadFrameTimed(ctx)
  227. return f, raw, err
  228. }
  229. func (p *Port) ReadFrameTimed(ctx context.Context) (protocol.Frame, []byte, time.Time, time.Time, error) {
  230. f := p.file()
  231. if f == nil {
  232. return protocol.Frame{}, nil, time.Time{}, time.Time{}, ErrDisconnected
  233. }
  234. buf := make([]byte, 256)
  235. var firstByte time.Time
  236. ignoreCtx := testIgnoreContext.Load()
  237. for {
  238. if !ignoreCtx {
  239. if err := ctx.Err(); err != nil {
  240. return protocol.Frame{}, nil, firstByte, time.Now(), err
  241. }
  242. }
  243. d := 50 * time.Millisecond
  244. if p.interByte > 0 && p.interByte < d {
  245. d = p.interByte
  246. }
  247. if !ignoreCtx {
  248. if dl, ok := ctx.Deadline(); ok {
  249. remain := time.Until(dl)
  250. if remain <= 0 {
  251. return protocol.Frame{}, nil, firstByte, time.Now(), ErrTimeout
  252. }
  253. if remain < d {
  254. d = remain
  255. }
  256. }
  257. }
  258. f = p.file()
  259. if f == nil {
  260. return protocol.Frame{}, nil, firstByte, time.Now(), ErrDisconnected
  261. }
  262. _ = f.SetReadDeadline(time.Now().Add(d))
  263. n, err := f.Read(buf)
  264. now := time.Now()
  265. if n > 0 {
  266. if firstByte.IsZero() {
  267. firstByte = now
  268. }
  269. parsed := p.parser.Push(buf[:n], now)
  270. for _, item := range parsed {
  271. if item.Err != nil {
  272. return protocol.Frame{}, item.Raw, firstByte, now, item.Err
  273. }
  274. return item.Frame, item.Raw, firstByte, now, nil
  275. }
  276. }
  277. if n == 0 && err == nil {
  278. if ignoreCtx {
  279. time.Sleep(d)
  280. continue
  281. }
  282. select {
  283. case <-ctx.Done():
  284. return protocol.Frame{}, nil, firstByte, now, ErrTimeout
  285. case <-time.After(d):
  286. }
  287. continue
  288. }
  289. if err != nil {
  290. if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
  291. p.parser.InterByteTimeout(now)
  292. if !ignoreCtx && ctx.Err() != nil {
  293. return protocol.Frame{}, nil, firstByte, now, ErrTimeout
  294. }
  295. continue
  296. }
  297. if errors.Is(err, io.EOF) || isDisconnect(err) {
  298. // A pts slave Read often returns EOF when the buffer is empty even
  299. // though the master is still open. Wait for data or the context
  300. // deadline instead of treating the first empty read as hangup.
  301. if strings.HasPrefix(p.path, "/dev/pts/") && (ignoreCtx || ctx.Err() == nil) {
  302. continue
  303. }
  304. if !ignoreCtx && ctx.Err() != nil {
  305. return protocol.Frame{}, nil, firstByte, now, ErrTimeout
  306. }
  307. return protocol.Frame{}, nil, firstByte, now, fmt.Errorf("%w: %v", ErrDisconnected, err)
  308. }
  309. return protocol.Frame{}, nil, firstByte, now, err
  310. }
  311. }
  312. }
  313. func isDisconnect(err error) bool {
  314. return errors.Is(err, io.EOF) || errors.Is(err, unix.EIO) || errors.Is(err, unix.ENXIO) || errors.Is(err, unix.ENODEV)
  315. }