1
//go:build !remote && (linux || freebsd)
15
"github.com/containers/common/pkg/config"
16
"github.com/containers/common/pkg/detach"
17
"github.com/containers/common/pkg/resize"
18
"github.com/containers/podman/v5/libpod/define"
19
"github.com/containers/podman/v5/pkg/errorhandling"
20
"github.com/moby/term"
21
"github.com/sirupsen/logrus"
22
"golang.org/x/sys/unix"
25
/* Sync with stdpipe_t in conmon.c */
32
// Attach to the given container.
33
// Does not check if state is appropriate.
34
// started is only required if startContainer is true.
35
func (r *ConmonOCIRuntime) Attach(c *Container, params *AttachOptions) error {
36
passthrough := c.LogDriver() == define.PassthroughLogging || c.LogDriver() == define.PassthroughTTYLogging
38
if params == nil || params.Streams == nil {
39
return fmt.Errorf("must provide parameters to Attach: %w", define.ErrInternal)
42
if !params.Streams.AttachOutput && !params.Streams.AttachError && !params.Streams.AttachInput && !passthrough {
43
return fmt.Errorf("must provide at least one stream to attach to: %w", define.ErrInvalidArg)
45
if params.Start && params.Started == nil {
46
return fmt.Errorf("started chan not passed when startContainer set: %w", define.ErrInternal)
49
keys := config.DefaultDetachKeys
50
if params.DetachKeys != nil {
51
keys = *params.DetachKeys
54
detachKeys, err := processDetachKeys(keys)
59
var conn *net.UnixConn
61
logrus.Debugf("Attaching to container %s", c.ID())
63
// If we have a resize, do it.
64
if params.InitialSize != nil {
65
if err := r.AttachResize(c, *params.InitialSize); err != nil {
70
attachSock, err := c.AttachSocketPath()
75
conn, err = openUnixSocket(attachSock)
77
return fmt.Errorf("failed to connect to container's attach socket: %v: %w", attachSock, err)
80
if err := conn.Close(); err != nil {
81
logrus.Errorf("unable to close socket: %q", err)
86
// If starting was requested, start the container and notify when that's
89
if err := c.start(context.TODO()); err != nil {
92
params.Started <- true
99
receiveStdoutError, stdinDone := setupStdioChannels(params.Streams, conn, detachKeys)
100
if params.AttachReady != nil {
101
params.AttachReady <- true
103
return readStdio(conn, params.Streams, receiveStdoutError, stdinDone)
106
// Attach to the given container's exec session.
108
// attachFd and startFd must be open file descriptors. attachFd must be the
109
// output side of the fd and is used for two things:
111
// 1. conmon will first send a nonce value across the pipe indicating it has
112
// set up its side of the console socket this ensures attachToExec gets all of
113
// the output of the called process.
115
// 2. conmon will then send the exit code of the exec process, or an error in the exec session.
117
// startFd must be the input side of the fd.
119
// newSize resizes the tty to this size before the process is started, must be
120
// nil if the exec session has no tty
122
// conmon will wait to start the exec session until the parent process has set up the console socket.
124
// Once attachToExec successfully attaches to the console socket, the child
125
// conmon process responsible for calling runtime exec will read from the
126
// output side of start fd, thus learning to start the child process.
128
// Thus, the order goes as follow:
129
// 1. conmon parent process sets up its console socket. sends on attachFd
130
// 2. attachToExec attaches to the console socket after reading on attachFd and resizes the tty
131
// 3. child waits on startFd for attachToExec to attach to said console socket
132
// 4. attachToExec sends on startFd, signalling it has attached to the socket and child is ready to go
133
// 5. child receives on startFd, runs the runtime exec command
134
// attachToExec is responsible for closing startFd and attachFd
135
func (c *Container) attachToExec(streams *define.AttachStreams, keys *string, sessionID string, startFd, attachFd *os.File, newSize *resize.TerminalSize) error {
136
if !streams.AttachOutput && !streams.AttachError && !streams.AttachInput {
137
return fmt.Errorf("must provide at least one stream to attach to: %w", define.ErrInvalidArg)
139
if startFd == nil || attachFd == nil {
140
return fmt.Errorf("start sync pipe and attach sync pipe must be defined for exec attach: %w", define.ErrInvalidArg)
143
defer errorhandling.CloseQuiet(startFd)
144
defer errorhandling.CloseQuiet(attachFd)
146
detachString := config.DefaultDetachKeys
150
detachKeys, err := processDetachKeys(detachString)
155
logrus.Debugf("Attaching to container %s exec session %s", c.ID(), sessionID)
157
// set up the socket path, such that it is the correct length and location for exec
158
sockPath, err := c.execAttachSocketPath(sessionID)
163
// 2: read from attachFd that the parent process has set up the console socket
164
if _, err := readConmonPipeData(c.ociRuntime.Name(), attachFd, ""); err != nil {
168
// resize before we start the container process
170
err = c.ociRuntime.ExecAttachResize(c, sessionID, *newSize)
172
logrus.Warnf("Resize failed: %v", err)
177
conn, err := openUnixSocket(sockPath)
179
return fmt.Errorf("failed to connect to container's attach socket: %v: %w", sockPath, err)
182
if err := conn.Close(); err != nil {
183
logrus.Errorf("Unable to close socket: %q", err)
187
// start listening on stdio of the process
188
receiveStdoutError, stdinDone := setupStdioChannels(streams, conn, detachKeys)
190
// 4: send start message to child
191
if err := writeConmonPipeData(startFd); err != nil {
195
return readStdio(conn, streams, receiveStdoutError, stdinDone)
198
func processDetachKeys(keys string) ([]byte, error) {
199
// Check the validity of the provided keys first
203
detachKeys, err := term.ToBytes(keys)
205
return nil, fmt.Errorf("invalid detach keys: %w", err)
207
return detachKeys, nil
210
func registerResizeFunc(r <-chan resize.TerminalSize, bundlePath string) {
211
resize.HandleResizing(r, func(size resize.TerminalSize) {
212
controlPath := filepath.Join(bundlePath, "ctl")
213
controlFile, err := os.OpenFile(controlPath, unix.O_WRONLY, 0)
215
logrus.Debugf("Could not open ctl file: %v", err)
218
defer controlFile.Close()
220
logrus.Debugf("Received a resize event: %+v", size)
221
if _, err = fmt.Fprintf(controlFile, "%d %d %d\n", 1, size.Height, size.Width); err != nil {
222
logrus.Warnf("Failed to write to control file to resize terminal: %v", err)
227
func setupStdioChannels(streams *define.AttachStreams, conn *net.UnixConn, detachKeys []byte) (chan error, chan error) {
228
receiveStdoutError := make(chan error)
230
receiveStdoutError <- redirectResponseToOutputStreams(streams.OutputStream, streams.ErrorStream, streams.AttachOutput, streams.AttachError, conn)
233
stdinDone := make(chan error)
236
if streams.AttachInput {
237
_, err = detach.Copy(conn, streams.InputStream, detachKeys)
242
return receiveStdoutError, stdinDone
245
func redirectResponseToOutputStreams(outputStream, errorStream io.Writer, writeOutput, writeError bool, conn io.Reader) error {
247
buf := make([]byte, 8192+1) /* Sync with conmon STDIO_BUF_SIZE */
249
nr, er := conn.Read(buf)
254
case AttachPipeStdout:
256
doWrite = writeOutput
257
case AttachPipeStderr:
261
logrus.Infof("Received unexpected attach type %+d", buf[0])
264
return errors.New("output destination cannot be nil")
268
nw, ew := dst.Write(buf[1:nr])
274
err = io.ErrShortWrite
279
if errors.Is(er, io.EOF) || errors.Is(er, syscall.ECONNRESET) {
290
func readStdio(conn *net.UnixConn, streams *define.AttachStreams, receiveStdoutError, stdinDone chan error) error {
293
case err = <-receiveStdoutError:
294
if err := socketCloseWrite(conn); err != nil {
295
logrus.Errorf("Failed to close stdin: %v", err)
298
case err = <-stdinDone:
299
if err == define.ErrDetach {
300
if err := socketCloseWrite(conn); err != nil {
301
logrus.Errorf("Failed to close stdin: %v", err)
306
// copy stdin is done, close it
307
if connErr := socketCloseWrite(conn); connErr != nil {
308
logrus.Errorf("Unable to close conn: %v", connErr)
311
if streams.AttachOutput || streams.AttachError {
312
return <-receiveStdoutError