git-lfs/lfs/client.go

711 lines
16 KiB
Go
Raw Normal View History

2015-03-19 19:30:55 +00:00
package lfs
2013-10-04 17:09:03 +00:00
import (
2015-03-20 01:55:40 +00:00
"bytes"
"encoding/base64"
2015-03-19 23:20:39 +00:00
"encoding/json"
"errors"
2013-10-04 17:09:03 +00:00
"fmt"
"io"
2015-03-19 23:20:39 +00:00
"io/ioutil"
2013-10-04 17:09:03 +00:00
"net/http"
"net/url"
2015-03-20 01:55:40 +00:00
"os"
"path/filepath"
2015-03-19 23:20:39 +00:00
"regexp"
2015-03-20 01:55:40 +00:00
"strconv"
2015-05-13 19:43:41 +00:00
2015-05-25 18:20:50 +00:00
"github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx"
2013-10-04 17:09:03 +00:00
)
const (
mediaType = "application/vnd.git-lfs+json; charset=utf-8"
)
2015-03-19 21:16:52 +00:00
var (
2015-03-20 17:10:38 +00:00
lfsMediaTypeRE = regexp.MustCompile(`\Aapplication/vnd\.git\-lfs\+json(;|\z)`)
2015-03-22 18:32:22 +00:00
jsonMediaTypeRE = regexp.MustCompile(`\Aapplication/json(;|\z)`)
2015-03-19 21:16:52 +00:00
objectRelationDoesNotExist = errors.New("relation does not exist")
hiddenHeaders = map[string]bool{
"Authorization": true,
}
2015-03-19 23:20:39 +00:00
defaultErrors = map[int]string{
400: "Client error: %s",
401: "Authorization error: %s\nCheck that you have proper access to the repository",
2015-03-27 15:53:02 +00:00
403: "Authorization error: %s\nCheck that you have proper access to the repository",
2015-03-19 23:20:39 +00:00
404: "Repository or object not found: %s\nCheck that it exists and that you have proper access to it",
500: "Server error: %s",
}
2015-03-19 21:16:52 +00:00
)
2015-08-07 13:32:28 +00:00
type objectError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e *objectError) Error() string {
return fmt.Sprintf("[%d] %s", e.Code, e.Message)
}
2015-02-26 01:09:53 +00:00
type objectResource struct {
2015-07-31 21:20:31 +00:00
Oid string `json:"oid,omitempty"`
Size int64 `json:"size"`
Actions map[string]*linkRelation `json:"actions,omitempty"`
Links map[string]*linkRelation `json:"_links,omitempty"`
2015-08-07 13:32:28 +00:00
Error *objectError `json:"error,omitempty"`
2015-02-26 01:09:53 +00:00
}
func (o *objectResource) NewRequest(relation, method string) (*http.Request, error) {
rel, ok := o.Rel(relation)
if !ok {
return nil, objectRelationDoesNotExist
}
req, err := newClientRequest(method, rel.Href, rel.Header)
if err != nil {
return nil, err
}
return req, nil
}
2015-02-26 01:09:53 +00:00
func (o *objectResource) Rel(name string) (*linkRelation, bool) {
2015-08-07 13:37:03 +00:00
var rel *linkRelation
var ok bool
2015-08-07 13:37:03 +00:00
if o.Actions != nil {
rel, ok = o.Actions[name]
} else {
rel, ok = o.Links[name]
2015-02-26 01:09:53 +00:00
}
return rel, ok
}
type linkRelation struct {
Href string `json:"href"`
Header map[string]string `json:"header,omitempty"`
}
2015-03-19 21:16:52 +00:00
type ClientError struct {
Message string `json:"message"`
DocumentationUrl string `json:"documentation_url,omitempty"`
RequestId string `json:"request_id,omitempty"`
}
2015-03-19 21:16:52 +00:00
func (e *ClientError) Error() string {
msg := e.Message
if len(e.DocumentationUrl) > 0 {
msg += "\nDocs: " + e.DocumentationUrl
2013-10-04 17:09:03 +00:00
}
2015-03-19 21:16:52 +00:00
if len(e.RequestId) > 0 {
msg += "\nRequest ID: " + e.RequestId
}
2015-03-19 21:16:52 +00:00
return msg
2013-10-04 17:09:03 +00:00
}
2015-03-19 21:16:52 +00:00
func Download(oid string) (io.ReadCloser, int64, *WrappedError) {
req, err := newApiRequest("GET", oid)
2015-03-20 01:55:40 +00:00
if err != nil {
return nil, 0, Error(err)
}
res, obj, wErr := doApiRequest(req)
2015-03-20 01:55:40 +00:00
if wErr != nil {
return nil, 0, wErr
}
LogTransfer("lfs.api.download", res)
req, err = obj.NewRequest("download", "GET")
2015-03-20 01:55:40 +00:00
if err != nil {
return nil, 0, Error(err)
}
res, wErr = doStorageRequest(req)
2015-03-20 01:55:40 +00:00
if wErr != nil {
return nil, 0, wErr
}
LogTransfer("lfs.data.download", res)
2015-03-20 01:55:40 +00:00
return res.Body, res.ContentLength, nil
2015-03-19 21:16:52 +00:00
}
2015-01-23 22:11:10 +00:00
2015-03-26 18:46:33 +00:00
type byteCloser struct {
*bytes.Reader
}
2015-05-13 14:23:49 +00:00
func DownloadCheck(oid string) (*objectResource, *WrappedError) {
req, err := newApiRequest("GET", oid)
2015-05-13 14:23:49 +00:00
if err != nil {
return nil, Error(err)
}
res, obj, wErr := doApiRequest(req)
2015-05-13 14:23:49 +00:00
if wErr != nil {
return nil, wErr
}
LogTransfer("lfs.api.download", res)
2015-05-13 14:23:49 +00:00
_, err = obj.NewRequest("download", "GET")
if err != nil {
return nil, Error(err)
}
2015-05-13 14:23:49 +00:00
return obj, nil
}
func DownloadObject(obj *objectResource) (io.ReadCloser, int64, *WrappedError) {
req, err := obj.NewRequest("download", "GET")
2015-05-13 14:23:49 +00:00
if err != nil {
return nil, 0, Error(err)
}
res, wErr := doStorageRequest(req)
2015-05-13 14:23:49 +00:00
if wErr != nil {
return nil, 0, wErr
}
LogTransfer("lfs.data.download", res)
2015-05-13 14:23:49 +00:00
return res.Body, res.ContentLength, nil
}
2015-03-26 18:46:33 +00:00
func (b *byteCloser) Close() error {
return nil
}
2015-06-24 18:59:11 +00:00
func Batch(objects []*objectResource, operation string) ([]*objectResource, *WrappedError) {
if len(objects) == 0 {
return nil, nil
}
2015-06-24 20:52:31 +00:00
o := map[string]interface{}{"objects": objects, "operation": operation}
by, err := json.Marshal(o)
2015-03-20 01:55:40 +00:00
if err != nil {
return nil, Error(err)
2015-03-20 01:55:40 +00:00
}
req, err := newBatchApiRequest()
2015-03-20 01:55:40 +00:00
if err != nil {
return nil, Error(err)
}
req.Header.Set("Content-Type", mediaType)
req.Header.Set("Content-Length", strconv.Itoa(len(by)))
req.ContentLength = int64(len(by))
req.Body = &byteCloser{bytes.NewReader(by)}
tracerx.Printf("api: batch %d files", len(objects))
res, objs, wErr := doApiBatchRequest(req)
if wErr != nil {
if res == nil {
return nil, wErr
}
switch res.StatusCode {
case 401:
Config.SetPrivateAccess()
tracerx.Printf("api: batch not authorized, submitting with auth")
return Batch(objects, operation)
case 404, 410:
tracerx.Printf("api: batch not implemented: %d", res.StatusCode)
return nil, Error(newNotImplError())
}
tracerx.Printf("api error: %s", wErr)
}
LogTransfer("lfs.api.batch", res)
if res.StatusCode != 200 {
2015-08-18 17:10:50 +00:00
return nil, Error(fmt.Errorf("Invalid status for %s %s: %d", req.Method, req.URL, res.StatusCode))
}
return objs, nil
}
func UploadCheck(oidPath string) (*objectResource, *WrappedError) {
oid := filepath.Base(oidPath)
stat, err := os.Stat(oidPath)
if err != nil {
return nil, Error(err)
2015-03-20 01:55:40 +00:00
}
reqObj := &objectResource{
Oid: oid,
Size: stat.Size(),
}
by, err := json.Marshal(reqObj)
if err != nil {
return nil, Error(err)
2015-03-20 01:55:40 +00:00
}
req, err := newApiRequest("POST", oid)
2015-03-20 01:55:40 +00:00
if err != nil {
return nil, Error(err)
2015-03-20 01:55:40 +00:00
}
req.Header.Set("Content-Type", mediaType)
req.Header.Set("Content-Length", strconv.Itoa(len(by)))
req.ContentLength = int64(len(by))
2015-03-26 18:46:33 +00:00
req.Body = &byteCloser{bytes.NewReader(by)}
2015-03-20 01:55:40 +00:00
tracerx.Printf("api: uploading (%s)", oid)
res, obj, wErr := doApiRequest(req)
2015-03-20 01:55:40 +00:00
if wErr != nil {
return nil, wErr
2015-03-20 01:55:40 +00:00
}
LogTransfer("lfs.api.upload", res)
2015-03-20 01:55:40 +00:00
if res.StatusCode == 200 {
return nil, nil
}
if obj.Oid == "" {
obj.Oid = oid
}
if obj.Size == 0 {
obj.Size = reqObj.Size
}
return obj, nil
}
func UploadObject(o *objectResource, cb CopyCallback) *WrappedError {
path, err := LocalMediaPath(o.Oid)
if err != nil {
return Error(err)
}
file, err := os.Open(path)
if err != nil {
return Error(err)
}
defer file.Close()
reader := &CallbackReader{
C: cb,
TotalSize: o.Size,
Reader: file,
}
req, err := o.NewRequest("upload", "PUT")
2015-03-20 01:55:40 +00:00
if err != nil {
return Error(err)
}
if len(req.Header.Get("Content-Type")) == 0 {
req.Header.Set("Content-Type", "application/octet-stream")
}
if req.Header.Get("Transfer-Encoding") == "chunked" {
req.TransferEncoding = []string{"chunked"}
} else {
req.Header.Set("Content-Length", strconv.FormatInt(o.Size, 10))
}
req.ContentLength = o.Size
2015-03-20 18:01:43 +00:00
req.Body = ioutil.NopCloser(reader)
2015-03-20 01:55:40 +00:00
res, wErr := doStorageRequest(req)
2015-03-20 01:55:40 +00:00
if wErr != nil {
return wErr
}
LogTransfer("lfs.data.upload", res)
2015-03-20 01:55:40 +00:00
if res.StatusCode > 299 {
return Errorf(nil, "Invalid status for %s %s: %d", req.Method, req.URL, res.StatusCode)
}
io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
req, err = o.NewRequest("verify", "POST")
2015-03-20 01:55:40 +00:00
if err == objectRelationDoesNotExist {
return nil
} else if err != nil {
return Error(err)
}
by, err := json.Marshal(o)
if err != nil {
return Error(err)
}
2015-03-20 01:55:40 +00:00
req.Header.Set("Content-Type", mediaType)
req.Header.Set("Content-Length", strconv.Itoa(len(by)))
req.ContentLength = int64(len(by))
2015-03-20 01:55:40 +00:00
req.Body = ioutil.NopCloser(bytes.NewReader(by))
res, wErr = doHttpRequest(req, nil)
if wErr != nil {
return wErr
}
LogTransfer("lfs.data.verify", res)
io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
2015-03-20 01:55:40 +00:00
return wErr
2015-01-23 22:11:10 +00:00
}
// doApiRequest to the legacy API.
func doApiRequest(req *http.Request) (*http.Response, *objectResource, *WrappedError) {
via := make([]*http.Request, 0, 4)
res, wErr := doApiRequestWithRedirects(req, via, true)
if wErr != nil {
return res, nil, wErr
}
obj := &objectResource{}
wErr = decodeApiResponse(res, obj)
if wErr != nil {
setErrorResponseContext(wErr, res)
return nil, nil, wErr
}
return res, obj, nil
}
// doApiBatchRequest runs the request to the batch API. If the API returns a 401,
// the repo will be marked as having private access and the request will be
// re-run. When the repo is marked as having private access, credentials will
// be retrieved.
func doApiBatchRequest(req *http.Request) (*http.Response, []*objectResource, *WrappedError) {
via := make([]*http.Request, 0, 4)
res, wErr := doApiRequestWithRedirects(req, via, Config.PrivateAccess())
if wErr != nil {
return res, nil, wErr
}
var objs map[string][]*objectResource
wErr = decodeApiResponse(res, &objs)
if wErr != nil {
setErrorResponseContext(wErr, res)
}
return res, objs["objects"], wErr
}
// doStorageREquest runs the request to the storage API from a link provided by
// the "actions" or "_links" properties an LFS API response.
func doStorageRequest(req *http.Request) (*http.Response, *WrappedError) {
creds, err := getCreds(req)
if err != nil {
return nil, Error(err)
}
return doHttpRequest(req, creds)
}
// doHttpRequest runs the given HTTP request. LFS or Storage API requests should
// use doApiBatchRequest() or doStorageRequest() instead.
func doHttpRequest(req *http.Request, creds Creds) (*http.Response, *WrappedError) {
2015-07-21 20:44:40 +00:00
res, err := Config.HttpClient().Do(req)
if res == nil {
res = &http.Response{
StatusCode: 0,
Header: make(http.Header),
Request: req,
Body: ioutil.NopCloser(bytes.NewBufferString("")),
}
}
2015-03-19 23:20:39 +00:00
var wErr *WrappedError
if err != nil {
wErr = Errorf(err, "Error for %s %s", res.Request.Method, res.Request.URL)
} else {
wErr = handleResponse(res, creds)
2015-03-19 23:20:39 +00:00
}
if wErr != nil {
if res != nil {
setErrorResponseContext(wErr, res)
} else {
setErrorRequestContext(wErr, req)
}
}
return res, wErr
}
func doApiRequestWithRedirects(req *http.Request, via []*http.Request, useCreds bool) (*http.Response, *WrappedError) {
var creds Creds
if useCreds {
c, err := getCredsForAPI(req)
if err != nil {
return nil, Error(err)
}
creds = c
}
res, wErr := doHttpRequest(req, creds)
2015-03-26 18:46:33 +00:00
if wErr != nil {
return res, wErr
2015-03-26 18:46:33 +00:00
}
if res.StatusCode == 307 {
redirectTo := res.Header.Get("Location")
locurl, err := url.Parse(redirectTo)
if err == nil && !locurl.IsAbs() {
locurl = req.URL.ResolveReference(locurl)
redirectTo = locurl.String()
}
redirectedReq, err := newClientRequest(req.Method, redirectTo, nil)
2015-03-26 18:46:33 +00:00
if err != nil {
return res, Errorf(err, err.Error())
2015-03-26 18:46:33 +00:00
}
via = append(via, req)
// Avoid seeking and re-wrapping the countingReadCloser, just get the "real" body
realBody := req.Body
if wrappedBody, ok := req.Body.(*countingReadCloser); ok {
realBody = wrappedBody.ReadCloser
}
seeker, ok := realBody.(io.Seeker)
2015-05-11 14:42:31 +00:00
if !ok {
return res, Errorf(nil, "Request body needs to be an io.Seeker to handle redirects.")
2015-03-26 18:46:33 +00:00
}
2015-05-11 14:42:31 +00:00
if _, err := seeker.Seek(0, 0); err != nil {
return res, Error(err)
2015-05-11 14:42:31 +00:00
}
redirectedReq.Body = realBody
2015-05-11 14:42:31 +00:00
redirectedReq.ContentLength = req.ContentLength
2015-03-26 18:46:33 +00:00
if err = checkRedirect(redirectedReq, via); err != nil {
return res, Errorf(err, err.Error())
2015-03-26 18:46:33 +00:00
}
return doApiRequestWithRedirects(redirectedReq, via, useCreds)
2015-03-26 18:46:33 +00:00
}
2015-05-11 14:42:23 +00:00
return res, nil
2015-03-26 18:46:33 +00:00
}
func handleResponse(res *http.Response, creds Creds) *WrappedError {
saveCredentials(creds, res)
2015-03-19 23:20:39 +00:00
if res.StatusCode < 400 {
return nil
}
defer func() {
io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
}()
2015-03-20 01:55:40 +00:00
cliErr := &ClientError{}
wErr := decodeApiResponse(res, cliErr)
if wErr == nil {
if len(cliErr.Message) == 0 {
wErr = defaultError(res)
} else {
wErr = Error(cliErr)
2015-03-19 23:20:39 +00:00
}
}
wErr.Panic = res.StatusCode > 499 && res.StatusCode != 501 && res.StatusCode != 509
return wErr
}
2015-03-20 01:55:40 +00:00
func decodeApiResponse(res *http.Response, obj interface{}) *WrappedError {
2015-03-20 17:10:38 +00:00
ctype := res.Header.Get("Content-Type")
2015-03-22 18:32:22 +00:00
if !(lfsMediaTypeRE.MatchString(ctype) || jsonMediaTypeRE.MatchString(ctype)) {
2015-03-20 01:55:40 +00:00
return nil
}
err := json.NewDecoder(res.Body).Decode(obj)
io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
2015-03-20 01:55:40 +00:00
if err != nil {
return Errorf(err, "Unable to parse HTTP response for %s %s", res.Request.Method, res.Request.URL)
}
return nil
}
2015-03-19 23:20:39 +00:00
func defaultError(res *http.Response) *WrappedError {
var msgFmt string
if f, ok := defaultErrors[res.StatusCode]; ok {
msgFmt = f
} else if res.StatusCode < 500 {
msgFmt = defaultErrors[400] + fmt.Sprintf(" from HTTP %d", res.StatusCode)
} else {
msgFmt = defaultErrors[500] + fmt.Sprintf(" from HTTP %d", res.StatusCode)
}
return Error(fmt.Errorf(msgFmt, res.Request.URL))
}
func newApiRequest(method, oid string) (*http.Request, error) {
endpoint := Config.Endpoint()
objectOid := oid
operation := "download"
if method == "POST" {
if oid != "batch" {
objectOid = ""
operation = "upload"
}
}
res, err := sshAuthenticate(endpoint, operation, oid)
if err != nil {
tracerx.Printf("ssh: attempted with %s. Error: %s",
endpoint.SshUserAndHost, err.Error(),
)
}
if len(res.Href) > 0 {
endpoint.Url = res.Href
}
u, err := ObjectUrl(endpoint, objectOid)
2015-01-23 22:11:10 +00:00
if err != nil {
return nil, err
2015-01-23 22:11:10 +00:00
}
req, err := newClientRequest(method, u.String(), res.Header)
2015-05-11 14:42:34 +00:00
if err != nil {
return nil, err
2015-05-11 14:42:34 +00:00
}
req.Header.Set("Accept", mediaType)
return req, nil
2015-01-23 22:11:10 +00:00
}
func newClientRequest(method, rawurl string, header map[string]string) (*http.Request, error) {
2015-03-19 21:16:52 +00:00
req, err := http.NewRequest(method, rawurl, nil)
if err != nil {
return nil, err
}
for key, value := range header {
req.Header.Set(key, value)
}
2015-03-19 21:16:52 +00:00
req.Header.Set("User-Agent", UserAgent)
return req, nil
}
func newBatchApiRequest() (*http.Request, error) {
2015-06-18 16:31:33 +00:00
endpoint := Config.Endpoint()
res, err := sshAuthenticate(endpoint, "download", "")
if err != nil {
tracerx.Printf("ssh: attempted with %s. Error: %s",
endpoint.SshUserAndHost, err.Error(),
)
}
if len(res.Href) > 0 {
endpoint.Url = res.Href
}
u, err := ObjectUrl(endpoint, "batch")
if err != nil {
return nil, err
2015-06-18 16:31:33 +00:00
}
req, err := newBatchClientRequest("POST", u.String())
2015-06-18 16:31:33 +00:00
if err != nil {
return nil, err
2015-06-18 16:31:33 +00:00
}
req.Header.Set("Accept", mediaType)
if res.Header != nil {
for key, value := range res.Header {
req.Header.Set(key, value)
}
}
return req, nil
2015-06-18 16:31:33 +00:00
}
func newBatchClientRequest(method, rawurl string) (*http.Request, error) {
2015-06-18 16:31:33 +00:00
req, err := http.NewRequest(method, rawurl, nil)
if err != nil {
return nil, err
2015-06-18 16:31:33 +00:00
}
req.Header.Set("User-Agent", UserAgent)
return req, nil
2015-06-18 16:31:33 +00:00
}
func setRequestAuthFromUrl(req *http.Request, u *url.URL) bool {
if u.User != nil {
if pass, ok := u.User.Password(); ok {
fmt.Fprintln(os.Stderr, "warning: current Git remote contains credentials")
setRequestAuth(req, u.User.Username(), pass)
return true
}
}
return false
}
func setRequestAuth(req *http.Request, user, pass string) {
if len(user) == 0 && len(pass) == 0 {
return
}
token := fmt.Sprintf("%s:%s", user, pass)
auth := "Basic " + base64.URLEncoding.EncodeToString([]byte(token))
req.Header.Set("Authorization", auth)
2014-08-08 20:02:44 +00:00
}
func setErrorResponseContext(err *WrappedError, res *http.Response) {
2014-08-08 17:31:33 +00:00
err.Set("Status", res.Status)
2014-08-08 20:02:44 +00:00
setErrorHeaderContext(err, "Request", res.Header)
2014-08-08 17:31:33 +00:00
setErrorRequestContext(err, res.Request)
2013-11-02 00:23:37 +00:00
}
func setErrorRequestContext(err *WrappedError, req *http.Request) {
err.Set("Endpoint", Config.Endpoint().Url)
err.Set("URL", fmt.Sprintf("%s %s", req.Method, req.URL.String()))
setErrorHeaderContext(err, "Response", req.Header)
}
func setErrorHeaderContext(err *WrappedError, prefix string, head http.Header) {
2014-08-08 20:02:44 +00:00
for key, _ := range head {
contextKey := fmt.Sprintf("%s:%s", prefix, key)
if _, skip := hiddenHeaders[key]; skip {
err.Set(contextKey, "--")
} else {
err.Set(contextKey, head.Get(key))
}
}
}
type notImplError struct {
error
}
func (e notImplError) NotImplemented() bool {
return true
}
func newNotImplError() error {
return notImplError{errors.New("Not Implemented")}
}
func isNotImplError(err *WrappedError) bool {
type notimplerror interface {
NotImplemented() bool
}
if e, ok := err.Err.(notimplerror); ok {
return e.NotImplemented()
}
return false
}