| 1 | package tq |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "sort" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/git-lfs/git-lfs/v3/errors" |
| 15 | "github.com/git-lfs/git-lfs/v3/lfshttp" |
| 16 | "github.com/git-lfs/git-lfs/v3/ssh" |
| 17 | "github.com/git-lfs/git-lfs/v3/tools" |
| 18 | "github.com/git-lfs/git-lfs/v3/tr" |
| 19 | "github.com/rubyist/tracerx" |
| 20 | ) |
| 21 | |
| 22 | const ( |
| 23 | SSHAdapterName = "ssh" |
| 24 | ) |
| 25 | |
| 26 | type SSHBatchClient struct { |
| 27 | maxRetries int |
| 28 | transfer *ssh.SSHTransfer |
| 29 | } |
| 30 | |
| 31 | func (a *SSHBatchClient) batchInternal(args []string, batchLines []string) (int, []string, []string, error) { |
| 32 | conn, err := a.transfer.Connection(0) |
| 33 | if err != nil { |
| 34 | return 0, nil, nil, errors.Wrap(err, tr.Tr.Get("could not get connection for batch request")) |
| 35 | } |
| 36 | conn.Lock() |
| 37 | defer conn.Unlock() |
| 38 | err = conn.SendMessageWithLines("batch", args, batchLines) |
| 39 | if err != nil { |
| 40 | return 0, nil, nil, errors.Wrap(err, tr.Tr.Get("batch request")) |
| 41 | } |
| 42 | |
| 43 | status, args, lines, err := conn.ReadStatusWithLines() |
| 44 | if err != nil { |
| 45 | return status, nil, nil, errors.Wrap(err, tr.Tr.Get("batch response")) |
| 46 | } |
| 47 | return status, args, lines, err |
| 48 | } |
| 49 | |
| 50 | func (a *SSHBatchClient) Batch(remote string, bReq *batchRequest) (*BatchResponse, error) { |
| 51 | bRes := &BatchResponse{TransferAdapterName: SSHAdapterName} |
| 52 | if len(bReq.Objects) == 0 { |
| 53 | return bRes, nil |
| 54 | } |
| 55 | |
| 56 | batchLines := make([]string, 0, len(bReq.Objects)) |
| 57 | for _, obj := range bReq.Objects { |
| 58 | batchLines = append(batchLines, fmt.Sprintf("%s %d", obj.Oid, obj.Size)) |
| 59 | } |
| 60 | |
| 61 | tracerx.Printf("api: batch %d files", len(bReq.Objects)) |
| 62 | |
| 63 | requestedAt := time.Now() |
| 64 | args := []string{"transfer=ssh", "hash-algo=sha256"} |
| 65 | if bReq.Ref != nil { |
| 66 | args = append(args, fmt.Sprintf("refname=%s", bReq.Ref.Name)) |
| 67 | } |
| 68 | status, args, lines, err := a.batchInternal(args, batchLines) |
| 69 | if err != nil { |
| 70 | return nil, err |
| 71 | } |
| 72 | |
| 73 | if status != 200 { |
| 74 | msg := tr.Tr.Get("no message provided") |
| 75 | if len(lines) > 0 { |
| 76 | msg = lines[0] |
| 77 | } |
| 78 | return nil, errors.New(tr.Tr.Get("batch response: status %d from server (%s)", status, msg)) |
| 79 | } |
| 80 | |
| 81 | for _, arg := range args { |
| 82 | entries := strings.SplitN(arg, "=", 2) |
| 83 | if len(entries) < 2 { |
| 84 | continue |
| 85 | } |
| 86 | if entries[0] == "hash-algo" { |
| 87 | bRes.HashAlgorithm = entries[1] |
| 88 | if bRes.HashAlgorithm != "sha256" { |
| 89 | return nil, errors.New(tr.Tr.Get("batch response: unsupported hash algorithm: %q", entries[1])) |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | sort.Strings(lines) |
| 95 | for _, line := range lines { |
| 96 | entries := strings.Split(line, " ") |
| 97 | if len(entries) < 3 { |
| 98 | return nil, errors.New(tr.Tr.Get("batch response: malformed response: %q", line)) |
| 99 | } |
| 100 | length := len(bRes.Objects) |
| 101 | if length == 0 || bRes.Objects[length-1].Oid != entries[0] { |
| 102 | bRes.Objects = append(bRes.Objects, &Transfer{Actions: make(map[string]*Action)}) |
| 103 | } |
| 104 | transfer := bRes.Objects[len(bRes.Objects)-1] |
| 105 | transfer.Oid = entries[0] |
| 106 | transfer.Size, err = strconv.ParseInt(entries[1], 10, 64) |
| 107 | if err != nil { |
| 108 | return nil, errors.New(tr.Tr.Get("batch response: invalid size: %s", entries[1])) |
| 109 | } |
| 110 | if entries[2] == "noop" { |
| 111 | continue |
| 112 | } |
| 113 | transfer.Actions[entries[2]] = &Action{} |
| 114 | if len(entries) > 3 { |
| 115 | for _, entry := range entries[3:] { |
| 116 | if strings.HasPrefix(entry, "id=") { |
| 117 | transfer.Actions[entries[2]].Id = entry[3:] |
| 118 | } else if strings.HasPrefix(entry, "token=") { |
| 119 | transfer.Actions[entries[2]].Token = entry[6:] |
| 120 | } else if strings.HasPrefix(entry, "expires-in=") { |
| 121 | transfer.Actions[entries[2]].ExpiresIn, err = strconv.Atoi(entry[11:]) |
| 122 | if err != nil { |
| 123 | return nil, errors.New(tr.Tr.Get("batch response: invalid expires-in: %s", entry)) |
| 124 | } |
| 125 | } else if strings.HasPrefix(entry, "expires-at=") { |
| 126 | transfer.Actions[entries[2]].ExpiresAt, err = time.Parse(time.RFC3339, entry[11:]) |
| 127 | if err != nil { |
| 128 | return nil, errors.New(tr.Tr.Get("batch response: invalid expires-at: %s", entry)) |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | for _, obj := range bRes.Objects { |
| 136 | for _, a := range obj.Actions { |
| 137 | a.createdAt = requestedAt |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | return bRes, nil |
| 142 | } |
| 143 | |
| 144 | func (a *SSHBatchClient) MaxRetries() int { |
| 145 | return a.maxRetries |
| 146 | } |
| 147 | |
| 148 | func (a *SSHBatchClient) SetMaxRetries(n int) { |
| 149 | a.maxRetries = n |
| 150 | } |
| 151 | |
| 152 | type SSHAdapter struct { |
| 153 | *adapterBase |
| 154 | ctx lfshttp.Context |
| 155 | transfer *ssh.SSHTransfer |
| 156 | } |
| 157 | |
| 158 | // WorkerStarting is called when a worker goroutine starts to process jobs |
| 159 | // Implementations can run some startup logic here & return some context if needed |
| 160 | func (a *SSHAdapter) WorkerStarting(workerNum int) (interface{}, error) { |
| 161 | if a.transfer == nil { |
| 162 | return nil, errors.New(tr.Tr.Get("missing SSH transfer connection for SSH transfer adapter")) |
| 163 | } |
| 164 | a.transfer.SetConnectionCountAtLeast(workerNum + 1) |
| 165 | return workerNum, nil |
| 166 | } |
| 167 | |
| 168 | // WorkerEnding is called when a worker goroutine is shutting down |
| 169 | // Implementations can clean up per-worker resources here, context is as returned from WorkerStarting |
| 170 | func (a *SSHAdapter) WorkerEnding(workerNum int, ctx interface{}) { |
| 171 | } |
| 172 | |
| 173 | func (a *SSHAdapter) tempDir() string { |
| 174 | // Shared with the basic download adapter. |
| 175 | d := filepath.Join(a.fs.LFSStorageDir, "incomplete") |
| 176 | if err := tools.MkdirAll(d, a.fs); err != nil { |
| 177 | return os.TempDir() |
| 178 | } |
| 179 | return d |
| 180 | } |
| 181 | |
| 182 | // DoTransfer performs a single transfer within a worker. ctx is any context returned from WorkerStarting |
| 183 | func (a *SSHAdapter) DoTransfer(ctx interface{}, t *Transfer, cb ProgressCallback, authOkFunc func()) error { |
| 184 | if authOkFunc != nil { |
| 185 | authOkFunc() |
| 186 | } |
| 187 | workerNum := ctx.(int) |
| 188 | if a.adapterBase.direction == Upload { |
| 189 | return a.upload(t, workerNum, cb) |
| 190 | } else { |
| 191 | return a.download(t, workerNum, cb) |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | func (a *SSHAdapter) download(t *Transfer, workerNum int, cb ProgressCallback) error { |
| 196 | rel, err := t.Rel("download") |
| 197 | if err != nil { |
| 198 | return err |
| 199 | } |
| 200 | if rel == nil { |
| 201 | return errors.New(tr.Tr.Get("No download action for object: %s", t.Oid)) |
| 202 | } |
| 203 | // Reserve a temporary filename. We need to make sure nobody operates on the file simultaneously with us. |
| 204 | f, err := tools.TempFile(a.tempDir(), t.Oid, a.fs) |
| 205 | if err != nil { |
| 206 | return err |
| 207 | } |
| 208 | tmpName := f.Name() |
| 209 | defer func() { |
| 210 | if f != nil { |
| 211 | f.Close() |
| 212 | } |
| 213 | os.Remove(tmpName) |
| 214 | }() |
| 215 | |
| 216 | return a.doDownload(t, workerNum, f, cb) |
| 217 | } |
| 218 | |
| 219 | // doDownload starts a download. f is expected to be an existing file open in RW mode |
| 220 | func (a *SSHAdapter) doDownload(t *Transfer, workerNum int, f *os.File, cb ProgressCallback) error { |
| 221 | args := a.argumentsForTransfer(t, "download") |
| 222 | conn, err := a.transfer.Connection(workerNum) |
| 223 | if err != nil { |
| 224 | return err |
| 225 | } |
| 226 | conn.Lock() |
| 227 | defer conn.Unlock() |
| 228 | err = conn.SendMessage(fmt.Sprintf("get-object %s", t.Oid), args) |
| 229 | if err != nil { |
| 230 | return err |
| 231 | } |
| 232 | status, args, data, err := conn.ReadStatusWithData() |
| 233 | if err != nil { |
| 234 | return err |
| 235 | } |
| 236 | if status < 200 || status > 299 { |
| 237 | buffer := &bytes.Buffer{} |
| 238 | if data != nil { |
| 239 | io.CopyN(buffer, data, 1024) |
| 240 | io.Copy(io.Discard, data) |
| 241 | } |
| 242 | return errors.NewRetriableError(errors.New(tr.Tr.Get("got status %d when fetching OID %s: %s", status, t.Oid, buffer.String()))) |
| 243 | } |
| 244 | |
| 245 | var actualSize int64 |
| 246 | seenSize := false |
| 247 | for _, arg := range args { |
| 248 | if strings.HasPrefix(arg, "size=") { |
| 249 | if seenSize { |
| 250 | return errors.NewProtocolError(tr.Tr.Get("unexpected size argument"), nil) |
| 251 | } |
| 252 | actualSize, err = strconv.ParseInt(arg[5:], 10, 64) |
| 253 | if err != nil || actualSize < 0 { |
| 254 | return errors.NewProtocolError(tr.Tr.Get("expected valid size, got %q", arg[5:]), err) |
| 255 | } |
| 256 | seenSize = true |
| 257 | } |
| 258 | } |
| 259 | if !seenSize { |
| 260 | return errors.NewProtocolError(tr.Tr.Get("no size argument seen"), nil) |
| 261 | } |
| 262 | |
| 263 | dlfilename := f.Name() |
| 264 | // Wrap callback to give name context |
| 265 | ccb := func(totalSize int64, readSoFar int64, readSinceLast int) error { |
| 266 | if cb != nil { |
| 267 | return cb(t.Name, totalSize, readSoFar, readSinceLast) |
| 268 | } |
| 269 | return nil |
| 270 | } |
| 271 | hasher := tools.NewHashingReader(data) |
| 272 | written, err := tools.CopyWithCallback(f, hasher, t.Size, ccb) |
| 273 | if err != nil { |
| 274 | return errors.Wrap(err, tr.Tr.Get("cannot write data to temporary file %q", dlfilename)) |
| 275 | } |
| 276 | |
| 277 | if actual := hasher.Hash(); actual != t.Oid { |
| 278 | return errors.New(tr.Tr.Get("expected OID %s, got %s after %d bytes written", t.Oid, actual, written)) |
| 279 | } |
| 280 | |
| 281 | if err := f.Close(); err != nil { |
| 282 | return errors.New(tr.Tr.Get("can't close temporary file %q: %v", dlfilename, err)) |
| 283 | } |
| 284 | |
| 285 | err = tools.RenameFileCopyPermissions(dlfilename, t.Path) |
| 286 | if _, err2 := os.Stat(t.Path); err2 == nil { |
| 287 | // Target file already exists, possibly was downloaded by other git-lfs process |
| 288 | return nil |
| 289 | } |
| 290 | return err |
| 291 | } |
| 292 | |
| 293 | func (a *SSHAdapter) verifyUpload(t *Transfer, workerNum int) error { |
| 294 | args := a.argumentsForTransfer(t, "upload") |
| 295 | conn, err := a.transfer.Connection(workerNum) |
| 296 | if err != nil { |
| 297 | return err |
| 298 | } |
| 299 | conn.Lock() |
| 300 | defer conn.Unlock() |
| 301 | err = conn.SendMessage(fmt.Sprintf("verify-object %s", t.Oid), args) |
| 302 | if err != nil { |
| 303 | return err |
| 304 | } |
| 305 | status, _, lines, err := conn.ReadStatusWithLines() |
| 306 | if err != nil { |
| 307 | return err |
| 308 | } |
| 309 | if status < 200 || status > 299 { |
| 310 | if len(lines) > 0 { |
| 311 | return errors.New(tr.Tr.Get("got status %d when verifying upload OID %s: %s", status, t.Oid, lines[0])) |
| 312 | } |
| 313 | return errors.New(tr.Tr.Get("got status %d when verifying upload OID %s", status, t.Oid)) |
| 314 | } |
| 315 | return nil |
| 316 | } |
| 317 | |
| 318 | func (a *SSHAdapter) doUpload(t *Transfer, workerNum int, f *os.File, cb ProgressCallback) (int, []string, []string, error) { |
| 319 | args := a.argumentsForTransfer(t, "upload") |
| 320 | |
| 321 | // Ensure progress callbacks made while uploading |
| 322 | // Wrap callback to give name context |
| 323 | ccb := func(totalSize int64, readSoFar int64, readSinceLast int) error { |
| 324 | if cb != nil { |
| 325 | return cb(t.Name, totalSize, readSoFar, readSinceLast) |
| 326 | } |
| 327 | return nil |
| 328 | } |
| 329 | |
| 330 | cbr := tools.NewFileBodyWithCallback(f, t.Size, ccb) |
| 331 | |
| 332 | conn, err := a.transfer.Connection(workerNum) |
| 333 | if err != nil { |
| 334 | return 0, nil, nil, err |
| 335 | } |
| 336 | conn.Lock() |
| 337 | defer conn.Unlock() |
| 338 | defer cbr.Close() |
| 339 | err = conn.SendMessageWithData(fmt.Sprintf("put-object %s", t.Oid), args, cbr) |
| 340 | if err != nil { |
| 341 | return 0, nil, nil, err |
| 342 | } |
| 343 | return conn.ReadStatusWithLines() |
| 344 | } |
| 345 | |
| 346 | // upload starts an upload. |
| 347 | func (a *SSHAdapter) upload(t *Transfer, workerNum int, cb ProgressCallback) error { |
| 348 | rel, err := t.Rel("upload") |
| 349 | if err != nil { |
| 350 | return err |
| 351 | } |
| 352 | if rel == nil { |
| 353 | return errors.New(tr.Tr.Get("No upload action for object: %s", t.Oid)) |
| 354 | } |
| 355 | |
| 356 | f, err := os.OpenFile(t.Path, os.O_RDONLY, 0644) |
| 357 | if err != nil { |
| 358 | return errors.Wrap(err, tr.Tr.Get("SSH upload")) |
| 359 | } |
| 360 | defer f.Close() |
| 361 | |
| 362 | status, _, lines, err := a.doUpload(t, workerNum, f, cb) |
| 363 | if err != nil { |
| 364 | return err |
| 365 | } |
| 366 | if status < 200 || status > 299 { |
| 367 | // A status code of 403 likely means that an authentication token for the |
| 368 | // upload has expired. This can be safely retried. |
| 369 | if status == 403 { |
| 370 | err = errors.New(tr.Tr.Get("Received status %d", status)) |
| 371 | return errors.NewRetriableError(err) |
| 372 | } |
| 373 | |
| 374 | if status == 429 { |
| 375 | return errors.NewRetriableError(errors.New(tr.Tr.Get("got status %d when uploading OID %s", status, t.Oid))) |
| 376 | } |
| 377 | |
| 378 | if len(lines) > 0 { |
| 379 | return errors.New(tr.Tr.Get("got status %d when uploading OID %s: %s", status, t.Oid, lines[0])) |
| 380 | } |
| 381 | return errors.New(tr.Tr.Get("got status %d when uploading OID %s", status, t.Oid)) |
| 382 | |
| 383 | } |
| 384 | |
| 385 | return a.verifyUpload(t, workerNum) |
| 386 | } |
| 387 | |
| 388 | func (a *SSHAdapter) argumentsForTransfer(t *Transfer, action string) []string { |
| 389 | args := make([]string, 0, 3) |
| 390 | set, ok := t.Actions[action] |
| 391 | if !ok { |
| 392 | return nil |
| 393 | } |
| 394 | args = append(args, fmt.Sprintf("size=%d", t.Size)) |
| 395 | if set.Id != "" { |
| 396 | args = append(args, fmt.Sprintf("id=%s", set.Id)) |
| 397 | } |
| 398 | if set.Token != "" { |
| 399 | args = append(args, fmt.Sprintf("token=%s", set.Token)) |
| 400 | } |
| 401 | return args |
| 402 | } |
| 403 | |
| 404 | // Begin a new batch of uploads or downloads. Call this first, followed by one |
| 405 | // or more Add calls. The passed in callback will receive updates on progress. |
| 406 | func (a *SSHAdapter) Begin(cfg AdapterConfig, cb ProgressCallback) error { |
| 407 | if err := a.adapterBase.Begin(cfg, cb); err != nil { |
| 408 | return err |
| 409 | } |
| 410 | a.ctx = a.adapterBase.apiClient.Context() |
| 411 | a.debugging = a.ctx.OSEnv().Bool("GIT_TRANSFER_TRACE", false) |
| 412 | return nil |
| 413 | } |
| 414 | |
| 415 | func (a *SSHAdapter) Trace(format string, args ...interface{}) { |
| 416 | if !a.adapterBase.debugging { |
| 417 | return |
| 418 | } |
| 419 | tracerx.Printf(format, args...) |
| 420 | } |
| 421 | |
| 422 | func configureSSHAdapter(m *concreteManifest) { |
| 423 | m.RegisterNewAdapterFunc(SSHAdapterName, Upload, false, func(name string, dir Direction) Adapter { |
| 424 | a := &SSHAdapter{newAdapterBase(m.fs, name, dir, nil), nil, m.sshTransfer} |
| 425 | a.transferImpl = a |
| 426 | return a |
| 427 | }) |
| 428 | m.RegisterNewAdapterFunc(SSHAdapterName, Download, false, func(name string, dir Direction) Adapter { |
| 429 | a := &SSHAdapter{newAdapterBase(m.fs, name, dir, nil), nil, m.sshTransfer} |
| 430 | a.transferImpl = a |
| 431 | return a |
| 432 | }) |
| 433 | } |