File: open_linux.go

package info (click to toggle)
golang-github-containers-buildah 1.41.4%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 8,148 kB
  • sloc: sh: 2,569; makefile: 241; perl: 187; asm: 16; awk: 12; ansic: 1
file content (88 lines) | stat: -rw-r--r-- 2,259 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package open

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"strings"

	"github.com/containers/storage/pkg/reexec"
	"github.com/sirupsen/logrus"
	"golang.org/x/sys/unix"
)

const (
	bindFdToPathCommand = "buildah-bind-fd-to-path"
)

func init() {
	reexec.Register(bindFdToPathCommand, bindFdToPathMain)
}

// BindFdToPath creates a bind mount from the open file (which is actually a
// directory) to the specified location.  If it succeeds, the caller will need
// to unmount the targetPath when it's finished using it.  Regardless, it
// closes the passed-in descriptor.
func BindFdToPath(fd uintptr, targetPath string) error {
	f := os.NewFile(fd, "passed-in directory descriptor")
	defer func() {
		if err := f.Close(); err != nil {
			logrus.Debugf("closing descriptor %d after attempting to bind to %q: %v", fd, targetPath, err)
		}
	}()
	pipeReader, pipeWriter, err := os.Pipe()
	if err != nil {
		return err
	}
	cmd := reexec.Command(bindFdToPathCommand)
	cmd.Stdin = pipeReader
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout, cmd.Stderr = &stdout, &stderr
	cmd.ExtraFiles = append(cmd.ExtraFiles, f)

	err = cmd.Start()
	pipeReader.Close()
	if err != nil {
		pipeWriter.Close()
		return fmt.Errorf("starting child: %w", err)
	}

	encoder := json.NewEncoder(pipeWriter)
	if err := encoder.Encode(&targetPath); err != nil {
		return fmt.Errorf("sending target path to child: %w", err)
	}
	pipeWriter.Close()
	err = cmd.Wait()
	trimmedOutput := strings.TrimSpace(stdout.String()) + strings.TrimSpace(stderr.String())
	if err != nil {
		if len(trimmedOutput) > 0 {
			err = fmt.Errorf("%s: %w", trimmedOutput, err)
		}
	} else {
		if len(trimmedOutput) > 0 {
			err = errors.New(trimmedOutput)
		}
	}
	return err
}

func bindFdToPathMain() {
	var targetPath string
	decoder := json.NewDecoder(os.Stdin)
	if err := decoder.Decode(&targetPath); err != nil {
		fmt.Fprintf(os.Stderr, "error decoding target path")
		os.Exit(1)
	}
	if err := unix.Fchdir(3); err != nil {
		fmt.Fprintf(os.Stderr, "fchdir(): %v", err)
		os.Exit(1)
	}
	if err := unix.Mount(".", targetPath, "bind", unix.MS_BIND, ""); err != nil {
		fmt.Fprintf(os.Stderr, "bind-mounting passed-in directory to %q: %v", targetPath, err)
		os.Exit(1)
	}
	os.Exit(0)
}