port_linux.go 6.8 KB

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