| 1 | package standalone |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/url" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "regexp" |
| 12 | "runtime" |
| 13 | "strings" |
| 14 | |
| 15 | "github.com/git-lfs/git-lfs/v3/config" |
| 16 | "github.com/git-lfs/git-lfs/v3/errors" |
| 17 | "github.com/git-lfs/git-lfs/v3/lfs" |
| 18 | "github.com/git-lfs/git-lfs/v3/lfsapi" |
| 19 | "github.com/git-lfs/git-lfs/v3/subprocess" |
| 20 | "github.com/git-lfs/git-lfs/v3/tools" |
| 21 | "github.com/git-lfs/git-lfs/v3/tr" |
| 22 | "github.com/rubyist/tracerx" |
| 23 | ) |
| 24 | |
| 25 | // inputMessage represents a message from Git LFS to the standalone transfer |
| 26 | // agent. Not all fields will be filled in on all requests. |
| 27 | type inputMessage struct { |
| 28 | Event string `json:"event"` |
| 29 | Operation string `json:"operation"` |
| 30 | Remote string `json:"remote"` |
| 31 | Oid string `json:"oid"` |
| 32 | Size int64 `json:"size"` |
| 33 | Path string `json:"path"` |
| 34 | } |
| 35 | |
| 36 | // errorMessage represents an optional error message that may occur in a |
| 37 | // completion response. |
| 38 | type errorMessage struct { |
| 39 | Message string `json:"message"` |
| 40 | } |
| 41 | |
| 42 | // outputErrorMessage represents an error message that may occur during startup. |
| 43 | type outputErrorMessage struct { |
| 44 | Error errorMessage `json:"error"` |
| 45 | } |
| 46 | |
| 47 | // completeMessage represents a completion response. |
| 48 | type completeMessage struct { |
| 49 | Event string `json:"event"` |
| 50 | Oid string `json:"oid"` |
| 51 | Path string `json:"path,omitempty"` |
| 52 | Error *errorMessage `json:"error,omitempty"` |
| 53 | } |
| 54 | |
| 55 | type fileHandler struct { |
| 56 | remotePath string |
| 57 | remoteConfig *config.Configuration |
| 58 | output *os.File |
| 59 | config *config.Configuration |
| 60 | tempdir string |
| 61 | } |
| 62 | |
| 63 | // fileUrlFromRemote looks up the URL depending on the remote. The remote can be |
| 64 | // a literal URL or the name of a remote. |
| 65 | // |
| 66 | // In this situation, we only accept file URLs. |
| 67 | func fileUrlFromRemote(cfg *config.Configuration, name string, direction string) (*url.URL, error) { |
| 68 | if strings.HasPrefix(name, "file://") { |
| 69 | if url, err := url.Parse(name); err == nil { |
| 70 | return url, nil |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | apiClient := lfsapi.NewClient(cfg) |
| 75 | defer apiClient.Close() |
| 76 | |
| 77 | for _, remote := range cfg.Remotes() { |
| 78 | if remote != name { |
| 79 | continue |
| 80 | } |
| 81 | remoteEndpoint := apiClient.Endpoints.Endpoint(direction, remote) |
| 82 | if !strings.HasPrefix(remoteEndpoint.Url, "file://") { |
| 83 | return nil, nil |
| 84 | } |
| 85 | return url.Parse(remoteEndpoint.Url) |
| 86 | } |
| 87 | return nil, nil |
| 88 | } |
| 89 | |
| 90 | // gitDirAtPath finds the .git directory corresponding to the given path, which |
| 91 | // may be the .git directory itself, the working tree, or the root of a bare |
| 92 | // repository. |
| 93 | // |
| 94 | // We filter out the GIT_DIR environment variable to ensure we get the expected |
| 95 | // result, and we change directories to ensure that we can make use of |
| 96 | // filepath.Abs. Using --absolute-git-dir instead of --git-dir is not an option |
| 97 | // because we support Git versions that don't have --absolute-git-dir. |
| 98 | func gitDirAtPath(path string) (string, error) { |
| 99 | // Filter out all the GIT_* environment variables. |
| 100 | env := os.Environ() |
| 101 | n := 0 |
| 102 | for _, val := range env { |
| 103 | if !strings.HasPrefix(val, "GIT_") { |
| 104 | env[n] = val |
| 105 | n++ |
| 106 | } |
| 107 | } |
| 108 | env = env[:n] |
| 109 | |
| 110 | // Trim any trailing .git path segment. |
| 111 | if filepath.Base(path) == ".git" { |
| 112 | path = filepath.Dir(path) |
| 113 | } |
| 114 | |
| 115 | curdir, err := os.Getwd() |
| 116 | if err != nil { |
| 117 | return "", err |
| 118 | } |
| 119 | |
| 120 | err = os.Chdir(path) |
| 121 | if err != nil { |
| 122 | return "", err |
| 123 | } |
| 124 | |
| 125 | cmd, err := subprocess.ExecCommand("git", "rev-parse", "--git-dir") |
| 126 | if err != nil { |
| 127 | return "", errors.Wrap(err, tr.Tr.Get("failed to find `git rev-parse --git-dir`")) |
| 128 | } |
| 129 | cmd.Cmd.Env = env |
| 130 | out, err := cmd.Output() |
| 131 | if err != nil { |
| 132 | if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 { |
| 133 | return "", errors.New(tr.Tr.Get("failed to call `git rev-parse --git-dir`: %s", string(err.Stderr))) |
| 134 | } |
| 135 | return "", errors.Wrap(err, tr.Tr.Get("failed to call `git rev-parse --git-dir`")) |
| 136 | } |
| 137 | |
| 138 | gitdir, err := tools.TranslateCygwinPath(strings.TrimRight(string(out), "\n")) |
| 139 | if err != nil { |
| 140 | return "", errors.Wrap(err, tr.Tr.Get("unable to translate path")) |
| 141 | } |
| 142 | |
| 143 | gitdir, err = filepath.Abs(gitdir) |
| 144 | if err != nil { |
| 145 | return "", errors.Wrap(err, tr.Tr.Get("unable to canonicalize path")) |
| 146 | } |
| 147 | |
| 148 | err = os.Chdir(curdir) |
| 149 | if err != nil { |
| 150 | return "", err |
| 151 | } |
| 152 | return tools.CanonicalizeSystemPath(gitdir) |
| 153 | } |
| 154 | |
| 155 | func fixUrlPath(path string) string { |
| 156 | if runtime.GOOS != "windows" { |
| 157 | return path |
| 158 | } |
| 159 | |
| 160 | // When parsing a file URL, Go produces a path starting with a slash. If |
| 161 | // it looks like there's a Windows drive letter at the beginning, strip |
| 162 | // off the beginning slash. If this is a Unix-style path from a |
| 163 | // Cygwin-like environment, we'll canonicalize it later. |
| 164 | re := regexp.MustCompile("/[A-Za-z]:/") |
| 165 | if re.MatchString(path) { |
| 166 | return path[1:] |
| 167 | } |
| 168 | return path |
| 169 | } |
| 170 | |
| 171 | // newHandler creates a new handler for the protocol. |
| 172 | func newHandler(cfg *config.Configuration, output *os.File, msg *inputMessage) (*fileHandler, error) { |
| 173 | url, err := fileUrlFromRemote(cfg, msg.Remote, msg.Operation) |
| 174 | if err != nil { |
| 175 | return nil, err |
| 176 | } |
| 177 | if url == nil { |
| 178 | return nil, errors.New(tr.Tr.Get("no valid file:// URLs found")) |
| 179 | } |
| 180 | |
| 181 | path, err := tools.TranslateCygwinPath(fixUrlPath(url.Path)) |
| 182 | if err != nil { |
| 183 | return nil, err |
| 184 | } |
| 185 | |
| 186 | gitdir, err := gitDirAtPath(path) |
| 187 | if err != nil { |
| 188 | return nil, err |
| 189 | } |
| 190 | |
| 191 | tempdir, err := os.MkdirTemp(cfg.TempDir(), "lfs-standalone-file-*") |
| 192 | if err != nil { |
| 193 | return nil, err |
| 194 | } |
| 195 | |
| 196 | tracerx.Printf("using %q as remote git directory", gitdir) |
| 197 | |
| 198 | return &fileHandler{ |
| 199 | remotePath: path, |
| 200 | remoteConfig: config.NewIn(gitdir, gitdir), |
| 201 | output: output, |
| 202 | config: cfg, |
| 203 | tempdir: tempdir, |
| 204 | }, nil |
| 205 | } |
| 206 | |
| 207 | // dispatch dispatches the event depending on the message type. |
| 208 | func (h *fileHandler) dispatch(msg *inputMessage) (bool, error) { |
| 209 | switch msg.Event { |
| 210 | case "init": |
| 211 | fmt.Fprintln(h.output, "{}") |
| 212 | case "upload": |
| 213 | h.respond(h.upload(msg.Oid, msg.Size, msg.Path)) |
| 214 | case "download": |
| 215 | h.respond(h.download(msg.Oid, msg.Size)) |
| 216 | case "terminate": |
| 217 | return false, nil |
| 218 | default: |
| 219 | return false, errors.New(tr.Tr.Get("unknown event %q", msg.Event)) |
| 220 | } |
| 221 | return true, nil |
| 222 | } |
| 223 | |
| 224 | // respond sends a response to an upload or download command, using the return |
| 225 | // values from those functions. |
| 226 | func (h *fileHandler) respond(oid string, path string, err error) { |
| 227 | response := &completeMessage{ |
| 228 | Event: "complete", |
| 229 | Oid: oid, |
| 230 | Path: path, |
| 231 | } |
| 232 | if err != nil { |
| 233 | response.Error = &errorMessage{Message: err.Error()} |
| 234 | } |
| 235 | json.NewEncoder(h.output).Encode(response) |
| 236 | } |
| 237 | |
| 238 | // upload performs the upload action for the given OID, size, and path. It |
| 239 | // returns arguments suitable for the respond method. |
| 240 | func (h *fileHandler) upload(oid string, size int64, path string) (string, string, error) { |
| 241 | if h.remoteConfig.LFSObjectExists(oid, size) { |
| 242 | // Already there, nothing to do. |
| 243 | return oid, "", nil |
| 244 | } |
| 245 | dest, err := h.remoteConfig.Filesystem().ObjectPath(oid) |
| 246 | if err != nil { |
| 247 | return oid, "", err |
| 248 | } |
| 249 | return oid, "", lfs.LinkOrCopy(h.remoteConfig, path, dest) |
| 250 | } |
| 251 | |
| 252 | // download performs the download action for the given OID and size. It returns |
| 253 | // arguments suitable for the respond method. |
| 254 | func (h *fileHandler) download(oid string, size int64) (string, string, error) { |
| 255 | if !h.remoteConfig.LFSObjectExists(oid, size) { |
| 256 | tracerx.Printf("missing object in %q (%s)", h.remotePath, oid) |
| 257 | return oid, "", errors.New(tr.Tr.Get("remote missing object %s", oid)) |
| 258 | } |
| 259 | |
| 260 | src, err := h.remoteConfig.Filesystem().ObjectPath(oid) |
| 261 | if err != nil { |
| 262 | return oid, "", err |
| 263 | } |
| 264 | |
| 265 | tmp, err := os.CreateTemp(h.tempdir, "download") |
| 266 | if err != nil { |
| 267 | return oid, "", err |
| 268 | } |
| 269 | tmp.Close() |
| 270 | os.Remove(tmp.Name()) |
| 271 | path := tmp.Name() |
| 272 | return oid, path, lfs.LinkOrCopy(h.config, src, path) |
| 273 | } |
| 274 | |
| 275 | // ProcessStandaloneData is the primary endpoint for processing data with a |
| 276 | // standalone transfer agent. It reads input from the specified input file and |
| 277 | // produces output to the specified output file. |
| 278 | func ProcessStandaloneData(cfg *config.Configuration, input *os.File, output *os.File) error { |
| 279 | var handler *fileHandler |
| 280 | |
| 281 | var eventErr error |
| 282 | scanner := bufio.NewScanner(input) |
| 283 | for scanner.Scan() { |
| 284 | var msg inputMessage |
| 285 | if err := json.NewDecoder(strings.NewReader(scanner.Text())).Decode(&msg); err != nil { |
| 286 | return errors.Wrap(err, tr.Tr.Get("error decoding JSON")) |
| 287 | } |
| 288 | if handler == nil { |
| 289 | var err error |
| 290 | handler, err = newHandler(cfg, output, &msg) |
| 291 | if err != nil { |
| 292 | err := errors.Wrap(err, tr.Tr.Get("error creating handler")) |
| 293 | errMsg := outputErrorMessage{ |
| 294 | Error: errorMessage{ |
| 295 | Message: err.Error(), |
| 296 | }, |
| 297 | } |
| 298 | json.NewEncoder(output).Encode(errMsg) |
| 299 | return err |
| 300 | } |
| 301 | } |
| 302 | if cont, err := handler.dispatch(&msg); !cont || err != nil { |
| 303 | eventErr = err |
| 304 | break |
| 305 | } |
| 306 | } |
| 307 | if handler != nil { |
| 308 | os.RemoveAll(handler.tempdir) |
| 309 | } |
| 310 | err := scanner.Err() |
| 311 | if err != nil { |
| 312 | err = errors.Wrap(err, tr.Tr.Get("error reading input")) |
| 313 | } |
| 314 | return errors.Join(eventErr, err) |
| 315 | } |