pkg/term

FD leak in open()

stephan57160 opened this issue · 4 comments

The code of term.Open() does not close the FD, in case of error:

// Open opens an asynchronous communications port.
func Open(name string, options ...func(*Term) error) (*Term, error) {
	fd, e := unix.Open(name, unix.O_NOCTTY|unix.O_CLOEXEC|unix.O_NDELAY|unix.O_RDWR, 0666)
	if e != nil {
		// FD not opened, so, we don't care.
		return nil, &os.PathError{
			Op:   "open",
			Path: name,
			Err:  e,
		}
	}

	orig, err := termios.Tcgetattr(uintptr(fd))
	if err != nil {
		// FD opened, but not closed.
		return nil, err
	}
	t := Term{name: name, fd: fd, orig: *orig}
	if err := t.SetOption(options...); err != nil {
		// FD open, but not closed.
		return nil, err
	}
	
	// FD opened, but not closed if SetNonblock() fails.
	return &t, unix.SetNonblock(t.fd, false)
}

Leak may happen, when the supposed TERM file is not a TERM.

good catch, would you like to send a PR?

Well...
Actually, I found almost the same in

  • term_open_posix.go
  • term_solaris.go
    Working on a similar solution for the 2nd one as well, but, I cannot test anything.

PR #69 raised, in case you have some time to check it.