Skip to content

Commit 219fa3d

Browse files
committed
cio.copyIO: fix pipes potentially not being closed (Windows)
The defer functions were checking the local variable, and would therefore not be executed, as the function returned if an error occurred. Perhaps best illustrated when renaming the local variables; if fifos.Stdin != "" { l, err1 := winio.ListenPipe(fifos.Stdin, nil) if err1 != nil { return nil, errors.Wrapf(err1, "failed to create stdin pipe %s", fifos.Stdin) } defer func(l net.Listener) { if err1 != nil { l.Close() } }(l) // ... } if fifos.Stdout != "" { l, err2 := winio.ListenPipe(fifos.Stdout, nil) if err2 != nil { return nil, errors.Wrapf(err2, "failed to create stdout pipe %s", fifos.Stdout) } defer func(l net.Listener) { if err2 != nil { l.Close() } }(l) // .... } This patch changes the function to use a named return variable, and to use a single `defer()` that closes all pipes. Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent baf6c1d commit 219fa3d

1 file changed

Lines changed: 13 additions & 17 deletions

File tree

cio/io_windows.go

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import (
2020
"context"
2121
"fmt"
2222
"io"
23-
"net"
2423

2524
winio "github.com/Microsoft/go-winio"
2625
"github.com/containerd/containerd/log"
@@ -43,21 +42,28 @@ func NewFIFOSetInDir(_, id string, terminal bool) (*FIFOSet, error) {
4342
}, nil), nil
4443
}
4544

46-
func copyIO(fifos *FIFOSet, ioset *Streams) (*cio, error) {
45+
func copyIO(fifos *FIFOSet, ioset *Streams) (_ *cio, retErr error) {
4746
var (
4847
set []io.Closer
4948
)
5049

50+
defer func() {
51+
if retErr == nil {
52+
return
53+
}
54+
for _, closer := range set {
55+
if closer == nil {
56+
continue
57+
}
58+
_ = closer.Close()
59+
}
60+
}()
61+
5162
if fifos.Stdin != "" {
5263
l, err := winio.ListenPipe(fifos.Stdin, nil)
5364
if err != nil {
5465
return nil, errors.Wrapf(err, "failed to create stdin pipe %s", fifos.Stdin)
5566
}
56-
defer func(l net.Listener) {
57-
if err != nil {
58-
l.Close()
59-
}
60-
}(l)
6167
set = append(set, l)
6268

6369
go func() {
@@ -81,11 +87,6 @@ func copyIO(fifos *FIFOSet, ioset *Streams) (*cio, error) {
8187
if err != nil {
8288
return nil, errors.Wrapf(err, "failed to create stdout pipe %s", fifos.Stdout)
8389
}
84-
defer func(l net.Listener) {
85-
if err != nil {
86-
l.Close()
87-
}
88-
}(l)
8990
set = append(set, l)
9091

9192
go func() {
@@ -109,11 +110,6 @@ func copyIO(fifos *FIFOSet, ioset *Streams) (*cio, error) {
109110
if err != nil {
110111
return nil, errors.Wrapf(err, "failed to create stderr pipe %s", fifos.Stderr)
111112
}
112-
defer func(l net.Listener) {
113-
if err != nil {
114-
l.Close()
115-
}
116-
}(l)
117113
set = append(set, l)
118114

119115
go func() {

0 commit comments

Comments
 (0)