Skip to content

Commit c79e45e

Browse files
committed
pty: add GetPtyFromFile as safer GetPty
Security-conscious callers may wish to have more control over opening /dev/ptmx, and so GetPty is not suitable for them. Previously it was not possible for such users to open /dev/ptmx and then use this package to create new ptys and manage the console. On Linux, the intended usage would be for a daemon to get an O_PATH handle to /dev/ptmx that can then be re-opened (through procfs) to get a new handle to /dev/ptmx. I suspect on FreeBSD you could use O_EMPTY_PATH to accomplish something similar. Signed-off-by: Aleksa Sarai <[email protected]>
1 parent 12ba745 commit c79e45e

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

console_test.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ func TestWinSize(t *testing.T) {
5454
}
5555
}
5656

57-
func TestConsolePty(t *testing.T) {
58-
console, slavePath, err := NewPty()
57+
func testConsolePty(t *testing.T, newPty func() (Console, string, error)) {
58+
console, slavePath, err := newPty()
5959
if err != nil {
6060
t.Fatal(err)
6161
}
@@ -100,3 +100,18 @@ func TestConsolePty(t *testing.T) {
100100
t.Errorf("unexpected output %q", out)
101101
}
102102
}
103+
104+
func TestConsolePty_NewPty(t *testing.T) {
105+
testConsolePty(t, NewPty)
106+
}
107+
108+
func TestConsolePty_NewPtyFromFile(t *testing.T) {
109+
testConsolePty(t, func() (Console, string, error) {
110+
// Equivalent to NewPty().
111+
f, err := openpt()
112+
if err != nil {
113+
return nil, "", err
114+
}
115+
return NewPtyFromFile(f)
116+
})
117+
}

console_unix.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,15 @@ func NewPty() (Console, string, error) {
3131
if err != nil {
3232
return nil, "", err
3333
}
34+
return NewPtyFromFile(f)
35+
}
36+
37+
// NewPtyFromFile creates a new pty pair, just like [NewPty] except that the
38+
// provided [os.File] is used as the master rather than automatically creating
39+
// a new master from /dev/ptmx. The ownership of [os.File] is passed to the
40+
// returned [Console], so the caller must be careful to not call Close on the
41+
// underlying file.
42+
func NewPtyFromFile(f File) (Console, string, error) {
3443
slave, err := ptsname(f)
3544
if err != nil {
3645
return nil, "", err

0 commit comments

Comments
 (0)