/
tarcopy.go
294 lines (254 loc) · 6.95 KB
/
tarcopy.go
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package dockerbuild
import (
"archive/tar"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/cockroachdb/errors"
"github.com/rs/zerolog/log"
)
type tarCopier struct {
fileTimes *time.Time
tw *tar.Writer
seenDirs map[ImagePath]bool
}
func newTarCopier(tw *tar.Writer, opts ...tarCopyOption) *tarCopier {
tc := &tarCopier{
tw: tw,
seenDirs: make(map[ImagePath]bool),
}
for _, opt := range opts {
opt(tc)
}
return tc
}
type tarCopyOption func(*tarCopier)
func setFileTimes(t time.Time) tarCopyOption {
return func(tc *tarCopier) {
tc.fileTimes = &t
}
}
// dirCopyDesc describes how to copy a directory to the tar.
type dirCopyDesc struct {
Spec *ImageSpec
SrcPath HostPath
DstPath ImagePath
// Src paths to exclude.
ExcludeSrcPaths map[HostPath]bool
}
func (tc *tarCopier) CopyData(spec *ImageSpec) error {
// Sort the paths by the destination path so that the tar file is deterministic.
type pathPair struct {
Src HostPath
Dest ImagePath
}
var paths []pathPair
for dest, src := range spec.CopyData {
paths = append(paths, pathPair{Src: src, Dest: dest})
}
sort.Slice(paths, func(i, j int) bool {
return paths[i].Dest < paths[j].Dest
})
for _, p := range paths {
fi, err := os.Stat(string(p.Src))
if err != nil {
return errors.Wrap(err, "stat source file")
}
if err := tc.MkdirAll(p.Dest.Dir(), 0755); err != nil {
return errors.Wrap(err, "create dirs")
}
if fi.IsDir() {
err = tc.CopyDir(&dirCopyDesc{
Spec: spec,
SrcPath: p.Src,
DstPath: p.Dest,
ExcludeSrcPaths: nil,
})
} else {
err = tc.CopyFile(p.Dest, p.Src, fi, "")
}
if err != nil {
return errors.Wrap(err, "copy path")
}
}
return nil
}
func (tc *tarCopier) CopyDir(desc *dirCopyDesc) error {
err := filepath.WalkDir(string(desc.SrcPath), func(pathStr string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
path := HostPath(pathStr)
// Should we skip this path?
if desc.ExcludeSrcPaths[path] {
if d.IsDir() {
return filepath.SkipDir
} else {
return nil
}
}
relPath, err := desc.SrcPath.Rel(path)
if err != nil {
return errors.WithStack(err)
}
dstPath := desc.DstPath.Join(string(relPath.ToImage()))
// If this is a symlink, compute the link target relative to DstPath.
var link ImagePath
if d.Type()&fs.ModeSymlink != 0 {
target, err := os.Readlink(string(path))
if err != nil {
return errors.WithStack(err)
}
link, err = tc.rewriteSymlink(desc, path, HostPath(target))
if err != nil {
return errors.WithStack(err)
} else if link == "" {
// Drop the symlink
return nil
}
}
fi, err := d.Info()
if err != nil {
return errors.WithStack(err)
}
err = tc.CopyFile(dstPath, path, fi, link)
return errors.Wrap(err, "add file")
})
return errors.WithStack(err)
}
// rewriteSymlink rewrites the symlink to the target filesystem.
func (tc *tarCopier) rewriteSymlink(desc *dirCopyDesc, path HostPath, linkTarget HostPath) (newTarget ImagePath, err error) {
var (
absTarget HostPath
relFromSrcPath HostPath
)
if linkTarget.IsAbs() {
// It's a link to an absolute destination.
// Determine its relative path, and see if that lives within the desc.SrcPath.
absTarget = linkTarget
relFromSrcPath, err = desc.SrcPath.Rel(absTarget)
if err != nil {
return "", err
}
// If the relative path is local to the SrcPath, allow it.
if filepath.IsLocal(relFromSrcPath.String()) {
return desc.DstPath.JoinImage(relFromSrcPath.ToImage()), nil
}
} else {
// We have a relative link target. Determine its absolute destination.
// Use path.Dir() since the symlink is relative to its directory, not relative to itself.
absTarget = path.Dir().JoinHost(linkTarget)
// Determine its relative path, and see if that lives within the desc.SrcPath.
relFromSrcPath, err = desc.SrcPath.Rel(absTarget)
if err != nil {
return "", err
}
// If the relative path is local to the SrcPath, allow it.
if filepath.IsLocal(relFromSrcPath.String()) {
return desc.DstPath.JoinImage(relFromSrcPath.ToImage()), nil
}
}
// Otherwise, determine if the absTarget is within some other path being copied.
absTargetStr := absTarget.String()
for dst, src := range desc.Spec.CopyData {
srcStr := src.String()
stcStrSep := srcStr + string(filepath.Separator)
if absTargetStr == srcStr {
return dst, nil
} else if suffix, found := strings.CutPrefix(absTargetStr, stcStrSep); found {
// It lives within the target. Compute the new target path.
return dst.Join(suffix), nil
}
}
log.Debug().
Str("target", linkTarget.String()).
Str("rel_target", relFromSrcPath.String()).
Str("abs_target", absTarget.String()).
Msg("dropping escaping symlink")
return "", nil
}
func (tc *tarCopier) MkdirAll(dstPath ImagePath, mode fs.FileMode) (err error) {
dstPath = ImagePath(filepath.ToSlash(dstPath.String()))
dstPath = dstPath.Clean()
for dstPath != "." && dstPath != "/" {
if !tc.seenDirs[dstPath] {
modTime := time.Time{}
if tc.fileTimes != nil {
modTime = *tc.fileTimes
}
header := &tar.Header{
Typeflag: tar.TypeDir,
ModTime: modTime,
Name: (dstPath + "/").String(), // from [archive/tar.FileInfoHeader]
Mode: int64(mode.Perm()),
}
if err := tc.tw.WriteHeader(header); err != nil {
return errors.Wrap(err, "write tar header")
}
tc.seenDirs[dstPath] = true
}
dstPath = dstPath.Dir()
}
return nil
}
func (tc *tarCopier) CopyFile(dstPath ImagePath, srcPath HostPath, fi fs.FileInfo, linkTarget ImagePath) (err error) {
header, err := tar.FileInfoHeader(fi, linkTarget.String())
if err != nil {
return err
}
if tc.fileTimes != nil {
t := *tc.fileTimes
header.ModTime = t
header.AccessTime = t
header.ChangeTime = t
}
header.Name = filepath.ToSlash(dstPath.String())
if err := tc.tw.WriteHeader(header); err != nil {
return errors.Wrap(err, "write tar header")
}
if fi.IsDir() {
tc.seenDirs[dstPath] = true
return nil
}
// If this is not a symlink, write the file.
if (fi.Mode() & fs.ModeSymlink) != fs.ModeSymlink {
// Write the file
f, err := os.Open(srcPath.String())
if err != nil {
return errors.Wrap(err, "open file")
}
defer func() {
if closeErr := f.Close(); err == nil {
err = errors.Wrap(closeErr, "close file")
}
}()
if _, err = io.Copy(tc.tw, f); err != nil {
return errors.Wrap(err, "copy file")
}
}
return nil
}
func (tc *tarCopier) WriteFile(dstPath string, mode fs.FileMode, data []byte) (err error) {
header := &tar.Header{
Name: dstPath,
Typeflag: tar.TypeReg,
Mode: int64(mode.Perm()),
Size: int64(len(data)),
}
if tc.fileTimes != nil {
t := *tc.fileTimes
header.ModTime = t
header.AccessTime = t
header.ChangeTime = t
}
header.Name = filepath.ToSlash(dstPath)
if err := tc.tw.WriteHeader(header); err != nil {
return errors.Wrap(err, "write tar header")
}
_, err = tc.tw.Write(data)
return errors.Wrap(err, "copy file")
}