Debian Codegraph @

localfs.go

raw
1 package desync
2
3 import (
4 "fmt"
5 "io"
6 "os"
7 "path/filepath"
8 "slices"
9 "strings"
10 "sync"
11 "time"
12 )
13
14 // LocalFS uses the local filesystem for tar/untar operations.
15 type LocalFS struct {
16 // Base directory
17 Root string
18
19 opts LocalFSOptions
20
21 dev uint64
22 once sync.Once
23 entries chan walkEntry
24 sErr error
25
26 // Writer side. All write/metadata operations are performed through an
27 // os.Root handle which confines them to Root and refuses to follow any
28 // symlink (planted by the archive itself) that would escape it.
29 wonce sync.Once
30 wroot *os.Root
31 wErr error
32 rootReal string
33
34 // Directories whose metadata (owner, xattrs, permissions and timestamps)
35 // hasn't been applied yet because they may still be populated. Held in
36 // the order they were created, i.e. a directory is always preceded by its
37 // parent.
38 pending []NodeDirectory
39 }
40
41 // LocalFSOptions influence the behavior of the filesystem when reading from or writing to it.
42 type LocalFSOptions struct {
43 // Only used when reading from the filesystem. Will only return
44 // files from the same device as the first read operation.
45 OneFileSystem bool
46
47 // When writing files, use the current owner and don't try to apply the original owner.
48 NoSameOwner bool
49
50 // Ignore the incoming permissions when writing files. Use the current default instead.
51 NoSamePermissions bool
52
53 // Reads all timestamps as zero. Used in tar operations to avoid unnecessary changes.
54 NoTime bool
55 }
56
57 var _ FilesystemWriter = &LocalFS{}
58 var _ FilesystemReader = &LocalFS{}
59 var _ FilesystemFinalizer = &LocalFS{}
60
61 // writeRoot lazily creates the extraction root directory and opens an os.Root
62 // handle anchored to it. Every write/metadata operation goes through the
63 // returned handle so that no path component (including symlinks created earlier
64 // by the same archive) can be used to escape Root. The handle is opened only
65 // once; the result (or error) is cached for the lifetime of the LocalFS.
66 func (fs *LocalFS) writeRoot() (*os.Root, error) {
67 fs.wonce.Do(func() {
68 if err := os.MkdirAll(fs.Root, 0777); err != nil {
69 fs.wErr = err
70 return
71 }
72 // Resolved real path of the root, used for the rare symlink/device
73 // xattr fallback that has no fd-based equivalent.
74 if real, err := filepath.EvalSymlinks(fs.Root); err == nil {
75 fs.rootReal = real
76 } else {
77 fs.rootReal = fs.Root
78 }
79 fs.wroot, fs.wErr = os.OpenRoot(fs.Root)
80 })
81 return fs.wroot, fs.wErr
82 }
83
84 // Close applies any outstanding directory metadata on a best-effort basis and
85 // releases the os.Root handle used for writing. It is safe to call even if no
86 // write operation was ever performed. On a successful untar the metadata has
87 // normally been applied by Finalize() already.
88 func (fs *LocalFS) Close() error {
89 err := fs.Finalize()
90 if fs.wroot != nil {
91 if cerr := fs.wroot.Close(); err == nil {
92 err = cerr
93 }
94 }
95 return err
96 }
97
98 // Finalize applies the deferred metadata of all directories that are still
99 // pending, deepest first. It's called at the end of an untar operation, once
100 // no further entries can be written. Safe to call more than once.
101 func (fs *LocalFS) Finalize() error {
102 var err error
103 for _, n := range slices.Backward(fs.pending) {
104 if e := fs.applyDirMetadata(n); e != nil && err == nil {
105 err = e
106 }
107 }
108 fs.pending = nil
109 return err
110 }
111
112 // contains reports whether name refers to something inside the directory dir.
113 // Both are clean slash-separated paths relative to the extraction root, with
114 // "." being the root itself.
115 func contains(dir, name string) bool {
116 return dir == "." || strings.HasPrefix(name, dir+"/")
117 }
118
119 // completeDirs applies the deferred metadata of every pending directory that
120 // doesn't contain name, deepest first. Those directories are complete since
121 // entries arrive depth-first.
122 func (fs *LocalFS) completeDirs(name string) error {
123 for len(fs.pending) > 0 {
124 n := fs.pending[len(fs.pending)-1]
125 if contains(n.Name, name) {
126 return nil
127 }
128 // Only drop it once it's done, so a failure here can still be retried
129 // by the best-effort Finalize() in Close().
130 if err := fs.applyDirMetadata(n); err != nil {
131 return err
132 }
133 fs.pending = fs.pending[:len(fs.pending)-1]
134 }
135 return nil
136 }
137
138 // applyDirMetadata sets owner, xattrs, permissions and timestamps of a
139 // directory that has been fully populated.
140 func (fs *LocalFS) applyDirMetadata(n NodeDirectory) error {
141 r, err := fs.writeRoot()
142 if err != nil {
143 return err
144 }
145 if err := fs.SetDirPermissions(n); err != nil {
146 return err
147 }
148 if n.MTime == time.Unix(0, 0) {
149 return nil
150 }
151 return r.Chtimes(n.Name, n.MTime, n.MTime)
152 }
153
154 func (fs *LocalFS) CreateDir(n NodeDirectory) error {
155 r, err := fs.writeRoot()
156 if err != nil {
157 return err
158 }
159
160 // Everything that isn't an ancestor of this new directory is complete now.
161 if err := fs.completeDirs(n.Name); err != nil {
162 return err
163 }
164
165 // Let's see if there is a dir with the same name already
166 var (
167 created bool
168 existing os.FileMode
169 )
170 if info, err := r.Lstat(n.Name); err == nil {
171 if !info.IsDir() {
172 return fmt.Errorf("%s exists and is not a directory", n.Name)
173 }
174 existing = info.Mode().Perm()
175 } else {
176 // Stat error'ed out, presumably because the dir doesn't exist. Create it.
177 // (n.Name == "." is the extraction root itself, which already exists.)
178 // The mode from the archive is the upper bound of what the directory
179 // gets here, so its contents are never written into a directory more
180 // permissive than the archive says. The exact mode, including any
181 // setuid/setgid/sticky bits, is applied by prepareDirWrite below and
182 // again by applyDirMetadata once the directory is complete.
183 mode := os.FileMode(0777)
184 if !fs.opts.NoSamePermissions {
185 mode = n.Mode.Perm() | 0700
186 }
187 if err := r.Mkdir(n.Name, mode); err != nil {
188 return fmt.Errorf("%s: %w", n.Name, err)
189 }
190 created = true
191 }
192
193 fs.prepareDirWrite(r, n, existing, created)
194
195 // The remaining metadata is applied once the directory is complete. Doing
196 // it now would not only prevent writing into a read-only directory, it'd
197 // also see the timestamps overwritten by those very writes.
198 fs.pending = append(fs.pending, n)
199 return nil
200 }
201
202 func (fs *LocalFS) CreateFile(n NodeFile) error {
203 r, err := fs.writeRoot()
204 if err != nil {
205 return err
206 }
207
208 if err := fs.completeDirs(n.Name); err != nil {
209 return err
210 }
211
212 if err := r.RemoveAll(n.Name); err != nil && !os.IsNotExist(err) {
213 return fmt.Errorf("%s: %w", n.Name, err)
214 }
215 f, err := r.OpenFile(n.Name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
216 if err != nil {
217 return fmt.Errorf("%s: %w", n.Name, err)
218 }
219 defer f.Close()
220 if _, err = io.Copy(f, n.Data); err != nil {
221 return err
222 }
223
224 if err := fs.SetFilePermissions(n); err != nil {
225 return err
226 }
227
228 if n.MTime == time.Unix(0, 0) {
229 return nil
230 }
231 return r.Chtimes(n.Name, n.MTime, n.MTime)
232 }
233
234 func (fs *LocalFS) CreateSymlink(n NodeSymlink) error {
235 r, err := fs.writeRoot()
236 if err != nil {
237 return err
238 }
239
240 if err := fs.completeDirs(n.Name); err != nil {
241 return err
242 }
243
244 if err := r.Remove(n.Name); err != nil && !os.IsNotExist(err) {
245 return fmt.Errorf("%s: %w", n.Name, err)
246 }
247 // The target is stored verbatim (an archive may legitimately contain
248 // absolute or relative symlinks, same as GNU tar/casync). It is never
249 // followed during extraction: subsequent operations go through os.Root,
250 // which refuses to traverse a symlink that escapes the root.
251 if err := r.Symlink(n.Target, n.Name); err != nil {
252 return fmt.Errorf("%s: %w", n.Name, err)
253 }
254
255 if err := fs.SetSymlinkPermissions(n); err != nil {
256 return err
257 }
258
259 return nil
260 }
261
262 type walkEntry struct {
263 path string
264 info os.FileInfo
265 err error
266 }