浏览文件
file.go
72 行 · 2.3 KB历史下载| 1 | // SPDX-FileCopyrightText: Copyright The Lima Authors |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| 4 | package osutil |
| 5 | |
| 6 | import ( |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | ) |
| 12 | |
| 13 | // FileExists reports whether path exists and is accessible. |
| 14 | // It returns true for any non-ErrNotExist stat result, including permission errors. |
| 15 | func FileExists(path string) bool { |
| 16 | _, err := os.Stat(path) |
| 17 | return !errors.Is(err, os.ErrNotExist) |
| 18 | } |
| 19 | |
| 20 | // Touch touches a file. |
| 21 | func Touch(path string) error { |
| 22 | f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644) |
| 23 | if err != nil { |
| 24 | return err |
| 25 | } |
| 26 | return f.Close() |
| 27 | } |
| 28 | |
| 29 | // RemoveStaleSocket removes path so a fresh listener can bind to it, but only |
| 30 | // when path is a Unix domain socket. A hostSocket comes from the instance |
| 31 | // config (which may originate from an untrusted template) and is validated only |
| 32 | // as an absolute path, so it can point at an existing directory or regular |
| 33 | // file. os.RemoveAll on such a path would delete it recursively; here anything |
| 34 | // that is not a socket is left in place and an error is returned instead. A |
| 35 | // non-existent path is not an error. |
| 36 | func RemoveStaleSocket(path string) error { |
| 37 | fi, err := os.Lstat(path) |
| 38 | if err != nil { |
| 39 | if errors.Is(err, os.ErrNotExist) { |
| 40 | return nil |
| 41 | } |
| 42 | return err |
| 43 | } |
| 44 | if fi.Mode()&os.ModeSocket == 0 { |
| 45 | return fmt.Errorf("refusing to remove %#q: not a socket (%s)", path, fi.Mode().Type()) |
| 46 | } |
| 47 | return os.Remove(path) |
| 48 | } |
| 49 | |
| 50 | // WriteFileBeneathDir writes data to name without following a symlink at the |
| 51 | // final path component. It is meant for destinations that untrusted code may be |
| 52 | // able to write to, e.g. a path inside a writable mount: a symlink planted at |
| 53 | // name (say pointing at ~/.ssh/authorized_keys) would otherwise get the bytes |
| 54 | // written through the link to a file outside the intended directory. |
| 55 | // os.OpenRoot confines the write to name's parent directory, so a symlink whose |
| 56 | // target escapes that directory is refused. |
| 57 | func WriteFileBeneathDir(name string, data []byte, perm os.FileMode) error { |
| 58 | root, err := os.OpenRoot(filepath.Dir(name)) |
| 59 | if err != nil { |
| 60 | return err |
| 61 | } |
| 62 | defer root.Close() |
| 63 | f, err := root.OpenFile(filepath.Base(name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) |
| 64 | if err != nil { |
| 65 | return err |
| 66 | } |
| 67 | if _, err := f.Write(data); err != nil { |
| 68 | _ = f.Close() |
| 69 | return err |
| 70 | } |
| 71 | return f.Close() |
| 72 | } |

