| 1 | package tq |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "net/http" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | |
| 11 | "github.com/git-lfs/git-lfs/v3/config" |
| 12 | "github.com/git-lfs/git-lfs/v3/errors" |
| 13 | "github.com/git-lfs/git-lfs/v3/lfsapi" |
| 14 | "github.com/git-lfs/git-lfs/v3/tools" |
| 15 | "github.com/git-lfs/git-lfs/v3/tr" |
| 16 | ) |
| 17 | |
| 18 | const ( |
| 19 | BasicAdapterName = "basic" |
| 20 | defaultContentType = "application/octet-stream" |
| 21 | ) |
| 22 | |
| 23 | // Adapter for basic uploads (non resumable) |
| 24 | type basicUploadAdapter struct { |
| 25 | *adapterBase |
| 26 | } |
| 27 | |
| 28 | func (a *basicUploadAdapter) tempDir() string { |
| 29 | // Dedicated to this adapter rather than shared with basic download. |
| 30 | d := filepath.Join(os.TempDir(), "git-lfs-basic-temp") |
| 31 | if err := tools.MkdirAll(d, a.fs); err != nil { |
| 32 | return os.TempDir() |
| 33 | } |
| 34 | return d |
| 35 | } |
| 36 | |
| 37 | func (a *basicUploadAdapter) WorkerStarting(workerNum int) (interface{}, error) { |
| 38 | return nil, nil |
| 39 | } |
| 40 | |
| 41 | func (a *basicUploadAdapter) WorkerEnding(workerNum int, ctx interface{}) { |
| 42 | } |
| 43 | |
| 44 | func (a *basicUploadAdapter) DoTransfer(ctx interface{}, t *Transfer, cb ProgressCallback, authOkFunc func()) error { |
| 45 | rel, err := t.Rel("upload") |
| 46 | if err != nil { |
| 47 | return err |
| 48 | } |
| 49 | if rel == nil { |
| 50 | return errors.New(tr.Tr.Get("No upload action for object: %s", t.Oid)) |
| 51 | } |
| 52 | |
| 53 | req, err := a.newHTTPRequest("PUT", rel) |
| 54 | if err != nil { |
| 55 | return err |
| 56 | } |
| 57 | |
| 58 | if req.Header.Get("Transfer-Encoding") == "chunked" { |
| 59 | req.TransferEncoding = []string{"chunked"} |
| 60 | } else { |
| 61 | req.Header.Set("Content-Length", strconv.FormatInt(t.Size, 10)) |
| 62 | } |
| 63 | |
| 64 | req.ContentLength = t.Size |
| 65 | |
| 66 | f, err := os.OpenFile(t.Path, os.O_RDONLY, 0644) |
| 67 | if err != nil { |
| 68 | return errors.Wrap(err, tr.Tr.Get("basic upload")) |
| 69 | } |
| 70 | defer f.Close() |
| 71 | |
| 72 | if err := a.setContentTypeFor(req, f); err != nil { |
| 73 | return err |
| 74 | } |
| 75 | |
| 76 | // Ensure progress callbacks made while uploading |
| 77 | // Wrap callback to give name context |
| 78 | ccb := func(totalSize int64, readSoFar int64, readSinceLast int) error { |
| 79 | if cb != nil { |
| 80 | return cb(t.Name, totalSize, readSoFar, readSinceLast) |
| 81 | } |
| 82 | return nil |
| 83 | } |
| 84 | |
| 85 | cbr := tools.NewFileBodyWithCallback(f, t.Size, ccb) |
| 86 | var reader lfsapi.ReadSeekCloser = cbr |
| 87 | |
| 88 | // Signal auth was ok on first read; this frees up other workers to start |
| 89 | if authOkFunc != nil { |
| 90 | reader = newStartCallbackReader(reader, func() error { |
| 91 | authOkFunc() |
| 92 | return nil |
| 93 | }) |
| 94 | } |
| 95 | |
| 96 | req.Body = reader |
| 97 | |
| 98 | req = a.apiClient.LogRequest(req, "lfs.data.upload") |
| 99 | res, err := a.makeRequest(t, req) |
| 100 | if err != nil { |
| 101 | if errors.IsUnprocessableEntityError(err) { |
| 102 | // If we got an HTTP 422, we do _not_ want to retry the |
| 103 | // request later below, because it is likely that the |
| 104 | // implementing server does not support non-standard |
| 105 | // Content-Type headers. |
| 106 | // |
| 107 | // Instead, return immediately and wait for the |
| 108 | // *tq.TransferQueue to report an error message. |
| 109 | return err |
| 110 | } |
| 111 | |
| 112 | // We're about to return a retriable error, meaning that this |
| 113 | // transfer will either be retried, or it will fail. |
| 114 | // |
| 115 | // Either way, let's decrement the number of bytes that we've |
| 116 | // read _so far_, so that the next iteration doesn't re-transfer |
| 117 | // those bytes, according to the progress meter. |
| 118 | if perr := cbr.ResetProgress(); perr != nil { |
| 119 | err = errors.Wrap(err, perr.Error()) |
| 120 | } |
| 121 | |
| 122 | if res == nil { |
| 123 | // We encountered a network or similar error which caused us |
| 124 | // to not receive a response at all. |
| 125 | return errors.NewRetriableError(err) |
| 126 | } |
| 127 | |
| 128 | if res.StatusCode == 429 { |
| 129 | retLaterErr := errors.NewRetriableLaterError(err, res.Header.Get("Retry-After")) |
| 130 | if retLaterErr != nil { |
| 131 | return retLaterErr |
| 132 | } |
| 133 | } |
| 134 | return errors.NewRetriableError(err) |
| 135 | } |
| 136 | |
| 137 | // A status code of 403 likely means that an authentication token for the |
| 138 | // upload has expired. This can be safely retried. |
| 139 | if res.StatusCode == 403 { |
| 140 | err = errors.New(tr.Tr.Get("Received status %d", res.StatusCode)) |
| 141 | return errors.NewRetriableError(err) |
| 142 | } |
| 143 | |
| 144 | if res.StatusCode > 299 { |
| 145 | return errors.New(tr.Tr.Get("Invalid status for %s %s: %d", |
| 146 | req.Method, |
| 147 | strings.SplitN(req.URL.String(), "?", 2)[0], |
| 148 | res.StatusCode, |
| 149 | )) |
| 150 | } |
| 151 | |
| 152 | io.Copy(io.Discard, res.Body) |
| 153 | res.Body.Close() |
| 154 | |
| 155 | return verifyUpload(a.apiClient, a.remote, t) |
| 156 | } |
| 157 | |
| 158 | func (a *adapterBase) setContentTypeFor(req *http.Request, r io.ReadSeeker) error { |
| 159 | uc := config.NewURLConfig(a.apiClient.GitEnv()) |
| 160 | disabled := !uc.Bool("lfs", req.URL.String(), "contenttype", true) |
| 161 | if len(req.Header.Get("Content-Type")) != 0 { |
| 162 | return nil |
| 163 | } |
| 164 | |
| 165 | var contentType string |
| 166 | |
| 167 | if !disabled { |
| 168 | buffer := make([]byte, 512) |
| 169 | n, err := r.Read(buffer) |
| 170 | if err != nil && err != io.EOF { |
| 171 | return errors.Wrap(err, tr.Tr.Get("content type detection error")) |
| 172 | } |
| 173 | |
| 174 | contentType = http.DetectContentType(buffer[:n]) |
| 175 | if _, err := r.Seek(0, io.SeekStart); err != nil { |
| 176 | return errors.Wrap(err, tr.Tr.Get("content type rewind failure")) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | if contentType == "" { |
| 181 | contentType = defaultContentType |
| 182 | } |
| 183 | |
| 184 | req.Header.Set("Content-Type", contentType) |
| 185 | return nil |
| 186 | } |
| 187 | |
| 188 | // startCallbackReader is a reader wrapper which calls a function as soon as the |
| 189 | // first Read() call is made. This callback is only made once |
| 190 | type startCallbackReader struct { |
| 191 | cb func() error |
| 192 | cbDone bool |
| 193 | lfsapi.ReadSeekCloser |
| 194 | } |
| 195 | |
| 196 | func (s *startCallbackReader) Read(p []byte) (n int, err error) { |
| 197 | if !s.cbDone && s.cb != nil { |
| 198 | if err := s.cb(); err != nil { |
| 199 | return 0, err |
| 200 | } |
| 201 | s.cbDone = true |
| 202 | } |
| 203 | return s.ReadSeekCloser.Read(p) |
| 204 | } |
| 205 | |
| 206 | func newStartCallbackReader(r lfsapi.ReadSeekCloser, cb func() error) *startCallbackReader { |
| 207 | return &startCallbackReader{ |
| 208 | ReadSeekCloser: r, |
| 209 | cb: cb, |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | func configureBasicUploadAdapter(m *concreteManifest) { |
| 214 | m.RegisterNewAdapterFunc(BasicAdapterName, Upload, false, func(name string, dir Direction) Adapter { |
| 215 | switch dir { |
| 216 | case Upload: |
| 217 | bu := &basicUploadAdapter{newAdapterBase(m.fs, name, dir, nil)} |
| 218 | // self implements impl |
| 219 | bu.transferImpl = bu |
| 220 | return bu |
| 221 | case Download: |
| 222 | panic(tr.Tr.Get("Should never ask this function to download")) |
| 223 | } |
| 224 | return nil |
| 225 | }) |
| 226 | } |
| 227 | |
| 228 | func (a *basicUploadAdapter) makeRequest(t *Transfer, req *http.Request) (*http.Response, error) { |
| 229 | res, err := a.doHTTP(t, req) |
| 230 | if errors.IsAuthError(err) && len(req.Header.Get("Authorization")) == 0 { |
| 231 | // Construct a new body with just the raw file and no callbacks. Since |
| 232 | // all progress tracking happens when the net.http code copies our |
| 233 | // request body into a new request, we can safely make this request |
| 234 | // outside of the flow of the transfer adapter, and if it fails, the |
| 235 | // transfer progress will be rewound at the top level |
| 236 | f, _ := os.OpenFile(t.Path, os.O_RDONLY, 0644) |
| 237 | defer f.Close() |
| 238 | |
| 239 | req.Body = tools.NewBodyWithCallback(f, t.Size, nil) |
| 240 | return a.makeRequest(t, req) |
| 241 | } |
| 242 | |
| 243 | return res, err |
| 244 | } |