|
| 1 | +package agent |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "net/http" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "regexp" |
| 9 | + "runtime" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/shirou/gopsutil/v4/disk" |
| 13 | + "golang.org/x/xerrors" |
| 14 | + |
| 15 | + "github.com/coder/coder/v2/coderd/httpapi" |
| 16 | + "github.com/coder/coder/v2/codersdk" |
| 17 | +) |
| 18 | + |
| 19 | +var WindowsDriveRegex = regexp.MustCompile(`^[a-zA-Z]:\\$`) |
| 20 | + |
| 21 | +func (*agent) HandleLS(rw http.ResponseWriter, r *http.Request) { |
| 22 | + ctx := r.Context() |
| 23 | + |
| 24 | + var query LSRequest |
| 25 | + if !httpapi.Read(ctx, rw, r, &query) { |
| 26 | + return |
| 27 | + } |
| 28 | + |
| 29 | + resp, err := listFiles(query) |
| 30 | + if err != nil { |
| 31 | + status := http.StatusInternalServerError |
| 32 | + switch { |
| 33 | + case errors.Is(err, os.ErrNotExist): |
| 34 | + status = http.StatusNotFound |
| 35 | + case errors.Is(err, os.ErrPermission): |
| 36 | + status = http.StatusForbidden |
| 37 | + default: |
| 38 | + } |
| 39 | + httpapi.Write(ctx, rw, status, codersdk.Response{ |
| 40 | + Message: err.Error(), |
| 41 | + }) |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + httpapi.Write(ctx, rw, http.StatusOK, resp) |
| 46 | +} |
| 47 | + |
| 48 | +func listFiles(query LSRequest) (LSResponse, error) { |
| 49 | + var fullPath []string |
| 50 | + switch query.Relativity { |
| 51 | + case LSRelativityHome: |
| 52 | + home, err := os.UserHomeDir() |
| 53 | + if err != nil { |
| 54 | + return LSResponse{}, xerrors.Errorf("failed to get user home directory: %w", err) |
| 55 | + } |
| 56 | + fullPath = []string{home} |
| 57 | + case LSRelativityRoot: |
| 58 | + if runtime.GOOS == "windows" { |
| 59 | + if len(query.Path) == 0 { |
| 60 | + return listDrives() |
| 61 | + } |
| 62 | + if !WindowsDriveRegex.MatchString(query.Path[0]) { |
| 63 | + return LSResponse{}, xerrors.Errorf("invalid drive letter %q", query.Path[0]) |
| 64 | + } |
| 65 | + } else { |
| 66 | + fullPath = []string{"/"} |
| 67 | + } |
| 68 | + default: |
| 69 | + return LSResponse{}, xerrors.Errorf("unsupported relativity type %q", query.Relativity) |
| 70 | + } |
| 71 | + |
| 72 | + fullPath = append(fullPath, query.Path...) |
| 73 | + fullPathRelative := filepath.Join(fullPath...) |
| 74 | + absolutePathString, err := filepath.Abs(fullPathRelative) |
| 75 | + if err != nil { |
| 76 | + return LSResponse{}, xerrors.Errorf("failed to get absolute path of %q: %w", fullPathRelative, err) |
| 77 | + } |
| 78 | + |
| 79 | + f, err := os.Open(absolutePathString) |
| 80 | + if err != nil { |
| 81 | + return LSResponse{}, xerrors.Errorf("failed to open directory %q: %w", absolutePathString, err) |
| 82 | + } |
| 83 | + defer f.Close() |
| 84 | + |
| 85 | + stat, err := f.Stat() |
| 86 | + if err != nil { |
| 87 | + return LSResponse{}, xerrors.Errorf("failed to stat directory %q: %w", absolutePathString, err) |
| 88 | + } |
| 89 | + |
| 90 | + if !stat.IsDir() { |
| 91 | + return LSResponse{}, xerrors.Errorf("path %q is not a directory", absolutePathString) |
| 92 | + } |
| 93 | + |
| 94 | + // `contents` may be partially populated even if the operation fails midway. |
| 95 | + contents, _ := f.ReadDir(-1) |
| 96 | + respContents := make([]LSFile, 0, len(contents)) |
| 97 | + for _, file := range contents { |
| 98 | + respContents = append(respContents, LSFile{ |
| 99 | + Name: file.Name(), |
| 100 | + AbsolutePathString: filepath.Join(absolutePathString, file.Name()), |
| 101 | + IsDir: file.IsDir(), |
| 102 | + }) |
| 103 | + } |
| 104 | + |
| 105 | + absolutePath := pathToArray(absolutePathString) |
| 106 | + |
| 107 | + return LSResponse{ |
| 108 | + AbsolutePath: absolutePath, |
| 109 | + AbsolutePathString: absolutePathString, |
| 110 | + Contents: respContents, |
| 111 | + }, nil |
| 112 | +} |
| 113 | + |
| 114 | +func listDrives() (LSResponse, error) { |
| 115 | + partitionStats, err := disk.Partitions(true) |
| 116 | + if err != nil { |
| 117 | + return LSResponse{}, xerrors.Errorf("failed to get partitions: %w", err) |
| 118 | + } |
| 119 | + contents := make([]LSFile, 0, len(partitionStats)) |
| 120 | + for _, a := range partitionStats { |
| 121 | + // Drive letters on Windows have a trailing separator as part of their name. |
| 122 | + // i.e. `os.Open("C:")` does not work, but `os.Open("C:\\")` does. |
| 123 | + name := a.Mountpoint + string(os.PathSeparator) |
| 124 | + contents = append(contents, LSFile{ |
| 125 | + Name: name, |
| 126 | + AbsolutePathString: name, |
| 127 | + IsDir: true, |
| 128 | + }) |
| 129 | + } |
| 130 | + |
| 131 | + return LSResponse{ |
| 132 | + AbsolutePath: []string{}, |
| 133 | + AbsolutePathString: "", |
| 134 | + Contents: contents, |
| 135 | + }, nil |
| 136 | +} |
| 137 | + |
| 138 | +func pathToArray(path string) []string { |
| 139 | + out := strings.FieldsFunc(path, func(r rune) bool { |
| 140 | + return r == os.PathSeparator |
| 141 | + }) |
| 142 | + // Drive letters on Windows have a trailing separator as part of their name. |
| 143 | + // i.e. `os.Open("C:")` does not work, but `os.Open("C:\\")` does. |
| 144 | + if runtime.GOOS == "windows" && len(out) > 0 { |
| 145 | + out[0] += string(os.PathSeparator) |
| 146 | + } |
| 147 | + return out |
| 148 | +} |
| 149 | + |
| 150 | +type LSRequest struct { |
| 151 | + // e.g. [], ["repos", "coder"], |
| 152 | + Path []string `json:"path"` |
| 153 | + // Whether the supplied path is relative to the user's home directory, |
| 154 | + // or the root directory. |
| 155 | + Relativity LSRelativity `json:"relativity"` |
| 156 | +} |
| 157 | + |
| 158 | +type LSResponse struct { |
| 159 | + AbsolutePath []string `json:"absolute_path"` |
| 160 | + // Returned so clients can display the full path to the user, and |
| 161 | + // copy it to configure file sync |
| 162 | + // e.g. Windows: "C:\\Users\\coder" |
| 163 | + // Linux: "/home/coder" |
| 164 | + AbsolutePathString string `json:"absolute_path_string"` |
| 165 | + Contents []LSFile `json:"contents"` |
| 166 | +} |
| 167 | + |
| 168 | +type LSFile struct { |
| 169 | + Name string `json:"name"` |
| 170 | + // e.g. "C:\\Users\\coder\\hello.txt" |
| 171 | + // "/home/coder/hello.txt" |
| 172 | + AbsolutePathString string `json:"absolute_path_string"` |
| 173 | + IsDir bool `json:"is_dir"` |
| 174 | +} |
| 175 | + |
| 176 | +type LSRelativity string |
| 177 | + |
| 178 | +const ( |
| 179 | + LSRelativityRoot LSRelativity = "root" |
| 180 | + LSRelativityHome LSRelativity = "home" |
| 181 | +) |
0 commit comments