浏览文件
nofollow.go
64 行 · 1.9 KB历史下载| 1 | package env |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "strings" |
| 6 | ) |
| 7 | |
| 8 | // The ways a NoFollow call fails. |
| 9 | var ( |
| 10 | // ErrNoFile: the file is not there (Read only). |
| 11 | ErrNoFile = errors.New("no such file") |
| 12 | // ErrUnsafe: a symlink, or something other than a folder or a regular |
| 13 | // file, is on the way. |
| 14 | ErrUnsafe = errors.New("a symlink, or not a regular file or folder, on the way") |
| 15 | ) |
| 16 | |
| 17 | // The NoFollow operations, each on top/rel, following no symlink below top: |
| 18 | // the one way the host touches the project, which the VM can write. Through |
| 19 | // a link planted there, a plain read would copy any file of the user's into |
| 20 | // the project, and a write could land anywhere; checking for links first is |
| 21 | // not enough, the VM can swap one in between the check and the use. |
| 22 | // |
| 23 | // Missing folders are made, except by Read. Write replaces the file with a |
| 24 | // new one, mode 600, renamed over it: a link there is replaced, not followed. |
| 25 | |
| 26 | // ReadIn is the content of top/rel. |
| 27 | func ReadIn(top, rel string) ([]byte, error) { return noFollow("read", top, rel, nil) } |
| 28 | |
| 29 | // WriteIn replaces top/rel with data. |
| 30 | func WriteIn(top, rel string, data []byte) error { |
| 31 | _, err := noFollow("write", top, rel, data) |
| 32 | return err |
| 33 | } |
| 34 | |
| 35 | // MkdirIn makes the folder top/rel and those above it. |
| 36 | func MkdirIn(top, rel string) error { |
| 37 | _, err := noFollow("mkdir", top, rel, nil) |
| 38 | return err |
| 39 | } |
| 40 | |
| 41 | // TouchIn makes top/rel an empty file unless it is a regular file already. |
| 42 | func TouchIn(top, rel string) error { |
| 43 | _, err := noFollow("touch", top, rel, nil) |
| 44 | return err |
| 45 | } |
| 46 | |
| 47 | // split is rel's folders and its last name; ErrUnsafe for ".." anywhere, or |
| 48 | // no name. |
| 49 | func split(rel string) (dirs []string, name string, err error) { |
| 50 | for _, c := range strings.Split(rel, "/") { |
| 51 | if c != "" && c != "." { |
| 52 | dirs = append(dirs, c) |
| 53 | } |
| 54 | } |
| 55 | if len(dirs) == 0 { |
| 56 | return nil, "", ErrUnsafe |
| 57 | } |
| 58 | for _, c := range dirs { |
| 59 | if c == ".." { |
| 60 | return nil, "", ErrUnsafe |
| 61 | } |
| 62 | } |
| 63 | return dirs[:len(dirs)-1], dirs[len(dirs)-1], nil |
| 64 | } |

