| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331 |
- //go:build linux
- package serialtransport
- import (
- "context"
- "errors"
- "fmt"
- "io"
- "os"
- "strings"
- "sync/atomic"
- "time"
- "golang.org/x/sys/unix"
- "hth/internal/protocol"
- )
- var (
- ErrShortWrite = errors.New("short serial write")
- ErrDisconnected = errors.New("serial disconnected")
- ErrTimeout = errors.New("serial timeout")
- ErrAlreadyLocked = errors.New("serial device exclusively locked")
- ErrUnexpectedRx = errors.New("unexpected serial bytes before request")
- )
- type Port struct {
- path string
- f atomic.Pointer[os.File]
- parser *protocol.StreamParser
- interByte time.Duration
- locked atomic.Bool
- }
- func (p *Port) file() *os.File {
- if p == nil {
- return nil
- }
- return p.f.Load()
- }
- func Open(path string, interByte time.Duration) (*Port, error) {
- f, err := os.OpenFile(path, os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
- if err != nil {
- return nil, err
- }
- fd := int(f.Fd())
- locked := false
- // PTYs are multiplexed test/sim nodes; flock is reserved for real serial
- // devices so a second hthd cannot steal /dev/ttyUSB*. Linux flock on a pts
- // slave races the keep-open fd and reconnect Open.
- if !strings.HasPrefix(path, "/dev/pts/") {
- if err := FlockExclusive(fd); err != nil {
- f.Close()
- if err == unix.EWOULDBLOCK || err == unix.EAGAIN {
- return nil, ErrAlreadyLocked
- }
- return nil, fmt.Errorf("flock: %w", err)
- }
- locked = true
- }
- if !strings.HasPrefix(path, "/dev/pts/") {
- if err := Configure1152008N1(fd); err != nil {
- if locked {
- Funlock(fd)
- }
- f.Close()
- return nil, err
- }
- } else if err := ConfigurePTYRaw(fd); err != nil {
- f.Close()
- return nil, err
- }
- p := &Port{
- path: path,
- parser: protocol.NewStreamParser(protocol.DefaultMaxPayload, interByte),
- interByte: interByte,
- }
- p.f.Store(f)
- p.locked.Store(locked)
- _ = p.Flush()
- return p, nil
- }
- func (p *Port) Path() string { return p.path }
- func (p *Port) Flush() error {
- f := p.file()
- if f == nil {
- return ErrDisconnected
- }
- p.parser.Reset()
- if strings.HasPrefix(p.path, "/dev/pts/") {
- return nil
- }
- if err := unix.IoctlSetInt(int(f.Fd()), unix.TCFLSH, unix.TCIOFLUSH); err != nil {
- return fmt.Errorf("tcflush: %w", err)
- }
- return nil
- }
- // RejectUnexpected fails closed if any residual protocol bytes are waiting.
- // It drains until EAGAIN/deadline, feeding each chunk to an isolated parser.
- // A complete late frame, half-frame, leftover header, or any unexplained
- // residual bytes mark the stream untrusted.
- func (p *Port) RejectUnexpected() error {
- f := p.file()
- if f == nil {
- return ErrDisconnected
- }
- if p.parser != nil && p.parser.Buffered() > 0 {
- left := p.parser.Buffered()
- p.parser.Reset()
- return fmt.Errorf("%w: parser leftover %d bytes", ErrUnexpectedRx, left)
- }
- drain := protocol.NewStreamParser(protocol.DefaultMaxPayload, p.interByte)
- buf := make([]byte, 256)
- deadline := time.Now().Add(20 * time.Millisecond)
- total := 0
- for time.Now().Before(deadline) {
- remain := time.Until(deadline)
- if remain <= 0 {
- break
- }
- slice := 2 * time.Millisecond
- if remain < slice {
- slice = remain
- }
- _ = f.SetReadDeadline(time.Now().Add(slice))
- n, err := f.Read(buf)
- if n > 0 {
- total += n
- parsed := drain.Push(buf[:n], time.Now())
- for _, fr := range parsed {
- p.parser.Reset()
- if fr.Err != nil {
- return fmt.Errorf("%w: untrusted residual parse: %v (%d bytes)", ErrUnexpectedRx, fr.Err, total)
- }
- if len(fr.Raw) > 0 {
- return fmt.Errorf("%w: late frame (%d bytes)", ErrUnexpectedRx, total)
- }
- }
- }
- if err != nil {
- if errors.Is(err, os.ErrDeadlineExceeded) {
- if n == 0 {
- break
- }
- continue
- }
- if errors.Is(err, io.EOF) {
- if total > 0 || drain.Buffered() > 0 {
- p.parser.Reset()
- return fmt.Errorf("%w: eof with residual %d bytes", ErrUnexpectedRx, total)
- }
- if isDisconnect(err) && !strings.HasPrefix(p.path, "/dev/pts/") {
- return ErrDisconnected
- }
- break
- }
- if isDisconnect(err) && !strings.HasPrefix(p.path, "/dev/pts/") {
- return ErrDisconnected
- }
- if n == 0 {
- break
- }
- }
- }
- if drain.Buffered() > 0 {
- p.parser.Reset()
- return fmt.Errorf("%w: half-frame leftover %d bytes after %d drained", ErrUnexpectedRx, drain.Buffered(), total)
- }
- if total > 0 {
- p.parser.Reset()
- return fmt.Errorf("%w: %d residual bytes", ErrUnexpectedRx, total)
- }
- return nil
- }
- func (p *Port) Interrupt() {
- f := p.file()
- if f == nil {
- return
- }
- _ = f.SetDeadline(time.Now())
- }
- func (p *Port) Close() error {
- if p == nil {
- return nil
- }
- f := p.f.Swap(nil)
- if f == nil {
- return nil
- }
- fd := int(f.Fd())
- _ = f.SetDeadline(time.Now())
- if p.locked.Swap(false) {
- _ = Funlock(fd)
- }
- return f.Close()
- }
- func (p *Port) Write(ctx context.Context, b []byte) (int, error) {
- f := p.file()
- if f == nil {
- return 0, ErrDisconnected
- }
- if err := p.RejectUnexpected(); err != nil {
- return 0, err
- }
- want := len(b)
- toWrite := b
- if capn := testWriteCap.Load(); capn > 0 && int(capn) < want {
- toWrite = b[:capn]
- }
- deadline, ok := ctx.Deadline()
- if ok {
- _ = f.SetWriteDeadline(deadline)
- } else {
- _ = f.SetWriteDeadline(time.Now().Add(2 * time.Second))
- }
- n, err := f.Write(toWrite)
- if n < want {
- return n, ErrShortWrite
- }
- if testForceErr.Swap(false) && err == nil {
- err = errors.New("injected full-write error")
- }
- if err != nil {
- if isDisconnect(err) {
- return n, ErrDisconnected
- }
- return n, err
- }
- return n, nil
- }
- func (p *Port) ReadFrame(ctx context.Context) (protocol.Frame, []byte, error) {
- f, raw, _, _, err := p.ReadFrameTimed(ctx)
- return f, raw, err
- }
- func (p *Port) ReadFrameTimed(ctx context.Context) (protocol.Frame, []byte, time.Time, time.Time, error) {
- f := p.file()
- if f == nil {
- return protocol.Frame{}, nil, time.Time{}, time.Time{}, ErrDisconnected
- }
- buf := make([]byte, 256)
- var firstByte time.Time
- ignoreCtx := testIgnoreContext.Load()
- for {
- if !ignoreCtx {
- if err := ctx.Err(); err != nil {
- return protocol.Frame{}, nil, firstByte, time.Now(), err
- }
- }
- d := 50 * time.Millisecond
- if p.interByte > 0 && p.interByte < d {
- d = p.interByte
- }
- if !ignoreCtx {
- if dl, ok := ctx.Deadline(); ok {
- remain := time.Until(dl)
- if remain <= 0 {
- return protocol.Frame{}, nil, firstByte, time.Now(), ErrTimeout
- }
- if remain < d {
- d = remain
- }
- }
- }
- f = p.file()
- if f == nil {
- return protocol.Frame{}, nil, firstByte, time.Now(), ErrDisconnected
- }
- _ = f.SetReadDeadline(time.Now().Add(d))
- n, err := f.Read(buf)
- now := time.Now()
- if n > 0 {
- if firstByte.IsZero() {
- firstByte = now
- }
- parsed := p.parser.Push(buf[:n], now)
- for _, item := range parsed {
- if item.Err != nil {
- return protocol.Frame{}, item.Raw, firstByte, now, item.Err
- }
- return item.Frame, item.Raw, firstByte, now, nil
- }
- }
- if n == 0 && err == nil {
- if ignoreCtx {
- time.Sleep(d)
- continue
- }
- select {
- case <-ctx.Done():
- return protocol.Frame{}, nil, firstByte, now, ErrTimeout
- case <-time.After(d):
- }
- continue
- }
- if err != nil {
- if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
- p.parser.InterByteTimeout(now)
- if !ignoreCtx && ctx.Err() != nil {
- return protocol.Frame{}, nil, firstByte, now, ErrTimeout
- }
- continue
- }
- if errors.Is(err, io.EOF) || isDisconnect(err) {
- // A pts slave Read often returns EOF when the buffer is empty even
- // though the master is still open. Wait for data or the context
- // deadline instead of treating the first empty read as hangup.
- if strings.HasPrefix(p.path, "/dev/pts/") && (ignoreCtx || ctx.Err() == nil) {
- continue
- }
- if !ignoreCtx && ctx.Err() != nil {
- return protocol.Frame{}, nil, firstByte, now, ErrTimeout
- }
- return protocol.Frame{}, nil, firstByte, now, fmt.Errorf("%w: %v", ErrDisconnected, err)
- }
- return protocol.Frame{}, nil, firstByte, now, err
- }
- }
- }
- func isDisconnect(err error) bool {
- return errors.Is(err, io.EOF) || errors.Is(err, unix.EIO) || errors.Is(err, unix.ENXIO) || errors.Is(err, unix.ENODEV)
- }
|