| 1 | package tq |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "hash" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "regexp" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | |
| 14 | "github.com/git-lfs/git-lfs/v3/config" |
| 15 | "github.com/git-lfs/git-lfs/v3/errors" |
| 16 | "github.com/git-lfs/git-lfs/v3/tools" |
| 17 | "github.com/git-lfs/git-lfs/v3/tr" |
| 18 | "github.com/klauspost/compress/zstd" |
| 19 | "github.com/rubyist/tracerx" |
| 20 | ) |
| 21 | |
| 22 | // Adapter for basic HTTP downloads, includes resuming via HTTP Range |
| 23 | type basicDownloadAdapter struct { |
| 24 | *adapterBase |
| 25 | } |
| 26 | |
| 27 | type basicDownloadAdapterWorkerContext struct { |
| 28 | zstdDecoder *zstd.Decoder |
| 29 | } |
| 30 | |
| 31 | func (a *basicDownloadAdapter) tempDir() string { |
| 32 | // Shared with the SSH adapter. |
| 33 | d := filepath.Join(a.fs.LFSStorageDir, "incomplete") |
| 34 | if err := tools.MkdirAll(d, a.fs); err != nil { |
| 35 | return os.TempDir() |
| 36 | } |
| 37 | return d |
| 38 | } |
| 39 | |
| 40 | func (a *basicDownloadAdapter) WorkerStarting(workerNum int) (interface{}, error) { |
| 41 | return &basicDownloadAdapterWorkerContext{}, nil |
| 42 | } |
| 43 | |
| 44 | func (a *basicDownloadAdapter) WorkerEnding(workerNum int, ctx interface{}) { |
| 45 | context, ok := ctx.(*basicDownloadAdapterWorkerContext) |
| 46 | if !ok { |
| 47 | tracerx.Printf("context object for basic download transfer adapter was of the wrong type") |
| 48 | return |
| 49 | } |
| 50 | |
| 51 | if context.zstdDecoder != nil { |
| 52 | context.zstdDecoder.Close() |
| 53 | tracerx.Printf("http: closed zstd decoder") |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func (a *basicDownloadAdapter) DoTransfer(ctx interface{}, t *Transfer, cb ProgressCallback, authOkFunc func()) error { |
| 58 | context, ok := ctx.(*basicDownloadAdapterWorkerContext) |
| 59 | if !ok { |
| 60 | return errors.New(tr.Tr.Get("context object for basic download transfer adapter was of the wrong type")) |
| 61 | } |
| 62 | |
| 63 | // Reserve a temporary filename. We need to make sure nobody operates on the file simultaneously with us. |
| 64 | f, err := tools.TempFile(a.tempDir(), t.Oid, a.fs) |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | tmpName := f.Name() |
| 69 | defer func() { |
| 70 | // Fail-safe: Most implementation of os.File.Close() does nil check |
| 71 | if f != nil { |
| 72 | f.Close() |
| 73 | } |
| 74 | // This will delete temp file if: |
| 75 | // - we failed to fully download file and move it to final location including the case when final location already |
| 76 | // exists because other parallel git-lfs processes downloaded file |
| 77 | // - we also failed to move it to a partially-downloaded location |
| 78 | os.Remove(tmpName) |
| 79 | }() |
| 80 | |
| 81 | // Close file because we will attempt to move partially-downloaded one on top of it |
| 82 | if err := f.Close(); err != nil { |
| 83 | return err |
| 84 | } |
| 85 | |
| 86 | // Attempt to resume download. No error checking here. If we fail, we'll simply download from the start |
| 87 | tools.RobustRename(a.downloadFilename(t), f.Name()) |
| 88 | |
| 89 | // Open temp file. It is either empty or partially downloaded |
| 90 | f, err = os.OpenFile(f.Name(), os.O_RDWR, 0644) |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | |
| 95 | // Read any existing data into hash |
| 96 | hash := tools.NewLfsContentHash() |
| 97 | fromByte, err := io.Copy(hash, f) |
| 98 | if err != nil { |
| 99 | return err |
| 100 | } |
| 101 | |
| 102 | // Ensure that partial file seems valid |
| 103 | if fromByte > 0 { |
| 104 | if fromByte < t.Size-1 { |
| 105 | tracerx.Printf("xfer: Attempting to resume download of %q from byte %d", t.Oid, fromByte) |
| 106 | } else { |
| 107 | // Somehow we have more data than expected. Let's retry from the beginning. |
| 108 | if _, err := f.Seek(0, io.SeekStart); err != nil { |
| 109 | return err |
| 110 | } |
| 111 | if err := f.Truncate(0); err != nil { |
| 112 | return err |
| 113 | } |
| 114 | fromByte = 0 |
| 115 | hash = nil |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | err = a.download(context, t, cb, authOkFunc, f, fromByte, hash) |
| 120 | |
| 121 | if err != nil { |
| 122 | f.Close() |
| 123 | // Rename file so next download can resume from where we stopped. |
| 124 | // No error checking here, if rename fails then file will be deleted and there just will be no download resuming |
| 125 | tools.RobustRename(f.Name(), a.downloadFilename(t)) |
| 126 | } |
| 127 | |
| 128 | return err |
| 129 | } |
| 130 | |
| 131 | // Returns path where partially downloaded file should be stored for download resuming |
| 132 | func (a *basicDownloadAdapter) downloadFilename(t *Transfer) string { |
| 133 | return filepath.Join(a.tempDir(), t.Oid+".part") |
| 134 | } |
| 135 | |
| 136 | // download starts or resumes and download. dlFile is expected to be an existing file open in RW mode |
| 137 | func (a *basicDownloadAdapter) download(context *basicDownloadAdapterWorkerContext, t *Transfer, cb ProgressCallback, authOkFunc func(), dlFile *os.File, fromByte int64, hash hash.Hash) error { |
| 138 | rel, err := t.Rel("download") |
| 139 | if err != nil { |
| 140 | return err |
| 141 | } |
| 142 | if rel == nil { |
| 143 | return errors.New(tr.Tr.Get("Object %s not found on the server.", t.Oid)) |
| 144 | } |
| 145 | |
| 146 | req, err := a.newHTTPRequest("GET", rel) |
| 147 | if err != nil { |
| 148 | return err |
| 149 | } |
| 150 | |
| 151 | if fromByte > 0 { |
| 152 | // We could just use a start byte, but since we know the length be specific |
| 153 | req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", fromByte, t.Size-1)) |
| 154 | } else { |
| 155 | // Set Accept-Encoding header if configured to zstd |
| 156 | // (Go's http client handles gzip automatically when no Accept-Encoding is set) |
| 157 | uc := config.NewURLConfig(a.apiClient.GitEnv()) |
| 158 | httpDownloadEncoding, _ := uc.Get("lfs.transfer", rel.Href, "httpdownloadencoding") |
| 159 | if httpDownloadEncoding != "" { |
| 160 | switch httpDownloadEncoding { |
| 161 | case "gzip": |
| 162 | // Don't set header, let Go's http client handle gzip automatically |
| 163 | case "zstd": |
| 164 | req.Header.Set("Accept-Encoding", "zstd") |
| 165 | default: |
| 166 | return errors.New(tr.Tr.Get("unsupported lfs.transfer.httpDownloadEncoding value %q: must be \"gzip\" or \"zstd\"", httpDownloadEncoding)) |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | req = a.apiClient.LogRequest(req, "lfs.data.download") |
| 172 | res, err := a.makeRequest(t, req) |
| 173 | if err != nil { |
| 174 | if res == nil { |
| 175 | // We encountered a network or similar error which caused us |
| 176 | // to not receive a response at all. |
| 177 | return errors.NewRetriableError(err) |
| 178 | } |
| 179 | |
| 180 | // Special-case status code 416 () - fall back |
| 181 | if fromByte > 0 && dlFile != nil && res.StatusCode == 416 { |
| 182 | tracerx.Printf("xfer: server rejected resume download request for %q from byte %d; re-downloading from start", t.Oid, fromByte) |
| 183 | if _, err := dlFile.Seek(0, io.SeekStart); err != nil { |
| 184 | return err |
| 185 | } |
| 186 | if err := dlFile.Truncate(0); err != nil { |
| 187 | return err |
| 188 | } |
| 189 | return a.download(context, t, cb, authOkFunc, dlFile, 0, nil) |
| 190 | } |
| 191 | |
| 192 | // Special-cae status code 429 - retry after certain time |
| 193 | if res.StatusCode == 429 { |
| 194 | retLaterErr := errors.NewRetriableLaterError(err, res.Header.Get("Retry-After")) |
| 195 | if retLaterErr != nil { |
| 196 | return retLaterErr |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | return errors.NewRetriableError(err) |
| 201 | } |
| 202 | |
| 203 | defer res.Body.Close() |
| 204 | |
| 205 | // Range request must return 206 & content range to confirm |
| 206 | if fromByte > 0 { |
| 207 | rangeRequestOk := false |
| 208 | var failReason string |
| 209 | // check 206 and Content-Range, fall back if either not as expected |
| 210 | if res.StatusCode == 206 { |
| 211 | // Probably a successful range request, check Content-Range |
| 212 | if rangeHdr := res.Header.Get("Content-Range"); rangeHdr != "" { |
| 213 | regex := regexp.MustCompile(`bytes (\d+)\-.*`) |
| 214 | match := regex.FindStringSubmatch(rangeHdr) |
| 215 | if match != nil && len(match) > 1 { |
| 216 | contentStart, _ := strconv.ParseInt(match[1], 10, 64) |
| 217 | if contentStart == fromByte { |
| 218 | rangeRequestOk = true |
| 219 | } else { |
| 220 | failReason = fmt.Sprintf("Content-Range start byte incorrect: %s expected %d", match[1], fromByte) |
| 221 | } |
| 222 | } else { |
| 223 | failReason = fmt.Sprintf("badly formatted Content-Range header: %q", rangeHdr) |
| 224 | } |
| 225 | } else { |
| 226 | failReason = "missing Content-Range header in response" |
| 227 | } |
| 228 | } else { |
| 229 | failReason = fmt.Sprintf("expected status code 206, received %d", res.StatusCode) |
| 230 | } |
| 231 | if rangeRequestOk { |
| 232 | tracerx.Printf("xfer: server accepted resume download request: %q from byte %d", t.Oid, fromByte) |
| 233 | advanceCallbackProgress(cb, t, fromByte) |
| 234 | } else { |
| 235 | // Abort resume, perform regular download |
| 236 | tracerx.Printf("xfer: failed to resume download for %q from byte %d: %s. Re-downloading from start", t.Oid, fromByte, failReason) |
| 237 | |
| 238 | if _, err := dlFile.Seek(0, io.SeekStart); err != nil { |
| 239 | return err |
| 240 | } |
| 241 | if err := dlFile.Truncate(0); err != nil { |
| 242 | return err |
| 243 | } |
| 244 | fromByte = 0 |
| 245 | hash = nil |
| 246 | |
| 247 | if res.StatusCode == 200 { |
| 248 | // If status code was 200 then server just ignored Range header and |
| 249 | // sent everything. Don't re-request, use this one from byte 0 |
| 250 | } else { |
| 251 | // re-request needed |
| 252 | return a.download(context, t, cb, authOkFunc, dlFile, fromByte, hash) |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // Signal auth OK on success response, before starting download to free up |
| 258 | // other workers immediately |
| 259 | if authOkFunc != nil { |
| 260 | authOkFunc() |
| 261 | } |
| 262 | |
| 263 | // Handle Content-Encoding decompression for zstd |
| 264 | // (gzip is handled automatically by Go's http client when we don't set Accept-Encoding) |
| 265 | var bodyReader io.Reader = res.Body |
| 266 | if strings.ToLower(res.Header.Get("Content-Encoding")) == "zstd" { |
| 267 | zstdDecoder := context.zstdDecoder |
| 268 | if zstdDecoder == nil { |
| 269 | zstdDecoder, err := zstd.NewReader(res.Body, zstd.WithDecoderConcurrency(1)) |
| 270 | if err != nil { |
| 271 | return errors.Wrap(err, tr.Tr.Get("failed to create zstd decompressor")) |
| 272 | } |
| 273 | context.zstdDecoder = zstdDecoder |
| 274 | tracerx.Printf("http: initialized zstd decoder") |
| 275 | } else { |
| 276 | zstdDecoder.Reset(res.Body) |
| 277 | } |
| 278 | bodyReader = context.zstdDecoder |
| 279 | |
| 280 | tracerx.Printf("http: decompressing zstd-encoded response") |
| 281 | |
| 282 | // Set ContentLength to -1 to match Go's default behaviour |
| 283 | // when decompressing gzipped responses; see: |
| 284 | // |
| 285 | // https://github.com/golang/go/blob/go1.25.7/src/net/http/response.go#L90-L92 |
| 286 | // https://github.com/golang/go/blob/go1.25.7/src/net/http/transport.go#L2385 |
| 287 | res.ContentLength = -1 |
| 288 | } |
| 289 | |
| 290 | var hasher *tools.HashingReader |
| 291 | httpReader := tools.NewRetriableReader(bodyReader) |
| 292 | |
| 293 | if fromByte > 0 && hash != nil { |
| 294 | // pre-load hashing reader with previous content |
| 295 | hasher = tools.NewHashingReaderPreloadHash(httpReader, hash) |
| 296 | } else { |
| 297 | hasher = tools.NewHashingReader(httpReader) |
| 298 | } |
| 299 | |
| 300 | dlfilename := dlFile.Name() |
| 301 | // Wrap callback to give name context |
| 302 | ccb := func(totalSize int64, readSoFar int64, readSinceLast int) error { |
| 303 | if cb != nil { |
| 304 | return cb(t.Name, totalSize, readSoFar+fromByte, readSinceLast) |
| 305 | } |
| 306 | return nil |
| 307 | } |
| 308 | written, err := tools.CopyWithCallback(dlFile, hasher, res.ContentLength, ccb) |
| 309 | if err != nil { |
| 310 | return errors.Wrap(err, tr.Tr.Get("cannot write data to temporary file %q", dlfilename)) |
| 311 | } |
| 312 | |
| 313 | if actual := hasher.Hash(); actual != t.Oid { |
| 314 | return errors.New(tr.Tr.Get("expected OID %s, got %s after %d bytes written", t.Oid, actual, written)) |
| 315 | } |
| 316 | |
| 317 | if err := dlFile.Close(); err != nil { |
| 318 | return errors.New(tr.Tr.Get("can't close temporary file %q: %v", dlfilename, err)) |
| 319 | } |
| 320 | |
| 321 | err = tools.RenameFileCopyPermissions(dlfilename, t.Path) |
| 322 | if _, err2 := os.Stat(t.Path); err2 == nil { |
| 323 | // Target file already exists, possibly was downloaded by other git-lfs process |
| 324 | return nil |
| 325 | } |
| 326 | return err |
| 327 | } |
| 328 | |
| 329 | func configureBasicDownloadAdapter(m *concreteManifest) { |
| 330 | m.RegisterNewAdapterFunc(BasicAdapterName, Download, false, func(name string, dir Direction) Adapter { |
| 331 | switch dir { |
| 332 | case Download: |
| 333 | bd := &basicDownloadAdapter{newAdapterBase(m.fs, name, dir, nil)} |
| 334 | // self implements impl |
| 335 | bd.transferImpl = bd |
| 336 | return bd |
| 337 | case Upload: |
| 338 | panic(tr.Tr.Get("Should never ask this function to upload")) |
| 339 | } |
| 340 | return nil |
| 341 | }) |
| 342 | } |
| 343 | |
| 344 | func (a *basicDownloadAdapter) makeRequest(t *Transfer, req *http.Request) (*http.Response, error) { |
| 345 | res, err := a.doHTTP(t, req) |
| 346 | if errors.IsAuthError(err) && len(req.Header.Get("Authorization")) == 0 { |
| 347 | return a.makeRequest(t, req) |
| 348 | } |
| 349 | |
| 350 | return res, err |
| 351 | } |