| 1 | //go:build !js |
| 2 | |
| 3 | package osfs |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | gofs "io/fs" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | |
| 13 | "github.com/go-git/go-billy/v6" |
| 14 | "github.com/go-git/go-billy/v6/helper/chroot" |
| 15 | "github.com/go-git/go-billy/v6/util" |
| 16 | ) |
| 17 | |
| 18 | // FromRoot creates a new [RootOS] from an [os.Root]. |
| 19 | // The provided root is used directly for all operations and the caller |
| 20 | // is responsible for its lifecycle. Root must not be nil. |
| 21 | // |
| 22 | // [WithMmap] enables an mmap-backed [billy.File] from [RootOS.Open] |
| 23 | // (and [RootOS.OpenFile] when opened read-only) on supported |
| 24 | // platforms; all other [Option] values are accepted for API |
| 25 | // compatibility but have no effect. |
| 26 | func FromRoot(root *os.Root, opts ...Option) (*RootOS, error) { |
| 27 | if root == nil { |
| 28 | return nil, errors.New("root must not be nil") |
| 29 | } |
| 30 | o := &options{} |
| 31 | for _, opt := range opts { |
| 32 | opt(o) |
| 33 | } |
| 34 | return &RootOS{root: root, mmap: o.mmap}, nil |
| 35 | } |
| 36 | |
| 37 | // RootOS is a high-performance fs implementation based on a caller-managed |
| 38 | // [os.Root]. Since the root is reused across all operations, this avoids |
| 39 | // the overhead of opening and closing it on every call. The caller is |
| 40 | // responsible for the root's lifecycle. |
| 41 | // |
| 42 | // For automatic lifecycle management at the cost of per-operation overhead, |
| 43 | // use [BoundOS] via [New] instead. |
| 44 | // |
| 45 | // Behaviours of note: |
| 46 | // 1. Read and write operations can only be directed to files which descend |
| 47 | // from the root dir. |
| 48 | // 2. Symlink targets are stored verbatim and not rewritten, so they may |
| 49 | // point outside the root dir or to non-existent paths. [RootOS.Readlink] |
| 50 | // returns the stored target with path separators normalised to forward |
| 51 | // slashes (see [filepath.ToSlash]). |
| 52 | // 3. Operations leading to escapes to outside the [os.Root] location result |
| 53 | // in [ErrPathEscapesParent]. |
| 54 | type RootOS struct { |
| 55 | root *os.Root |
| 56 | mmap bool |
| 57 | } |
| 58 | |
| 59 | func (fs *RootOS) Capabilities() billy.Capability { |
| 60 | return boundCapabilities() |
| 61 | } |
| 62 | |
| 63 | func (fs *RootOS) Create(name string) (billy.File, error) { |
| 64 | return fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, defaultCreateMode) |
| 65 | } |
| 66 | |
| 67 | func (fs *RootOS) OpenFile(name string, flag int, perm gofs.FileMode) (billy.File, error) { |
| 68 | rel := fs.toRelative(name) |
| 69 | display := fs.displayName(name) |
| 70 | |
| 71 | if flag&os.O_CREATE != 0 { |
| 72 | if err := createDir(fs.root, rel); err != nil { |
| 73 | return nil, translateError(err, rel) |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | openName := rel |
| 78 | if openName == "" { |
| 79 | openName = "." |
| 80 | } |
| 81 | f, err := fs.root.OpenFile(openName, flag, perm) |
| 82 | if err == nil { |
| 83 | return fs.wrapOpenedFile(f, display, flag) |
| 84 | } |
| 85 | |
| 86 | // os.Root rejects an absolute symlink target even when it points back |
| 87 | // inside the same root. Resolve that one case to keep existing Billy |
| 88 | // symlink behavior without allowing a real root escape. |
| 89 | if flag&os.O_CREATE == 0 && isPathEscapeError(err) { |
| 90 | escapeErr := err |
| 91 | fi, lstatErr := fs.root.Lstat(openName) |
| 92 | if lstatErr == nil && fi.Mode()&gofs.ModeSymlink != 0 { |
| 93 | if target, readlinkErr := fs.root.Readlink(openName); readlinkErr == nil { |
| 94 | if targetRel, ok := fs.absoluteSymlinkTarget(target); ok { |
| 95 | if f, err = fs.root.OpenFile(targetRel, flag, perm); err == nil { |
| 96 | return fs.wrapOpenedFile(f, display, flag) |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | err = escapeErr |
| 102 | } |
| 103 | |
| 104 | return nil, translateError(err, rel) |
| 105 | } |
| 106 | |
| 107 | // wrapOpenedFile picks the [billy.File] shape for f based on the |
| 108 | // filesystem's [WithMmap] configuration and the open flags. For |
| 109 | // read-only opens on [WithMmap]-configured filesystems on supported |
| 110 | // platforms it returns a [*mmapFile]; in every other case (write |
| 111 | // access, mmap disabled, platforms without mmap support, or mmap |
| 112 | // unavailable for this specific file) it returns the regular [*file] |
| 113 | // wrapper around the underlying [*os.File]. |
| 114 | func (fs *RootOS) wrapOpenedFile(f *os.File, name string, flag int) (billy.File, error) { |
| 115 | if fs.mmap && flag&(os.O_WRONLY|os.O_RDWR) == 0 { |
| 116 | mf, err := newMmapFile(f, name) |
| 117 | if err == nil { |
| 118 | return mf, nil |
| 119 | } |
| 120 | if !errors.Is(err, errMmapUnavailable) { |
| 121 | // Real failure (e.g. stat); newMmapFile already closed f. |
| 122 | return nil, err |
| 123 | } |
| 124 | // Fall through to the regular wrapper. |
| 125 | } |
| 126 | return &file{File: f, name: name}, nil |
| 127 | } |
| 128 | |
| 129 | func (fs *RootOS) ReadDir(name string) ([]gofs.DirEntry, error) { |
| 130 | rel := fs.toRelative(name) |
| 131 | if rel == "" { |
| 132 | rel = "." |
| 133 | } |
| 134 | |
| 135 | f, err := fs.root.Open(rel) |
| 136 | if err != nil { |
| 137 | return nil, translateError(err, rel) |
| 138 | } |
| 139 | defer f.Close() |
| 140 | |
| 141 | e, err := f.ReadDir(-1) |
| 142 | if err != nil { |
| 143 | return nil, translateError(err, rel) |
| 144 | } |
| 145 | return e, nil |
| 146 | } |
| 147 | |
| 148 | func (fs *RootOS) Rename(from, to string) error { |
| 149 | if fs.isBaseDir(from) { |
| 150 | return billy.ErrBaseDirCannotBeRenamed |
| 151 | } |
| 152 | |
| 153 | fromRel := fs.toRelative(from) |
| 154 | toRel := fs.toRelative(to) |
| 155 | |
| 156 | if err := createDir(fs.root, toRel); err != nil { |
| 157 | return translateError(err, toRel) |
| 158 | } |
| 159 | |
| 160 | return translateError(fs.root.Rename(fromRel, toRel), fmt.Sprintf("%s -> %s", fromRel, toRel)) |
| 161 | } |
| 162 | |
| 163 | func (fs *RootOS) MkdirAll(name string, perm gofs.FileMode) error { |
| 164 | rel := fs.toRelative(name) |
| 165 | if rel == "" { |
| 166 | rel = "." |
| 167 | } |
| 168 | |
| 169 | // os.Root errors when perm contains bits other than the nine least-significant bits (0o777). |
| 170 | err := fs.root.MkdirAll(rel, perm&0o777) |
| 171 | return translateError(err, rel) |
| 172 | } |
| 173 | |
| 174 | func (fs *RootOS) Open(name string) (billy.File, error) { |
| 175 | return fs.OpenFile(name, os.O_RDONLY, 0) |
| 176 | } |
| 177 | |
| 178 | func (fs *RootOS) Stat(name string) (os.FileInfo, error) { |
| 179 | rel := fs.toRelative(name) |
| 180 | if rel == "" { |
| 181 | rel = "." |
| 182 | } |
| 183 | |
| 184 | fi, err := fs.root.Stat(rel) |
| 185 | if err != nil { |
| 186 | return nil, translateError(err, rel) |
| 187 | } |
| 188 | |
| 189 | return fileInfo{FileInfo: fi, name: filepath.Base(fs.displayName(name))}, nil |
| 190 | } |
| 191 | |
| 192 | func (fs *RootOS) Remove(name string) error { |
| 193 | if fs.isBaseDir(name) { |
| 194 | return billy.ErrBaseDirCannotBeRemoved |
| 195 | } |
| 196 | |
| 197 | rel := fs.toRelative(name) |
| 198 | err := fs.root.Remove(rel) |
| 199 | if err == nil { |
| 200 | return nil |
| 201 | } |
| 202 | |
| 203 | return translateError(err, rel) |
| 204 | } |
| 205 | |
| 206 | // TempFile creates a temporary file. If dir is empty, the file |
| 207 | // will be created within a .tmp dir. |
| 208 | func (fs *RootOS) TempFile(dir, prefix string) (billy.File, error) { |
| 209 | return util.TempFile(fs, dir, prefix) |
| 210 | } |
| 211 | |
| 212 | func (fs *RootOS) Join(elem ...string) string { |
| 213 | return filepath.Join(elem...) |
| 214 | } |
| 215 | |
| 216 | func (fs *RootOS) RemoveAll(name string) error { |
| 217 | if fs.isBaseDir(name) { |
| 218 | return billy.ErrBaseDirCannotBeRemoved |
| 219 | } |
| 220 | |
| 221 | rel := fs.toRelative(name) |
| 222 | return translateError(fs.root.RemoveAll(rel), rel) |
| 223 | } |
| 224 | |
| 225 | func (fs *RootOS) Symlink(oldname, newname string) error { |
| 226 | newRel := fs.toRelative(newname) |
| 227 | |
| 228 | if err := createDir(fs.root, newRel); err != nil { |
| 229 | return translateError(err, newRel) |
| 230 | } |
| 231 | |
| 232 | return translateError(fs.root.Symlink(oldname, newRel), newRel) |
| 233 | } |
| 234 | |
| 235 | func (fs *RootOS) Lstat(name string) (os.FileInfo, error) { |
| 236 | rel := fs.toRelative(name) |
| 237 | if rel == "" { |
| 238 | rel = "." |
| 239 | } |
| 240 | |
| 241 | fi, err := fs.root.Lstat(rel) |
| 242 | if err != nil { |
| 243 | return nil, translateError(err, rel) |
| 244 | } |
| 245 | |
| 246 | return fileInfo{FileInfo: fi, name: filepath.Base(fs.displayName(name))}, nil |
| 247 | } |
| 248 | |
| 249 | func (fs *RootOS) Readlink(name string) (string, error) { |
| 250 | rel := fs.toRelative(name) |
| 251 | if rel == "" { |
| 252 | rel = "." |
| 253 | } |
| 254 | |
| 255 | lnk, err := fs.root.Readlink(rel) |
| 256 | if err != nil { |
| 257 | return "", translateError(err, rel) |
| 258 | } |
| 259 | |
| 260 | return filepath.ToSlash(lnk), nil |
| 261 | } |
| 262 | |
| 263 | func (fs *RootOS) Chmod(path string, mode gofs.FileMode) error { |
| 264 | rel := fs.toRelative(path) |
| 265 | if rel == "" { |
| 266 | rel = "." |
| 267 | } |
| 268 | return translateError(fs.root.Chmod(rel, mode), rel) |
| 269 | } |
| 270 | |
| 271 | // Chroot returns a logical sub-filesystem rooted at the result of joining |
| 272 | // the provided path with the underlying root dir. The returned filesystem |
| 273 | // reuses this [RootOS]'s [os.Root] (no new file descriptor is opened), |
| 274 | // so its lifecycle is tied to the parent root managed by the caller. |
| 275 | // |
| 276 | // If path does not yet exist under the parent root it is created (with |
| 277 | // [defaultDirectoryMode]). If path exists but is not a directory an error |
| 278 | // is returned. |
| 279 | // |
| 280 | // Containment is enforced by the parent [os.Root], not by the chroot |
| 281 | // path: operations cannot escape the parent root, but a symlink within |
| 282 | // the chroot may resolve to a sibling location elsewhere under the |
| 283 | // parent root. For a tighter boundary at the chroot path, open a new |
| 284 | // [os.Root] via [os.OpenRoot] and wrap it with [FromRoot]. |
| 285 | func (fs *RootOS) Chroot(path string) (billy.Filesystem, error) { |
| 286 | rel := fs.toRelative(path) |
| 287 | if rel == "" { |
| 288 | rel = "." |
| 289 | } |
| 290 | |
| 291 | if err := ensureDir(fs.root, rel); err != nil { |
| 292 | return nil, err |
| 293 | } |
| 294 | |
| 295 | return chroot.New(fs, filepath.Join(fs.root.Name(), rel)), nil |
| 296 | } |
| 297 | |
| 298 | // Root returns the current root dir of the filesystem. |
| 299 | func (fs *RootOS) Root() string { |
| 300 | return fs.root.Name() |
| 301 | } |
| 302 | |
| 303 | func (fs *RootOS) displayName(name string) string { |
| 304 | name = hostPath(name) |
| 305 | if filepath.IsAbs(name) && isHostRoot(fs.root.Name()) { |
| 306 | return filepath.Clean(name) |
| 307 | } |
| 308 | |
| 309 | rel := fs.toRelative(name) |
| 310 | if rel == "" { |
| 311 | return "." |
| 312 | } |
| 313 | return rel |
| 314 | } |
| 315 | |
| 316 | func (fs *RootOS) isBaseDir(name string) bool { |
| 317 | rel := fs.toRelative(name) |
| 318 | return rel == "" || rel == "." |
| 319 | } |
| 320 | |
| 321 | func (fs *RootOS) toRelative(name string) string { |
| 322 | if name == "" { |
| 323 | return "" |
| 324 | } |
| 325 | |
| 326 | name = hostPath(name) |
| 327 | if filepath.IsAbs(name) { |
| 328 | if rel, ok := relativeInsideBase(fs.root.Name(), name); ok { |
| 329 | return cleanUnderRoot(rel) |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | return cleanUnderRoot(name) |
| 334 | } |
| 335 | |
| 336 | func (fs *RootOS) absoluteSymlinkTarget(target string) (string, bool) { |
| 337 | if !isRootedPath(target) { |
| 338 | return "", false |
| 339 | } |
| 340 | target = hostPath(target) |
| 341 | rel, ok := relativeInsideBase(fs.root.Name(), target) |
| 342 | if !ok { |
| 343 | rel = cleanUnderRoot(target) |
| 344 | } |
| 345 | if rel == "" { |
| 346 | return ".", true |
| 347 | } |
| 348 | return cleanUnderRoot(rel), true |
| 349 | } |
| 350 | |
| 351 | func relativeInsideBase(base, name string) (string, bool) { |
| 352 | base = hostPath(base) |
| 353 | name = hostPath(name) |
| 354 | rel, err := filepath.Rel(filepath.Clean(base), filepath.Clean(name)) |
| 355 | if err != nil { |
| 356 | return "", false |
| 357 | } |
| 358 | if rel == "." { |
| 359 | return "", true |
| 360 | } |
| 361 | if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { |
| 362 | return "", false |
| 363 | } |
| 364 | return rel, true |
| 365 | } |
| 366 | |
| 367 | func isRootedPath(name string) bool { |
| 368 | name = hostPath(name) |
| 369 | if filepath.IsAbs(name) { |
| 370 | return true |
| 371 | } |
| 372 | return strings.HasPrefix(name, string(filepath.Separator)) |
| 373 | } |
| 374 | |
| 375 | func cleanUnderRoot(name string) string { |
| 376 | name = hostPath(name) |
| 377 | vol := filepath.VolumeName(name) |
| 378 | name = name[len(vol):] |
| 379 | name = filepath.Join(string(filepath.Separator), name) |
| 380 | return strings.TrimLeft(name, string(filepath.Separator)) |
| 381 | } |
| 382 | |
| 383 | func hostPath(name string) string { |
| 384 | name = filepath.FromSlash(name) |
| 385 | if filepath.Separator == '\\' && len(name) >= 3 && |
| 386 | name[0] == '\\' && name[2] == ':' { |
| 387 | return name[1:] |
| 388 | } |
| 389 | return name |
| 390 | } |
| 391 | |
| 392 | func isHostRoot(name string) bool { |
| 393 | name = filepath.Clean(hostPath(name)) |
| 394 | if !filepath.IsAbs(name) && !strings.HasPrefix(name, string(filepath.Separator)) { |
| 395 | return false |
| 396 | } |
| 397 | return filepath.Dir(name) == name |
| 398 | } |
| 399 | |
| 400 | func ensureDir(root *os.Root, path string) error { |
| 401 | fi, err := root.Lstat(path) |
| 402 | if errors.Is(err, os.ErrNotExist) { |
| 403 | if err := root.MkdirAll(path, defaultDirectoryMode); err != nil { |
| 404 | return fmt.Errorf("failed to auto create dir: %w", translateError(err, path)) |
| 405 | } |
| 406 | return nil |
| 407 | } |
| 408 | if err != nil { |
| 409 | return translateError(err, path) |
| 410 | } |
| 411 | if fi != nil && !fi.IsDir() { |
| 412 | return fmt.Errorf("cannot chroot: %q is not a dir (mode %s)", path, fi.Mode()) |
| 413 | } |
| 414 | return nil |
| 415 | } |
| 416 | |
| 417 | func createDir(root *os.Root, fullpath string) error { |
| 418 | dir := filepath.Dir(fullpath) |
| 419 | if dir != "." { |
| 420 | if err := root.MkdirAll(dir, defaultDirectoryMode); err != nil { |
| 421 | if errors.Is(err, os.ErrExist) { |
| 422 | return nil |
| 423 | } |
| 424 | return err |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | return nil |
| 429 | } |
| 430 | |
| 431 | func isPathEscapeError(err error) bool { |
| 432 | return err != nil && strings.Contains(err.Error(), ErrPathEscapesParent.Error()) |
| 433 | } |
| 434 | |
| 435 | func translateError(err error, file string) error { |
| 436 | if err == nil { |
| 437 | return nil |
| 438 | } |
| 439 | |
| 440 | if isPathEscapeError(err) { |
| 441 | return fmt.Errorf("%w: %q", ErrPathEscapesParent, file) |
| 442 | } |
| 443 | |
| 444 | return err |
| 445 | } |