Debian Codegraph @

osfs/os_bound.go

raw symbols SCIP
1 //go:build !js
2
3 /*
4 Copyright 2022 The Flux authors.
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17 */
18
19 package osfs
20
21 import (
22 "errors"
23 gofs "io/fs"
24 "os"
25 "path/filepath"
26
27 "github.com/go-git/go-billy/v6"
28 "github.com/go-git/go-billy/v6/util"
29 )
30
31 // BoundOS is a fs implementation based on the OS filesystem which relies on
32 // Go's [os.Root]. A new [os.Root] is opened and closed for each filesystem
33 // operation to avoid holding a directory handle open.
34 //
35 // For better performance, prefer [RootOS] via [FromRoot] with a
36 // caller-managed [os.Root].
37 //
38 // Behaviours of note:
39 // 1. Read and write operations can only be directed to files which descend
40 // from the base dir.
41 // 2. Symlink targets are stored verbatim and not rewritten, so they may
42 // point outside the base dir or to non-existent paths. [BoundOS.Readlink]
43 // returns the stored target with path separators normalised to forward
44 // slashes (see [filepath.ToSlash]).
45 // 3. Operations leading to escapes to outside the [os.Root] location result
46 // in [ErrPathEscapesParent].
47 type BoundOS struct {
48 baseDir string
49 mmap bool
50 }
51
52 func newBoundOS(d string) *BoundOS {
53 if d == "" {
54 d = string(os.PathSeparator)
55 }
56 d = hostPath(d)
57 return &BoundOS{baseDir: d}
58 }
59
60 // clone returns a new [BoundOS] rooted at d that carries over fs's
61 // configurable behaviour (currently just the [WithMmap] flag). Used
62 // to construct sub-filesystems via [BoundOS.Chroot] without silently
63 // dropping caller-supplied options.
64 func (fs *BoundOS) clone(d string) *BoundOS {
65 if d == "" {
66 d = string(os.PathSeparator)
67 }
68 return &BoundOS{baseDir: hostPath(d), mmap: fs.mmap}
69 }
70
71 // rootFS opens a temporary [RootOS] and returns a cleanup function that
72 // closes the underlying [os.Root].
73 func (fs *BoundOS) rootFS() (*RootOS, func(), error) {
74 return fs.rootFSWithCreate("", false)
75 }
76
77 func (fs *BoundOS) rootFSWithCreate(name string, createBase bool) (*RootOS, func(), error) {
78 rootPath := fs.operationRoot(name)
79 r, err := openRootAt(rootPath, createBase)
80 if err != nil {
81 return nil, func() {}, err
82 }
83 return &RootOS{root: r, mmap: fs.mmap}, func() { r.Close() }, nil
84 }
85
86 func (fs *BoundOS) Capabilities() billy.Capability {
87 return boundCapabilities()
88 }
89
90 func (fs *BoundOS) Create(name string) (billy.File, error) {
91 return fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, defaultCreateMode)
92 }
93
94 func (fs *BoundOS) OpenFile(name string, flag int, perm gofs.FileMode) (billy.File, error) {
95 rfs, cleanup, err := fs.rootFSWithCreate(name, flag&os.O_CREATE != 0)
96 if err != nil {
97 return nil, err
98 }
99 defer cleanup()
100 return rfs.OpenFile(name, flag, perm)
101 }
102
103 func (fs *BoundOS) ReadDir(name string) ([]gofs.DirEntry, error) {
104 rfs, cleanup, err := fs.rootFSWithCreate(name, false)
105 if err != nil {
106 return nil, err
107 }
108 defer cleanup()
109 return rfs.ReadDir(name)
110 }
111
112 func (fs *BoundOS) Rename(from, to string) error {
113 rfs, cleanup, err := fs.rootFSWithCreate(from, false)
114 if err != nil {
115 return err
116 }
117 defer cleanup()
118 return rfs.Rename(from, to)
119 }
120
121 func (fs *BoundOS) MkdirAll(name string, perm gofs.FileMode) error {
122 rfs, cleanup, err := fs.rootFSWithCreate(name, true)
123 if err != nil {
124 return err
125 }
126 defer cleanup()
127 return rfs.MkdirAll(name, perm)
128 }
129
130 func (fs *BoundOS) Open(name string) (billy.File, error) {
131 return fs.OpenFile(name, os.O_RDONLY, 0)
132 }
133
134 func (fs *BoundOS) Stat(name string) (os.FileInfo, error) {
135 if fs.isBaseDir(name) {
136 return fs.baseInfo(false)
137 }
138
139 rfs, cleanup, err := fs.rootFSWithCreate(name, false)
140 if err != nil {
141 return nil, err
142 }
143 defer cleanup()
144 return rfs.Stat(name)
145 }
146
147 func (fs *BoundOS) Remove(name string) error {
148 rfs, cleanup, err := fs.rootFSWithCreate(name, false)
149 if err != nil {
150 return err
151 }
152 defer cleanup()
153 return rfs.Remove(name)
154 }
155
156 // TempFile creates a temporary file. If dir is empty, the file
157 // will be created within a .tmp dir.
158 func (fs *BoundOS) TempFile(dir, prefix string) (billy.File, error) {
159 return util.TempFile(fs, dir, prefix)
160 }
161
162 func (fs *BoundOS) Join(elem ...string) string {
163 return filepath.Join(elem...)
164 }
165
166 func (fs *BoundOS) RemoveAll(name string) error {
167 rfs, cleanup, err := fs.rootFSWithCreate(name, false)
168 if err != nil {
169 return err
170 }
171 defer cleanup()
172 return rfs.RemoveAll(name)
173 }
174
175 func (fs *BoundOS) Symlink(oldname, newname string) error {
176 rfs, cleanup, err := fs.rootFSWithCreate(newname, true)
177 if err != nil {
178 return err
179 }
180 defer cleanup()
181 return rfs.Symlink(oldname, newname)
182 }
183
184 func (fs *BoundOS) Lstat(name string) (os.FileInfo, error) {
185 if fs.isBaseDir(name) {
186 return fs.baseInfo(true)
187 }
188
189 rfs, cleanup, err := fs.rootFSWithCreate(name, false)
190 if err != nil {
191 return nil, err
192 }
193 defer cleanup()
194 return rfs.Lstat(name)
195 }
196
197 func (fs *BoundOS) Readlink(name string) (string, error) {
198 rfs, cleanup, err := fs.rootFSWithCreate(name, false)
199 if err != nil {
200 return "", err
201 }
202 defer cleanup()
203 return rfs.Readlink(name)
204 }
205
206 func (fs *BoundOS) Chmod(path string, mode gofs.FileMode) error {
207 rfs, cleanup, err := fs.rootFSWithCreate(path, false)
208 if err != nil {
209 return err
210 }
211 defer cleanup()
212 return rfs.Chmod(path, mode)
213 }
214
215 // Chroot returns a new [BoundOS] filesystem, with the base dir set to the
216 // result of joining the provided path with the underlying base dir.
217 func (fs *BoundOS) Chroot(path string) (billy.Filesystem, error) {
218 if hostPath, ok := fs.hostAbsolutePath(path); ok {
219 return fs.clone(hostPath), nil
220 }
221
222 rfs, cleanup, err := fs.rootFS()
223 if err != nil {
224 if errors.Is(err, os.ErrNotExist) {
225 return fs.clone(fs.chrootPath(path)), nil
226 }
227 return nil, err
228 }
229 defer cleanup()
230
231 rel := rfs.toRelative(path)
232 if rel == "" {
233 rel = "."
234 }
235 childRoot, err := rfs.root.OpenRoot(rel)
236 if err != nil {
237 if errors.Is(err, os.ErrNotExist) {
238 return fs.clone(fs.chrootPath(path)), nil
239 }
240 return nil, err
241 }
242 defer childRoot.Close()
243
244 return fs.clone(filepath.Clean(childRoot.Name())), nil
245 }
246
247 // Root returns the current base dir of the billy.Filesystem.
248 func (fs *BoundOS) Root() string {
249 return fs.baseDir
250 }
251
252 func (fs *BoundOS) isBaseDir(name string) bool {
253 if name == "" {
254 return true
255 }
256
257 name = hostPath(name)
258 if filepath.IsAbs(name) {
259 if rel, ok := relativeInsideBase(fs.baseDir, name); ok {
260 return cleanUnderRoot(rel) == ""
261 }
262 }
263
264 return cleanUnderRoot(name) == ""
265 }
266
267 func (fs *BoundOS) chrootPath(path string) string {
268 if hostPath, ok := fs.hostAbsolutePath(path); ok {
269 return filepath.Clean(hostPath)
270 }
271
272 path = hostPath(path)
273 if filepath.IsAbs(path) {
274 if rel, ok := relativeInsideBase(fs.baseDir, path); ok {
275 return filepath.Clean(filepath.Join(fs.baseDir, rel))
276 }
277 }
278
279 return filepath.Clean(filepath.Join(fs.baseDir, cleanUnderRoot(path)))
280 }
281
282 func (fs *BoundOS) hostAbsolutePath(path string) (string, bool) {
283 if fs.baseDir != string(os.PathSeparator) {
284 return "", false
285 }
286
287 path = hostPath(path)
288 if filepath.VolumeName(path) != "" && filepath.IsAbs(path) {
289 return path, true
290 }
291
292 return "", false
293 }
294
295 func (fs *BoundOS) operationRoot(path string) string {
296 if hostPath, ok := fs.hostAbsolutePath(path); ok {
297 vol := filepath.VolumeName(hostPath)
298 if vol != "" {
299 return vol + string(filepath.Separator)
300 }
301 }
302
303 return fs.baseDir
304 }
305
306 func (fs *BoundOS) baseInfo(lstat bool) (os.FileInfo, error) {
307 base := filepath.Clean(fs.baseDir)
308 parent := filepath.Dir(base)
309 name := filepath.Base(base)
310
311 if parent == base {
312 root, err := openRootAt(base, false)
313 if err != nil {
314 return nil, err
315 }
316 defer root.Close()
317 if lstat {
318 return root.Lstat(".")
319 }
320 return root.Stat(".")
321 }
322
323 root, err := openRootAt(parent, false)
324 if err != nil {
325 return nil, err
326 }
327 defer root.Close()
328 if lstat {
329 return root.Lstat(name)
330 }
331 return root.Stat(name)
332 }
333
334 func openRootAt(path string, create bool) (*os.Root, error) {
335 path = filepath.Clean(path)
336 root, err := os.OpenRoot(path)
337 if err == nil || !create || !errors.Is(err, os.ErrNotExist) {
338 return root, err
339 }
340
341 ancestor, rel, err := openExistingAncestor(path)
342 if err != nil {
343 return nil, err
344 }
345 defer ancestor.Close()
346
347 if rel != "." {
348 if err := ancestor.MkdirAll(rel, defaultDirectoryMode); err != nil {
349 return nil, err
350 }
351 }
352
353 return os.OpenRoot(path)
354 }
355
356 func openExistingAncestor(path string) (*os.Root, string, error) {
357 path = filepath.Clean(path)
358 ancestorPath := path
359
360 for {
361 root, err := os.OpenRoot(ancestorPath)
362 if err == nil {
363 rel, relErr := filepath.Rel(ancestorPath, path)
364 if relErr != nil {
365 root.Close()
366 return nil, "", relErr
367 }
368 return root, rel, nil
369 }
370 if !errors.Is(err, os.ErrNotExist) {
371 return nil, "", err
372 }
373
374 parent := filepath.Dir(ancestorPath)
375 if parent == ancestorPath {
376 return nil, "", err
377 }
378 ancestorPath = parent
379 }
380 }