File: archive_unix.go

package info (click to toggle)
golang-github-containers-storage 1.59.1%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,184 kB
  • sloc: sh: 630; ansic: 389; makefile: 143; awk: 12
file content (260 lines) | stat: -rw-r--r-- 6,331 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//go:build !windows && !darwin

package chrootarchive

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"golang.org/x/sys/unix"

	"github.com/containers/storage/pkg/archive"
	"github.com/containers/storage/pkg/reexec"
)

type unpackDestination struct {
	root *os.File
	dest string
}

func (dst *unpackDestination) Close() error {
	return dst.root.Close()
}

// tarOptionsDescriptor is passed as an extra file
const tarOptionsDescriptor = 3

// rootFileDescriptor is passed as an extra file
const rootFileDescriptor = 4

// procPathForFd gives us a string for a descriptor.
// Note that while Linux supports actually *reading* this
// path, FreeBSD and other platforms don't; but in this codebase
// we only compare strings.
func procPathForFd(fd int) string {
	return fmt.Sprintf("/proc/self/fd/%d", fd)
}

// untar is the entry-point for storage-untar on re-exec. This is not used on
// Windows as it does not support chroot, hence no point sandboxing through
// chroot and rexec.
func untar() {
	runtime.LockOSThread()
	flag.Parse()

	var options archive.TarOptions

	// read the options from the pipe "ExtraFiles"
	if err := json.NewDecoder(os.NewFile(tarOptionsDescriptor, "options")).Decode(&options); err != nil {
		fatal(err)
	}

	dst := flag.Arg(0)
	var root string
	if len(flag.Args()) > 1 {
		root = flag.Arg(1)
	}

	// FreeBSD doesn't have proc/self, but we can handle it here
	if root == procPathForFd(rootFileDescriptor) {
		// Take ownership to ensure it's closed; no need to leak
		// this afterwards.
		rootFd := os.NewFile(rootFileDescriptor, "tar-root")
		defer rootFd.Close()
		if err := unix.Fchdir(int(rootFd.Fd())); err != nil {
			fatal(err)
		}
		root = "."
	} else if root == "" {
		root = dst
	}

	if err := chroot(root); err != nil {
		fatal(err)
	}

	if err := archive.Unpack(os.Stdin, dst, &options); err != nil {
		fatal(err)
	}
	// fully consume stdin in case it is zero padded
	if _, err := flush(os.Stdin); err != nil {
		fatal(err)
	}

	os.Exit(0)
}

// newUnpackDestination takes a root directory and a destination which
// must be underneath it, and returns an object that can unpack
// in the target root using a file descriptor.
func newUnpackDestination(root, dest string) (*unpackDestination, error) {
	if root == "" {
		return nil, errors.New("must specify a root to chroot to")
	}
	relDest, err := filepath.Rel(root, dest)
	if err != nil {
		return nil, err
	}
	if relDest == "." {
		relDest = "/"
	}
	if relDest[0] != '/' {
		relDest = "/" + relDest
	}

	rootfdRaw, err := unix.Open(root, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
	if err != nil {
		return nil, &fs.PathError{Op: "open", Path: root, Err: err}
	}
	return &unpackDestination{
		root: os.NewFile(uintptr(rootfdRaw), "rootfs"),
		dest: relDest,
	}, nil
}

func invokeUnpack(decompressedArchive io.Reader, dest *unpackDestination, options *archive.TarOptions) error {
	// We can't pass a potentially large exclude list directly via cmd line
	// because we easily overrun the kernel's max argument/environment size
	// when the full image list is passed (e.g. when this is used by
	// `docker load`). We will marshall the options via a pipe to the
	// child
	r, w, err := os.Pipe()
	if err != nil {
		return fmt.Errorf("untar pipe failure: %w", err)
	}

	cmd := reexec.Command("storage-untar", dest.dest, procPathForFd(rootFileDescriptor))
	cmd.Stdin = decompressedArchive

	// If you change this, change tarOptionsDescriptor above
	cmd.ExtraFiles = append(cmd.ExtraFiles, r) // fd 3
	// If you change this, change rootFileDescriptor above too
	cmd.ExtraFiles = append(cmd.ExtraFiles, dest.root) // fd 4
	output := bytes.NewBuffer(nil)
	cmd.Stdout = output
	cmd.Stderr = output

	if err := cmd.Start(); err != nil {
		w.Close()
		return fmt.Errorf("untar error on re-exec cmd: %w", err)
	}

	// write the options to the pipe for the untar exec to read
	if err := json.NewEncoder(w).Encode(options); err != nil {
		w.Close()
		return fmt.Errorf("untar json encode to pipe failed: %w", err)
	}
	w.Close()

	if err := cmd.Wait(); err != nil {
		errorOut := fmt.Errorf("unpacking failed (error: %w; output: %s)", err, output)
		// when `xz -d -c -q | storage-untar ...` failed on storage-untar side,
		// we need to exhaust `xz`'s output, otherwise the `xz` side will be
		// pending on write pipe forever
		if _, err := io.Copy(io.Discard, decompressedArchive); err != nil {
			return fmt.Errorf("%w\nexhausting input failed (error: %w)", errorOut, err)
		}

		return errorOut
	}
	return nil
}

func tar() {
	runtime.LockOSThread()
	flag.Parse()

	src := flag.Arg(0)
	var root string
	if len(flag.Args()) > 1 {
		root = flag.Arg(1)
	}

	if root == "" {
		root = src
	}

	if err := realChroot(root); err != nil {
		fatal(err)
	}

	var options archive.TarOptions
	if err := json.NewDecoder(os.Stdin).Decode(&options); err != nil {
		fatal(err)
	}

	rdr, err := archive.TarWithOptions(src, &options)
	if err != nil {
		fatal(err)
	}
	defer rdr.Close()

	if _, err := io.Copy(os.Stdout, rdr); err != nil {
		fatal(err)
	}

	os.Exit(0)
}

func invokePack(srcPath string, options *archive.TarOptions, root string) (io.ReadCloser, error) {
	if root == "" {
		return nil, errors.New("root path must not be empty")
	}

	relSrc, err := filepath.Rel(root, srcPath)
	if err != nil {
		return nil, err
	}
	if relSrc == "." {
		relSrc = "/"
	}
	if relSrc[0] != '/' {
		relSrc = "/" + relSrc
	}

	// make sure we didn't trim a trailing slash with the call to `Rel`
	if strings.HasSuffix(srcPath, "/") && !strings.HasSuffix(relSrc, "/") {
		relSrc += "/"
	}

	cmd := reexec.Command("storage-tar", relSrc, root)

	errBuff := bytes.NewBuffer(nil)
	cmd.Stderr = errBuff

	tarR, tarW := io.Pipe()
	cmd.Stdout = tarW

	stdin, err := cmd.StdinPipe()
	if err != nil {
		return nil, fmt.Errorf("getting options pipe for tar process: %w", err)
	}

	if err := cmd.Start(); err != nil {
		return nil, fmt.Errorf("tar error on re-exec cmd: %w", err)
	}

	go func() {
		err := cmd.Wait()
		if err != nil {
			err = fmt.Errorf("processing tar file(%s): %w", errBuff, err)
		}
		tarW.CloseWithError(err)
	}()

	if err := json.NewEncoder(stdin).Encode(options); err != nil {
		stdin.Close()
		return nil, fmt.Errorf("tar json encode to pipe failed: %w", err)
	}
	stdin.Close()

	return tarR, nil
}