From cd93bfd2516e4daecc727ec4953c56693bed8699 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Wed, 13 May 2015 16:36:54 -0700 Subject: [PATCH] Migrate mc s3 client code to objecstorage-go library, now all requests from mc are signature v4 authenticated --- Godeps/Godeps.json | 4 + .../minio/objectstorage-go/.travis.yml | 4 + .../minio/objectstorage-go/CONTRIBUTING.md | 34 ++ .../minio/objectstorage-go}/LICENSE | 0 .../minio/objectstorage-go/README.md | 24 + .../github.com/minio/objectstorage-go/api.go | 409 ++++++++++++++ .../minio/objectstorage-go/api_test.go | 20 +- .../examples/play/get_object.go | 50 ++ .../examples/play/list_buckets.go | 37 +- .../examples/play/list_objects.go | 40 ++ .../examples/play/put_object.go | 51 ++ .../objectstorage-go/examples/play/testfile | Bin 0 -> 16384 bytes .../examples/s3/get_object.go | 50 ++ .../examples/s3/list_buckets.go | 40 ++ .../examples/s3/list_objects.go | 40 ++ .../examples/s3/put_object.go | 51 ++ .../objectstorage-go/examples/s3/testfile | Bin 0 -> 16384 bytes .../minio/objectstorage-go/low_level_api.go | 513 ++++++++++++++++++ .../objectstorage-go/low_level_common.go | 77 +++ .../objectstorage-go/low_level_definitions.go | 132 +++++ .../objectstorage-go/low_level_errors.go | 58 ++ .../low_level_multipart_api.go | 202 +++++++ .../objectstorage-go/low_level_request.go | 237 ++++++++ .../minio/objectstorage-go/low_level_test.go | 53 ++ .../minio/objectstorage-go/multipart.go | 97 ++++ cmd-cat.go | 2 +- cmd-common.go | 2 +- common-methods.go | 7 +- cp-methods.go | 2 +- cp.go | 6 +- pkg/client/client.go | 4 +- pkg/client/errors.go | 4 +- pkg/client/fs/fs.go | 13 +- pkg/client/fs/fs_put.go | 10 +- pkg/client/s3/.gitignore | 1 - pkg/client/s3/LICENSE.GOOGLE | 20 - pkg/client/s3/auth.go | 220 -------- pkg/client/s3/auth_test.go | 61 --- pkg/client/s3/bucket.go | 125 ----- pkg/client/s3/bucket_object_metadata.go | 114 ---- pkg/client/s3/bucket_routines.go | 342 ------------ pkg/client/s3/client_test.go | 123 ----- pkg/client/s3/common.go | 48 -- pkg/client/s3/definitions.go | 81 --- pkg/client/s3/doc.go | 1 - pkg/client/s3/errors.go | 51 +- pkg/client/s3/object_get.go | 87 --- pkg/client/s3/object_put.go | 99 ---- pkg/client/s3/request.go | 95 ---- pkg/client/s3/s3.go | 270 +++++++++ pkg/client/s3/s3verify.go | 67 --- pkg/client/s3/trace.go | 2 +- 52 files changed, 2493 insertions(+), 1587 deletions(-) create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/.travis.yml create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/CONTRIBUTING.md rename {pkg/client/s3 => Godeps/_workspace/src/github.com/minio/objectstorage-go}/LICENSE (100%) create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/README.md create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/api.go rename pkg/client/s3/globals.go => Godeps/_workspace/src/github.com/minio/objectstorage-go/api_test.go (62%) create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/get_object.go rename pkg/client/s3/bucket_list_contents.go => Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/list_buckets.go (50%) create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/list_objects.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/put_object.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/testfile create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/get_object.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/list_buckets.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/list_objects.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/put_object.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/testfile create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_api.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_common.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_definitions.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_errors.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_multipart_api.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_request.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_test.go create mode 100644 Godeps/_workspace/src/github.com/minio/objectstorage-go/multipart.go delete mode 100644 pkg/client/s3/.gitignore delete mode 100644 pkg/client/s3/LICENSE.GOOGLE delete mode 100644 pkg/client/s3/auth.go delete mode 100644 pkg/client/s3/auth_test.go delete mode 100644 pkg/client/s3/bucket.go delete mode 100644 pkg/client/s3/bucket_object_metadata.go delete mode 100644 pkg/client/s3/bucket_routines.go delete mode 100644 pkg/client/s3/client_test.go delete mode 100644 pkg/client/s3/common.go delete mode 100644 pkg/client/s3/definitions.go delete mode 100644 pkg/client/s3/doc.go delete mode 100644 pkg/client/s3/object_get.go delete mode 100644 pkg/client/s3/object_put.go delete mode 100644 pkg/client/s3/request.go create mode 100644 pkg/client/s3/s3.go delete mode 100644 pkg/client/s3/s3verify.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 75264de9..93ea41cd 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -34,6 +34,10 @@ "ImportPath": "github.com/minio/minio/pkg/iodine", "Rev": "0f58045480309d4b13fe45878f05736c3ff20e7e" }, + { + "ImportPath": "github.com/minio/objectstorage-go", + "Rev": "8bf71605180e3d825840bcabfb40e179bf99548d" + }, { "ImportPath": "github.com/shiena/ansicolor", "Rev": "8368d3b31cf6f2c2464c7a91675342c9a0ac6658" diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/.travis.yml b/Godeps/_workspace/src/github.com/minio/objectstorage-go/.travis.yml new file mode 100644 index 00000000..6e3b6fc0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/.travis.yml @@ -0,0 +1,4 @@ +language: go +go: +- 1.4.2 +sudo: false diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/CONTRIBUTING.md b/Godeps/_workspace/src/github.com/minio/objectstorage-go/CONTRIBUTING.md new file mode 100644 index 00000000..08a857ac --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/CONTRIBUTING.md @@ -0,0 +1,34 @@ +### Setup your objectstorage-go Github Repository +Fork [objectstorage-go upstream](https://github.com/minio/objectstorage-go/fork) source repository to your own personal repository. +```sh +$ git clone https://github.com/$USER_ID/objectstorage-go +$ cd objectstorage-go +$ make +$ objectstorage-go --help +``` + +### Developer Guidelines + +``objectstorage-go`` welcomes your contribution. To make the process as seamless as possible, we ask for the following: + +* Go ahead and fork the project and make your changes. We encourage pull requests to discuss code changes. + - Fork it + - Create your feature branch (git checkout -b my-new-feature) + - Commit your changes (git commit -am 'Add some feature') + - Push to the branch (git push origin my-new-feature) + - Create new Pull Request + +* If you have additional dependencies for ``objectstorage-go``, ``objectstorage-go`` manages its depedencies using [godep](https://github.com/tools/godep) + - Run `go get foo/bar` + - Edit your code to import foo/bar + - Run `make save` from top-level directory (or `godep restore && godep save ./...`). + +* When you're ready to create a pull request, be sure to: + - Have test cases for the new code. If you have questions about how to do it, please ask in your pull request. + - Run `go fmt` + - Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request. + - Make sure `go test -race ./...` and `go build` completes. + +* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project + - `objectstorage-go` project is strictly conformant with Golang style + - if you happen to observe offending code, please feel free to send a pull request diff --git a/pkg/client/s3/LICENSE b/Godeps/_workspace/src/github.com/minio/objectstorage-go/LICENSE similarity index 100% rename from pkg/client/s3/LICENSE rename to Godeps/_workspace/src/github.com/minio/objectstorage-go/LICENSE diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/README.md b/Godeps/_workspace/src/github.com/minio/objectstorage-go/README.md new file mode 100644 index 00000000..bbf6f5a3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/README.md @@ -0,0 +1,24 @@ +# Minimal object storage library in Go + +## Install + +```go +# go get github.com/minio/objectstorage-go +``` + +## Documentation + +[Objectstorage library in Go](http://godoc.org/github.com/minio/objectstorage-go) + +## Join Community +* Community hangout on Gitter [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +* Ask questions on Quora [![Quora](http://upload.wikimedia.org/wikipedia/commons/thumb/5/57/Quora_logo.svg/55px-Quora_logo.svg.png)](http://www.quora.com/Minio) + +## Roadmap + +- Add v4 signature support +- Add s3 multi region support + +## Contribute + +[Contribute to minimal object storage library](./CONTRIBUTING.md) diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/api.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/api.go new file mode 100644 index 00000000..d112a61f --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/api.go @@ -0,0 +1,409 @@ +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package objectstorage + +import ( + "errors" + "io" + "net/http" + "runtime" + "sort" + "strings" + "time" +) + +// API - object storage API interface +type API interface { + // Bucket Read/Write/Stat operations + BucketAPI + + // Object Read/Write/Stat operations + ObjectAPI +} + +// BucketAPI - bucket specific Read/Write/Stat interface +type BucketAPI interface { + CreateBucket(bucket, acl, location string) error + SetBucketACL(bucket, acl string) error + StatBucket(bucket string) error + DeleteBucket(bucket string) error + + ListObjects(bucket, prefix string, recursive bool) <-chan ObjectOnChannel + ListBuckets() <-chan BucketOnChannel +} + +// ObjectAPI - object specific Read/Write/Stat interface +type ObjectAPI interface { + GetObject(bucket, object string, offset, length uint64) (io.ReadCloser, *ObjectMetadata, error) + CreateObject(bucket, object string, size uint64, data io.Reader) (string, error) + StatObject(bucket, object string) (*ObjectMetadata, error) + DeleteObject(bucket, object string) error +} + +// BucketOnChannel - bucket metadata over read channel +type BucketOnChannel struct { + Data *BucketMetadata + Err error +} + +// ObjectOnChannel - object metadata over read channel +type ObjectOnChannel struct { + Data *ObjectMetadata + Err error +} + +// BucketMetadata container for bucket metadata +type BucketMetadata struct { + // The name of the bucket. + Name string + // Date the bucket was created. + CreationDate time.Time +} + +// ObjectMetadata container for object metadata +type ObjectMetadata struct { + ETag string + Key string + LastModified time.Time + Size int64 + + Owner struct { + DisplayName string + ID string + } + + // The class of storage used to store the object. + StorageClass string +} + +// Regions s3 region map used by bucket location constraint +var Regions = map[string]string{ + "us-gov-west-1": "https://s3-fips-us-gov-west-1.amazonaws.com", + "us-east-1": "https://s3.amazonaws.com", + "us-west-1": "https://s3-us-west-1.amazonaws.com", + "us-west-2": "https://s3-us-west-2.amazonaws.com", + "eu-west-1": "https://s3-eu-west-1.amazonaws.com", + "eu-central-1": "https://s3-eu-central-1.amazonaws.com", + "ap-southeast-1": "https://s3-ap-southeast-1.amazonaws.com", + "ap-southeast-2": "https://s3-ap-southeast-2.amazonaws.com", + "ap-northeast-1": "https://s3-ap-northeast-1.amazonaws.com", + "sa-east-1": "https://s3-sa-east-1.amazonaws.com", + "cn-north-1": "https://s3.cn-north-1.amazonaws.com.cn", +} + +// getEndpoint fetches an endpoint based on region through the S3 Regions map +func getEndpoint(region string) string { + return Regions[region] +} + +type api struct { + *lowLevelAPI +} + +// Config - main configuration struct used by all to set endpoint, credentials, and other options for requests. +type Config struct { + // Standard options + AccessKeyID string + SecretAccessKey string + Region string + Endpoint string + + // Advanced options + AcceptType string // specify this to get server response in non XML style if server supports it + UserAgent string // user override useful when objectstorage-go is used with in your application + Transport http.RoundTripper // custom transport usually for debugging, by default its nil +} + +// MustGetEndpoint makes sure that a valid endpoint is provided all the time, even with false regions it will fall +// back to default, for no regions specified it chooses to default to "milkyway" and use endpoint as is +func (c *Config) MustGetEndpoint() string { + // for custom domains, there are no regions default to 'milkyway' + if strings.TrimSpace(c.Region) == "" && strings.TrimSpace(c.Endpoint) != "" { + c.Region = "milkyway" + return c.Endpoint + } + // if valid region provided override user provided endpoint + if endpoint := getEndpoint(strings.TrimSpace(c.Region)); endpoint != "" { + c.Endpoint = endpoint + return c.Endpoint + } + // fall back if region is set and not found, go through US-standard + c.Region = "us-east-1" + return getEndpoint(c.Region) +} + +// Global constants +const ( + LibraryName = "objectstorage-go/" + LibraryVersion = "0.1" +) + +// New - instantiate a new minio api client +func New(config *Config) API { + // if not UserAgent provided set it to default + if strings.TrimSpace(config.UserAgent) == "" { + config.UserAgent = LibraryName + " (" + LibraryVersion + "; " + runtime.GOOS + "; " + runtime.GOARCH + ")" + } + return &api{&lowLevelAPI{config}} +} + +/// Object operations + +// GetObject retrieve object +// +// Additionally it also takes range arguments to download the specified range bytes of an object. +// For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. +func (a *api) GetObject(bucket, object string, offset, length uint64) (io.ReadCloser, *ObjectMetadata, error) { + // get the the object + // NOTE : returned md5sum could be the md5sum of the partial object itself + // not the whole object depending on if offset range was requested or not + body, objectMetadata, err := a.getObject(bucket, object, offset, length) + if err != nil { + return nil, nil, err + } + return body, objectMetadata, nil +} + +// completedParts is a wrapper to make parts sortable by their part number +// multi part completion requires list of multi parts to be sorted +type completedParts []*completePart + +func (a completedParts) Len() int { return len(a) } +func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].PartNumber } + +// DefaultPartSize - default size per object after which PutObject becomes multipart +// one can change this value during a library import +var DefaultPartSize uint64 = 1024 * 1024 * 5 + +// CreateObject create an object in a bucket +// +// You must have WRITE permissions on a bucket to create an object +// +// This version of CreateObject automatically does multipart for more than 5MB worth of data +func (a *api) CreateObject(bucket, object string, size uint64, data io.Reader) (string, error) { + switch { + case size < DefaultPartSize: + // Single Part use case, use PutObject directly + for part := range MultiPart(data, DefaultPartSize) { + if part.Err != nil { + return "", part.Err + } + return "", a.putObject(bucket, object, part.Len, part.Data) + } + default: + initiateMultipartUploadResult, err := a.initiateMultipartUpload(bucket, object) + if err != nil { + return "", err + } + uploadID := initiateMultipartUploadResult.UploadID + completeMultipartUpload := new(completeMultipartUpload) + for part := range MultiPart(data, DefaultPartSize) { + if part.Err != nil { + return "", part.Err + } + completePart, err := a.uploadPart(bucket, object, uploadID, part.Num, part.Len, part.Data) + if err != nil { + return "", a.abortMultipartUpload(bucket, object, uploadID) + } + completeMultipartUpload.Part = append(completeMultipartUpload.Part, completePart) + } + sort.Sort(completedParts(completeMultipartUpload.Part)) + completeMultipartUploadResult, err := a.completeMultipartUpload(bucket, object, uploadID, completeMultipartUpload) + if err != nil { + return "", a.abortMultipartUpload(bucket, object, uploadID) + } + return completeMultipartUploadResult.ETag, nil + } + return "", errors.New("Unexpected control flow") +} + +// StatObject verify if object exists and you have permission to access it +func (a *api) StatObject(bucket, object string) (*ObjectMetadata, error) { + return a.headObject(bucket, object) +} + +// DeleteObject remove the object from a bucket +func (a *api) DeleteObject(bucket, object string) error { + return a.deleteObject(bucket, object) +} + +/// Bucket operations + +// CreateBucket create a new bucket +// +// optional arguments are acl and location - by default all buckets are created +// with ``private`` acl and location set to US Standard if one wishes to set +// different ACLs and Location one can set them properly. +// +// ACL valid values +// ------------------ +// private - owner gets full access [DEFAULT] +// public-read - owner gets full access, others get read access +// public-read-write - owner gets full access, others get full access too +// ------------------ +// +// Location valid values +// ------------------ +// [ us-west-1 | us-west-2 | eu-west-1 | eu-central-1 | ap-southeast-1 | ap-northeast-1 | ap-southeast-2 | sa-east-1 ] +// Default - US standard +func (a *api) CreateBucket(bucket, acl, location string) error { + return a.putBucket(bucket, acl, location) +} + +// SetBucketACL set the permissions on an existing bucket using access control lists (ACL) +// +// Currently supported are: +// ------------------ +// private - owner gets full access +// public-read - owner gets full access, others get read access +// public-read-write - owner gets full access, others get full access too +// ------------------ +func (a *api) SetBucketACL(bucket, acl string) error { + return a.putBucketACL(bucket, acl) +} + +// StatBucket verify if bucket exists and you have permission to access it +func (a *api) StatBucket(bucket string) error { + return a.headBucket(bucket) +} + +// DeleteBucket deletes the bucket named in the URI +// NOTE: - +// All objects (including all object versions and delete markers) +// in the bucket must be deleted before successfully attempting this request +func (a *api) DeleteBucket(bucket string) error { + return a.deleteBucket(bucket) +} + +// listObjectsInRoutine is an internal goroutine function called for listing objects +// This function feeds data into channel +func (a *api) listObjectsInRoutine(bucket, prefix string, recursive bool, ch chan ObjectOnChannel) { + defer close(ch) + switch { + case recursive == true: + listBucketResult, err := a.listObjects(bucket, 1000, "", prefix, "") + if err != nil { + ch <- ObjectOnChannel{ + Data: nil, + Err: err, + } + return + } + for _, object := range listBucketResult.Contents { + ch <- ObjectOnChannel{ + Data: object, + Err: nil, + } + } + for { + if !listBucketResult.IsTruncated { + break + } + listBucketResult, err = a.listObjects(bucket, 1000, listBucketResult.Marker, prefix, "") + if err != nil { + ch <- ObjectOnChannel{ + Data: nil, + Err: err, + } + return + } + for _, object := range listBucketResult.Contents { + ch <- ObjectOnChannel{ + Data: object, + Err: nil, + } + listBucketResult.Marker = object.Key + } + } + default: + listBucketResult, err := a.listObjects(bucket, 1000, "", prefix, "/") + if err != nil { + ch <- ObjectOnChannel{ + Data: nil, + Err: err, + } + return + } + for _, object := range listBucketResult.Contents { + ch <- ObjectOnChannel{ + Data: object, + Err: nil, + } + } + } +} + +// ListObjects - (List Objects) - List some objects or all recursively +// +// ListObjects is a channel based API implemented to facilitate ease of usage of S3 API ListObjects() +// by automatically recursively traversing all objects on a given bucket if specified. +// +// Your input paramters are just bucket, prefix and recursive +// +// If you enable recursive as 'true' this function will return back all the objects in a given bucket +// +// eg:- +// api := objectstorage.New(....) +// for message := range api.ListObjects("mytestbucket", "starthere", true) { +// fmt.Println(message.Data) +// } +// +func (a *api) ListObjects(bucket string, prefix string, recursive bool) <-chan ObjectOnChannel { + ch := make(chan ObjectOnChannel) + go a.listObjectsInRoutine(bucket, prefix, recursive, ch) + return ch +} + +// listBucketsInRoutine is an internal go routine function called for listing buckets +// This function feeds data into channel +func (a *api) listBucketsInRoutine(ch chan BucketOnChannel) { + defer close(ch) + listAllMyBucketListResults, err := a.listBuckets() + if err != nil { + ch <- BucketOnChannel{ + Data: nil, + Err: err, + } + return + } + for _, bucket := range listAllMyBucketListResults.Buckets.Bucket { + ch <- BucketOnChannel{ + Data: bucket, + Err: nil, + } + } + +} + +// ListBuckets list of all buckets owned by the authenticated sender of the request +// +// NOTE: +// This call requires explicit authentication, no anonymous +// requests are allowed for listing buckets +// +// eg:- +// api := objectstorage.New(....) +// for message := range api.ListBuckets() { +// fmt.Println(message.Data) +// } +// +func (a *api) ListBuckets() <-chan BucketOnChannel { + ch := make(chan BucketOnChannel) + go a.listBucketsInRoutine(ch) + return ch +} diff --git a/pkg/client/s3/globals.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/api_test.go similarity index 62% rename from pkg/client/s3/globals.go rename to Godeps/_workspace/src/github.com/minio/objectstorage-go/api_test.go index 3d2aa7a3..0e14e856 100644 --- a/pkg/client/s3/globals.go +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/api_test.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2015 Minio, Inc. + * Minimal object storage library (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,9 +14,19 @@ * limitations under the License. */ -// Package s3 contains all client specific global variables and constants -package s3 +package objectstorage_test -const ( - globalMaxKeys = 1000 // Maximum number of keys to fetch per request +import ( + "net/http/httptest" + "testing" ) + +func TestBucketOperations(t *testing.T) { + ts := httptest.NewServer(robotsTxtHandler) + defer ts.Close() +} + +func TestObjectOperations(t *testing.T) { + ts := httptest.NewServer(robotsTxtHandler) + defer ts.Close() +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/get_object.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/get_object.go new file mode 100644 index 00000000..47077fdf --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/get_object.go @@ -0,0 +1,50 @@ +// +build ignore + +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "io" + "log" + "os" + + "github.com/minio/objectstorage-go" +) + +func main() { + config := new(objectstorage.Config) + config.AccessKeyID = "" + config.SecretAccessKey = "" + config.Endpoint = "http://play.minio.io:9000" + config.AcceptType = "" + m := objectstorage.New(config) + reader, size, _, err := m.GetObject("testbucket", "testfile", 0, 0) + if err != nil { + log.Println(err) + } + localfile, err := os.Create("newfile") + if err != nil { + log.Println(err) + } + defer localfile.Close() + + _, err = io.CopyN(localfile, reader, size) + if err != nil { + log.Println(err) + } +} diff --git a/pkg/client/s3/bucket_list_contents.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/list_buckets.go similarity index 50% rename from pkg/client/s3/bucket_list_contents.go rename to Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/list_buckets.go index 5da97bee..90e32872 100644 --- a/pkg/client/s3/bucket_list_contents.go +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/list_buckets.go @@ -1,5 +1,7 @@ +// +build ignore + /* - * Minio Client (C) 2015 Minio, Inc. + * Minimal object storage library (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,22 +16,25 @@ * limitations under the License. */ -package s3 +package main -import "github.com/minio/mc/pkg/client" +import ( + "log" -/// Bucket API operations + "github.com/minio/objectstorage-go" +) -// List - list at delimited path not recursive -func (c *s3Client) List() <-chan client.ContentOnChannel { - contentCh := make(chan client.ContentOnChannel) - go c.listInGoRoutine(contentCh) - return contentCh -} - -// ListRecursive - list buckets and objects recursively -func (c *s3Client) ListRecursive() <-chan client.ContentOnChannel { - contentCh := make(chan client.ContentOnChannel) - go c.listRecursiveInGoRoutine(contentCh) - return contentCh +func main() { + config := new(objectstorage.Config) + config.AccessKeyID = "" + config.SecretAccessKey = "" + config.Endpoint = "http://play.minio.io:9000" + config.AcceptType = "" + m := objectstorage.New(config) + for message := range m.ListBuckets() { + if message.Err != nil { + log.Fatal(message.Err) + } + log.Println(message.Data) + } } diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/list_objects.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/list_objects.go new file mode 100644 index 00000000..0f814740 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/list_objects.go @@ -0,0 +1,40 @@ +// +build ignore + +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "log" + + "github.com/minio/objectstorage-go" +) + +func main() { + config := new(objectstorage.Config) + config.AccessKeyID = "" + config.SecretAccessKey = "" + config.Endpoint = "http://play.minio.io:9000" + config.AcceptType = "" + m := objectstorage.New(config) + for message := range m.ListObjects("public-bucket", "", true) { + if message.Err != nil { + log.Fatal(message.Err) + } + log.Println(message.Data) + } +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/put_object.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/put_object.go new file mode 100644 index 00000000..7f1e8653 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/put_object.go @@ -0,0 +1,51 @@ +// +build ignore + +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "log" + "os" + + "github.com/minio/objectstorage-go" +) + +func main() { + config := new(objectstorage.Config) + config.AccessKeyID = "" + config.SecretAccessKey = "" + config.Endpoint = "http://play.minio.io:9000" + config.AcceptType = "" + m := objectstorage.New(config) + object, err := os.Open("testfile") + if err != nil { + log.Fatalln(err) + } + objectInfo, err := object.Stat() + if err != nil { + object.Close() + log.Fatalln(err) + } + uploadID, err := m.CreateObject("testbucket", "testfile", uint64(objectInfo.Size()), object) + if err != nil { + object.Close() + log.Fatalln(err) + } + object.Close() + log.Println(uploadID) +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/testfile b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/play/testfile new file mode 100644 index 0000000000000000000000000000000000000000..294f4016d05bdd696670c4840f1f36a71f9239de GIT binary patch literal 16384 zcmeIuF#!Mo0K%a4Pi+hzh(KY$fB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM q7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjMyaxtA00031 literal 0 HcmV?d00001 diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/get_object.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/get_object.go new file mode 100644 index 00000000..2275f507 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/get_object.go @@ -0,0 +1,50 @@ +// +build ignore + +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "io" + "log" + "os" + + "github.com/minio/objectstorage-go" +) + +func main() { + config := new(objectstorage.Config) + config.AccessKeyID = "" + config.SecretAccessKey = "" + config.Endpoint = "https://s3.amazonaws.com" + config.AcceptType = "" + m := objectstorage.New(config) + reader, size, _, err := m.GetObject("testbucket", "testfile", 0, 0) + if err != nil { + log.Println(err) + } + localfile, err := os.Create("newfile") + if err != nil { + log.Println(err) + } + defer localfile.Close() + + _, err = io.CopyN(localfile, reader, size) + if err != nil { + log.Println(err) + } +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/list_buckets.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/list_buckets.go new file mode 100644 index 00000000..a1dd6a13 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/list_buckets.go @@ -0,0 +1,40 @@ +// +build ignore + +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "log" + + "github.com/minio/objectstorage-go" +) + +func main() { + config := new(objectstorage.Config) + config.AccessKeyID = "" + config.SecretAccessKey = "" + config.Endpoint = "https://s3.amazonaws.com" + config.AcceptType = "" + m := objectstorage.New(config) + for message := range m.ListBuckets() { + if message.Err != nil { + log.Fatal(message.Err) + } + log.Println(message.Data) + } +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/list_objects.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/list_objects.go new file mode 100644 index 00000000..2c61f582 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/list_objects.go @@ -0,0 +1,40 @@ +// +build ignore + +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "log" + + "github.com/minio/objectstorage-go" +) + +func main() { + config := new(objectstorage.Config) + config.AccessKeyID = "" + config.SecretAccessKey = "" + config.Endpoint = "https://s3.amazonaws.com" + config.AcceptType = "" + m := objectstorage.New(config) + for message := range m.ListObjects("public-bucket", "", true) { + if message.Err != nil { + log.Fatal(message.Err) + } + log.Println(message.Data) + } +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/put_object.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/put_object.go new file mode 100644 index 00000000..9114a038 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/put_object.go @@ -0,0 +1,51 @@ +// +build ignore + +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "log" + "os" + + "github.com/minio/objectstorage-go" +) + +func main() { + config := new(objectstorage.Config) + config.AccessKeyID = "" + config.SecretAccessKey = "" + config.Endpoint = "https://s3.amazonaws.com" + config.AcceptType = "" + m := objectstorage.New(config) + object, err := os.Open("testfile") + if err != nil { + log.Fatalln(err) + } + objectInfo, err := object.Stat() + if err != nil { + object.Close() + log.Fatalln(err) + } + uploadID, err := m.CreateObject("testbucket", "testfile", uint64(objectInfo.Size()), object) + if err != nil { + object.Close() + log.Fatalln(err) + } + object.Close() + log.Println(uploadID) +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/testfile b/Godeps/_workspace/src/github.com/minio/objectstorage-go/examples/s3/testfile new file mode 100644 index 0000000000000000000000000000000000000000..294f4016d05bdd696670c4840f1f36a71f9239de GIT binary patch literal 16384 zcmeIuF#!Mo0K%a4Pi+hzh(KY$fB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM q7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjMyaxtA00031 literal 0 HcmV?d00001 diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_api.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_api.go new file mode 100644 index 00000000..158ddc93 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_api.go @@ -0,0 +1,513 @@ +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package objectstorage + +import ( + "bytes" + "encoding/base64" + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +type lowLevelAPI struct { + config *Config +} + +// putBucketRequest wrapper creates a new PutBucket request +func (a *lowLevelAPI) putBucketRequest(bucket, acl, location string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "PUT", + HTTPPath: "/" + bucket, + } + var createBucketConfigBuffer *bytes.Reader + // If location is set use it and create proper bucket configuration + switch { + case location != "": + createBucketConfig := new(createBucketConfiguration) + createBucketConfig.Location = location + createBucketConfigBytes, err := xml.Marshal(createBucketConfig) + if err != nil { + return nil, err + } + createBucketConfigBuffer = bytes.NewReader(createBucketConfigBytes) + } + var r *request + var err error + switch { + case createBucketConfigBuffer == nil: + r, err = newRequest(op, a.config, nil) + if err != nil { + return nil, err + } + default: + r, err = newRequest(op, a.config, createBucketConfigBuffer) + if err != nil { + return nil, err + } + r.req.ContentLength = int64(createBucketConfigBuffer.Len()) + } + // by default bucket is private + switch { + case acl != "": + r.Set("x-amz-acl", acl) + default: + r.Set("x-amz-acl", "private") + } + + return r, nil +} + +/// Bucket Write Operations + +// putBucket create a new bucket +// +// Requires valid AWS Access Key ID to authenticate requests +// Anonymous requests are never allowed to create buckets +// +// optional arguments are acl and location - by default all buckets are created +// with ``private`` acl and location set to US Standard if one wishes to set +// different ACLs and Location one can set them properly. +// +// ACL valid values +// ------------------ +// private - owner gets full access [DEFAULT] +// public-read - owner gets full access, others get read access +// public-read-write - owner gets full access, others get full access too +// ------------------ +// +// Location valid values +// ------------------ +// [ us-west-1 | us-west-2 | eu-west-1 | eu-central-1 | ap-southeast-1 | ap-northeast-1 | ap-southeast-2 | sa-east-1 ] +// Default - US standard +func (a *lowLevelAPI) putBucket(bucket, acl, location string) error { + req, err := a.putBucketRequest(bucket, acl, location) + if err != nil { + return err + } + resp, err := req.Do() + if err != nil { + return err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return responseToError(resp) + } + } + return resp.Body.Close() +} + +// putBucketRequestACL wrapper creates a new putBucketACL request +func (a *lowLevelAPI) putBucketRequestACL(bucket, acl string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "PUT", + HTTPPath: "/" + bucket + "?acl", + } + req, err := newRequest(op, a.config, nil) + if err != nil { + return nil, err + } + req.Set("x-amz-acl", acl) + return req, nil +} + +// putBucketACL set the permissions on an existing bucket using access control lists (ACL) +func (a *lowLevelAPI) putBucketACL(bucket, acl string) error { + req, err := a.putBucketRequestACL(bucket, acl) + if err != nil { + return err + } + resp, err := req.Do() + if err != nil { + return err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return responseToError(resp) + } + } + return resp.Body.Close() +} + +// getBucketLocationRequest wrapper creates a new getBucketLocation request +func (a *lowLevelAPI) getBucketLocationRequest(bucket string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "GET", + HTTPPath: "/" + bucket + "?location", + } + req, err := newRequest(op, a.config, nil) + if err != nil { + return nil, err + } + return req, nil +} + +// getBucketLocation uses location subresource to return a bucket's region +func (a *lowLevelAPI) getBucketLocation(bucket string) (string, error) { + req, err := a.getBucketLocationRequest(bucket) + if err != nil { + return "", err + } + resp, err := req.Do() + if err != nil { + return "", err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return "", responseToError(resp) + } + } + var locationConstraint string + decoder := xml.NewDecoder(resp.Body) + err = decoder.Decode(&locationConstraint) + if err != nil { + return "", err + } + return locationConstraint, resp.Body.Close() +} + +// listObjectsRequest wrapper creates a new ListObjects request +func (a *lowLevelAPI) listObjectsRequest(bucket string, maxkeys int, marker, prefix, delimiter string) (*request, error) { + // resourceQuery - get resources properly escaped and lined up before using them in http request + resourceQuery := func() string { + switch { + case marker != "": + marker = fmt.Sprintf("&marker=%s", url.QueryEscape(marker)) + case prefix != "": + prefix = fmt.Sprintf("&prefix=%s", url.QueryEscape(prefix)) + case delimiter != "": + delimiter = fmt.Sprintf("&delimiter=%s", url.QueryEscape(delimiter)) + } + return fmt.Sprintf("?max-keys=%d", maxkeys) + marker + prefix + delimiter + } + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "GET", + HTTPPath: "/" + bucket + resourceQuery(), + } + r, err := newRequest(op, a.config, nil) + if err != nil { + return nil, err + } + return r, nil +} + +/// Bucket Read Operations + +// listObjects - (List Objects) - List some or all (up to 1000) of the objects in a bucket. +// +// You can use the request parameters as selection criteria to return a subset of the objects in a bucket. +// request paramters :- +// --------- +// ?marker - Specifies the key to start with when listing objects in a bucket. +// ?delimiter - A delimiter is a character you use to group keys. +// ?prefix - Limits the response to keys that begin with the specified prefix. +// ?max-keys - Sets the maximum number of keys returned in the response body. +func (a *lowLevelAPI) listObjects(bucket string, maxkeys int, marker, prefix, delimiter string) (*listBucketResult, error) { + req, err := a.listObjectsRequest(bucket, maxkeys, marker, prefix, delimiter) + if err != nil { + return nil, err + } + resp, err := req.Do() + if err != nil { + return nil, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return nil, responseToError(resp) + } + } + listBucketResult := new(listBucketResult) + decoder := xml.NewDecoder(resp.Body) + err = decoder.Decode(listBucketResult) + if err != nil { + return nil, err + } + + // close body while returning, along with any error + return listBucketResult, resp.Body.Close() +} + +func (a *lowLevelAPI) headBucketRequest(bucket string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "HEAD", + HTTPPath: "/" + bucket, + } + return newRequest(op, a.config, nil) +} + +// headBucket - useful to determine if a bucket exists and you have permission to access it. +func (a *lowLevelAPI) headBucket(bucket string) error { + req, err := a.headBucketRequest(bucket) + if err != nil { + return err + } + resp, err := req.Do() + if err != nil { + return err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + // Head has no response body, handle it + return fmt.Errorf("%s", resp.Status) + } + } + return resp.Body.Close() +} + +// deleteBucketRequest wrapper creates a new DeleteBucket request +func (a *lowLevelAPI) deleteBucketRequest(bucket string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "DELETE", + HTTPPath: "/" + bucket, + } + return newRequest(op, a.config, nil) +} + +// deleteBucket - deletes the bucket named in the URI +// NOTE: - +// All objects (including all object versions and delete markers) +// in the bucket must be deleted before successfully attempting this request +func (a *lowLevelAPI) deleteBucket(bucket string) error { + req, err := a.deleteBucketRequest(bucket) + if err != nil { + return err + } + resp, err := req.Do() + if err != nil { + return err + } + return resp.Body.Close() +} + +/// Object Read/Write/Stat Operations + +// putObjectRequest wrapper creates a new PutObject request +func (a *lowLevelAPI) putObjectRequest(bucket, object string, size int64, body io.ReadSeeker) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "PUT", + HTTPPath: "/" + bucket + "/" + object, + } + md5SumBytes, err := sumMD5Reader(body, size) + if err != nil { + return nil, err + } + r, err := newRequest(op, a.config, body) + if err != nil { + return nil, err + } + // set Content-MD5 as base64 encoded md5 + r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes)) + r.req.ContentLength = size + return r, nil +} + +// putObject - add an object to a bucket +// +// You must have WRITE permissions on a bucket to add an object to it. +func (a *lowLevelAPI) putObject(bucket, object string, size int64, body io.ReadSeeker) error { + req, err := a.putObjectRequest(bucket, object, size, body) + if err != nil { + return err + } + resp, err := req.Do() + if err != nil { + return err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return responseToError(resp) + } + } + return resp.Body.Close() +} + +// getObjectRequest wrapper creates a new GetObject request +func (a *lowLevelAPI) getObjectRequest(bucket, object string, offset, length uint64) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "GET", + HTTPPath: "/" + bucket + "/" + object, + } + r, err := newRequest(op, a.config, nil) + if err != nil { + return nil, err + } + // TODO - fix this to support full - http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html + switch { + case length > 0: + r.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) + default: + r.Set("Range", fmt.Sprintf("bytes=%d-", offset)) + } + return r, nil +} + +// getObject - retrieve object from Object Storage +// +// Additionally it also takes range arguments to download the specified range bytes of an object. +// For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. +func (a *lowLevelAPI) getObject(bucket, object string, offset, length uint64) (io.ReadCloser, *ObjectMetadata, error) { + req, err := a.getObjectRequest(bucket, object, offset, length) + if err != nil { + return nil, nil, err + } + resp, err := req.Do() + if err != nil { + return nil, nil, err + } + if resp != nil { + switch resp.StatusCode { + case http.StatusOK: + case http.StatusPartialContent: + default: + return nil, nil, responseToError(resp) + } + } + md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes + if md5sum == "" { + return nil, nil, errors.New("missing ETag") + } + date, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified")) + if err != nil { + return nil, nil, err + } + objectmetadata := new(ObjectMetadata) + objectmetadata.ETag = md5sum + objectmetadata.Key = object + objectmetadata.Size = resp.ContentLength + objectmetadata.LastModified = date + + // do not close body here, caller will close + return resp.Body, objectmetadata, nil +} + +// headObjectRequest wrapper creates a new HeadObject request +func (a *lowLevelAPI) headObjectRequest(bucket, object string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "HEAD", + HTTPPath: "/" + bucket + "/" + object, + } + return newRequest(op, a.config, nil) +} + +// headObject - retrieves metadata from an object without returning the object itself +func (a *lowLevelAPI) headObject(bucket, object string) (*ObjectMetadata, error) { + req, err := a.headObjectRequest(bucket, object) + if err != nil { + return nil, err + } + resp, err := req.Do() + if err != nil { + return nil, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return nil, responseToError(resp) + } + } + md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes + if md5sum == "" { + return nil, errors.New("missing ETag") + } + size, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64) + if err != nil { + return nil, err + } + date, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified")) + if err != nil { + return nil, err + } + objectmetadata := new(ObjectMetadata) + objectmetadata.ETag = md5sum + objectmetadata.Key = object + objectmetadata.Size = size + objectmetadata.LastModified = date + return objectmetadata, nil +} + +// deleteObjectRequest wrapper creates a new DeleteObject request +func (a *lowLevelAPI) deleteObjectRequest(bucket, object string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "DELETE", + HTTPPath: "/" + bucket + "/" + object, + } + return newRequest(op, a.config, nil) +} + +// deleteObject removes the object +func (a *lowLevelAPI) deleteObject(bucket, object string) error { + req, err := a.deleteObjectRequest(bucket, object) + if err != nil { + return err + } + resp, err := req.Do() + if err != nil { + return err + } + return resp.Body.Close() +} + +/// Service Operations + +// listBucketRequest wrapper creates a new ListBuckets request +func (a *lowLevelAPI) listBucketsRequest() (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "GET", + HTTPPath: "/", + } + return newRequest(op, a.config, nil) +} + +// listBuckets list of all buckets owned by the authenticated sender of the request +func (a *lowLevelAPI) listBuckets() (*listAllMyBucketsResult, error) { + req, err := a.listBucketsRequest() + if err != nil { + return nil, err + } + resp, err := req.Do() + if err != nil { + return nil, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return nil, responseToError(resp) + } + } + listAllMyBucketsResult := new(listAllMyBucketsResult) + decoder := xml.NewDecoder(resp.Body) + err = decoder.Decode(listAllMyBucketsResult) + if err != nil { + return nil, err + } + return listAllMyBucketsResult, resp.Body.Close() +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_common.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_common.go new file mode 100644 index 00000000..8901a8e0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_common.go @@ -0,0 +1,77 @@ +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package objectstorage + +import ( + "crypto/hmac" + "crypto/md5" + "crypto/sha256" + "io" +) + +// sum256Reader calculate sha256 sum for an input reader +func sum256Reader(reader io.ReadSeeker) ([]byte, error) { + h := sha256.New() + var err error + + start, _ := reader.Seek(0, 1) + defer reader.Seek(start, 0) + + for err == nil { + length := 0 + byteBuffer := make([]byte, 1024*1024) + length, err = reader.Read(byteBuffer) + byteBuffer = byteBuffer[0:length] + h.Write(byteBuffer) + } + + if err != io.EOF { + return nil, err + } + + return h.Sum(nil), nil +} + +// sum256 calculate sha256 sum for an input byte array +func sum256(data []byte) []byte { + hash := sha256.New() + hash.Write(data) + return hash.Sum(nil) +} + +// sumHMAC calculate hmac between two input byte array +func sumHMAC(key []byte, data []byte) []byte { + hash := hmac.New(sha256.New, key) + hash.Write(data) + return hash.Sum(nil) +} + +// sumMD5Reader calculate md5 for an input reader of a given size +func sumMD5Reader(body io.ReadSeeker, size int64) ([]byte, error) { + hasher := md5.New() + _, err := io.CopyN(hasher, body, size) + if err != nil { + return nil, err + } + // seek back + _, err = body.Seek(0, 0) + if err != nil { + return nil, err + } + // encode the md5 checksum in base64 + return hasher.Sum(nil), nil +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_definitions.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_definitions.go new file mode 100644 index 00000000..28269280 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_definitions.go @@ -0,0 +1,132 @@ +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package objectstorage + +import "time" + +// listAllMyBucketsResult container for ListBucets response +type listAllMyBucketsResult struct { + // Container for one or more buckets. + Buckets struct { + Bucket []*BucketMetadata + } + Owner owner +} + +// owner container for bucket owner information +type owner struct { + DisplayName string + ID string +} + +// commonPrefix container for prefix response in ListObjects +type commonPrefix struct { + Prefix string +} + +// listBucketResult container for ListObjects response +type listBucketResult struct { + CommonPrefixes []*commonPrefix // A response can contain CommonPrefixes only if you specify a delimiter + Contents []*ObjectMetadata // Metadata about each object returned + Delimiter string + + // Encoding type used to encode object keys in the response. + EncodingType string + + // A flag that indicates whether or not ListObjects returned all of the results + // that satisfied the search criteria. + IsTruncated bool + Marker string + MaxKeys int64 + Name string + + // When response is truncated (the IsTruncated element value in the response + // is true), you can use the key name in this field as marker in the subsequent + // request to get next set of objects. Object storage lists objects in alphabetical + // order Note: This element is returned only if you have delimiter request parameter + // specified. If response does not include the NextMaker and it is truncated, + // you can use the value of the last Key in the response as the marker in the + // subsequent request to get the next set of object keys. + NextMarker string + Prefix string +} + +// initiator container for who initiated multipart upload +type initiator struct { + ID string + DisplayName string +} + +// part container for particular part of an object +type part struct { + PartNumber int + LastModified time.Time `type:"timestamp" timestampFormat:"iso8601"` + ETag string + Size int64 +} + +// listObjectPartsResult container for ListObjectParts response +type listObjectPartsResult struct { + Bucket string + Key string + UploadID string `xml:"UploadId"` + + Initiator initiator + Owner owner + + StorageClass string + PartNumberMarker int + NextPartNumberMarker int + MaxParts int + + // Indicates whether the returned list of parts is truncated. + IsTruncated bool + Part []*part + + EncodingType string +} + +// initiateMultipartUploadResult container for InitiateMultiPartUpload response +type initiateMultipartUploadResult struct { + Bucket string + Key string + UploadID string `xml:"UploadId"` +} + +// completeMultipartUploadResult containe for completed multipart upload response +type completeMultipartUploadResult struct { + Location string + Bucket string + Key string + ETag string +} + +// completePart sub container lists individual part numbers and their md5sum, part of CompleteMultipartUpload +type completePart struct { + PartNumber int + ETag string +} + +// completeMultipartUpload container for completing multipart upload +type completeMultipartUpload struct { + Part []*completePart +} + +// createBucketConfiguration container for bucket configuration +type createBucketConfiguration struct { + Location string `xml:"LocationConstraint"` +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_errors.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_errors.go new file mode 100644 index 00000000..6845ccf2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_errors.go @@ -0,0 +1,58 @@ +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package objectstorage + +import ( + "encoding/xml" + "net/http" +) + +/* **** SAMPLE ERROR RESPONSE **** + + + AccessDenied + Access Denied + /mybucket/myphoto.jpg + F19772218238A85A + GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD + +*/ + +// errorResponse is the type returned by some API operations. +type errorResponse struct { + Code string + Message string + Resource string + RequestID string + HostID string +} + +// responseToError returns a new encoded ErrorResponse structure +func responseToError(res *http.Response) error { + var respError errorResponse + decoder := xml.NewDecoder(res.Body) + err := decoder.Decode(&respError) + if err != nil { + return err + } + return respError +} + +// Error formats HTTP error string +func (e errorResponse) Error() string { + return e.Message +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_multipart_api.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_multipart_api.go new file mode 100644 index 00000000..9d0bae49 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_multipart_api.go @@ -0,0 +1,202 @@ +package objectstorage + +import ( + "bytes" + "encoding/base64" + "encoding/hex" + "encoding/xml" + "fmt" + "io" + "net/http" + "strconv" +) + +// initiateMultipartRequest wrapper creates a new InitiateMultiPart request +func (a *lowLevelAPI) initiateMultipartRequest(bucket, object string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "POST", + HTTPPath: "/" + bucket + "/" + object + "?uploads", + } + return newRequest(op, a.config, nil) +} + +// initiateMultipartUpload initiates a multipart upload and returns an upload ID +func (a *lowLevelAPI) initiateMultipartUpload(bucket, object string) (*initiateMultipartUploadResult, error) { + req, err := a.initiateMultipartRequest(bucket, object) + if err != nil { + return nil, err + } + resp, err := req.Do() + if err != nil { + return nil, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return nil, responseToError(resp) + } + } + initiateMultipartUploadResult := new(initiateMultipartUploadResult) + decoder := xml.NewDecoder(resp.Body) + err = decoder.Decode(initiateMultipartUploadResult) + if err != nil { + return nil, err + } + return initiateMultipartUploadResult, resp.Body.Close() +} + +// completeMultipartUploadRequest wrapper creates a new CompleteMultipartUpload request +func (a *lowLevelAPI) completeMultipartUploadRequest(bucket, object, uploadID string, complete *completeMultipartUpload) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "POST", + HTTPPath: "/" + bucket + "/" + object + "?uploadId=" + uploadID, + } + completeMultipartUploadBytes, err := xml.Marshal(complete) + if err != nil { + return nil, err + } + completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes) + r, err := newRequest(op, a.config, completeMultipartUploadBuffer) + if err != nil { + return nil, err + } + r.req.ContentLength = int64(completeMultipartUploadBuffer.Len()) + return r, nil +} + +// completeMultipartUpload completes a multipart upload by assembling previously uploaded parts. +func (a *lowLevelAPI) completeMultipartUpload(bucket, object, uploadID string, c *completeMultipartUpload) (*completeMultipartUploadResult, error) { + req, err := a.completeMultipartUploadRequest(bucket, object, uploadID, c) + if err != nil { + return nil, err + } + resp, err := req.Do() + if err != nil { + return nil, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return nil, responseToError(resp) + } + } + completeMultipartUploadResult := new(completeMultipartUploadResult) + decoder := xml.NewDecoder(resp.Body) + err = decoder.Decode(completeMultipartUploadResult) + if err != nil { + return nil, err + } + return completeMultipartUploadResult, resp.Body.Close() +} + +// abortMultipartUploadRequest wrapper creates a new AbortMultipartUpload request +func (a *lowLevelAPI) abortMultipartUploadRequest(bucket, object, uploadID string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "DELETE", + HTTPPath: "/" + bucket + "/" + object + "?uploadId=" + uploadID, + } + return newRequest(op, a.config, nil) +} + +// abortMultipartUpload aborts a multipart upload for the given uploadID, all parts are deleted +func (a *lowLevelAPI) abortMultipartUpload(bucket, object, uploadID string) error { + req, err := a.abortMultipartUploadRequest(bucket, object, uploadID) + if err != nil { + return err + } + resp, err := req.Do() + if err != nil { + return err + } + if resp != nil { + if resp.StatusCode != http.StatusNoContent { + // Abort has no response body, handle it + return fmt.Errorf("%s", resp.Status) + } + } + return resp.Body.Close() +} + +// listObjectPartsRequest wrapper creates a new ListObjectParts request +func (a *lowLevelAPI) listObjectPartsRequest(bucket, object, uploadID string) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "GET", + HTTPPath: "/" + bucket + "/" + object + "?uploadId=" + uploadID, + } + return newRequest(op, a.config, nil) +} + +// listObjectParts lists the parts that have been uploaded for a specific multipart upload. +func (a *lowLevelAPI) listObjectParts(bucket, object, uploadID string) (*listObjectPartsResult, error) { + req, err := a.listObjectPartsRequest(bucket, object, uploadID) + if err != nil { + return nil, err + } + resp, err := req.Do() + if err != nil { + return nil, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return nil, responseToError(resp) + } + } + listObjectPartsResult := new(listObjectPartsResult) + decoder := xml.NewDecoder(resp.Body) + err = decoder.Decode(listObjectPartsResult) + if err != nil { + return nil, err + } + return listObjectPartsResult, resp.Body.Close() +} + +// uploadPartRequest wrapper creates a new UploadPart request +func (a *lowLevelAPI) uploadPartRequest(bucket, object, uploadID string, partNumber int, size int64, body io.ReadSeeker) (*request, error) { + op := &operation{ + HTTPServer: a.config.MustGetEndpoint(), + HTTPMethod: "PUT", + HTTPPath: "/" + bucket + "/" + object + "?partNumber=" + strconv.Itoa(partNumber) + "&uploadId=" + uploadID, + } + md5SumBytes, err := sumMD5Reader(body, size) + if err != nil { + return nil, err + } + r, err := newRequest(op, a.config, body) + if err != nil { + return nil, err + } + // set Content-MD5 as base64 encoded md5 + r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes)) + r.req.ContentLength = size + return r, nil +} + +// uploadPart uploads a part in a multipart upload. +func (a *lowLevelAPI) uploadPart(bucket, object, uploadID string, partNumber int, size int64, body io.ReadSeeker) (*completePart, error) { + req, err := a.uploadPartRequest(bucket, object, uploadID, partNumber, size, body) + if err != nil { + return nil, err + } + // get hex encoding for md5sum in base64 + md5SumBytes, err := base64.StdEncoding.DecodeString(req.Get("Content-MD5")) + if err != nil { + return nil, err + } + completePart := new(completePart) + completePart.PartNumber = partNumber + completePart.ETag = "\"" + hex.EncodeToString(md5SumBytes) + "\"" + + // initiate the request + resp, err := req.Do() + if err != nil { + return nil, err + } + if resp != nil { + if resp.StatusCode != http.StatusOK { + return nil, responseToError(resp) + } + } + return completePart, resp.Body.Close() +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_request.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_request.go new file mode 100644 index 00000000..cd1adf6c --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_request.go @@ -0,0 +1,237 @@ +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package objectstorage + +import ( + "bytes" + "encoding/hex" + "io" + "io/ioutil" + "net/http" + "net/url" + "sort" + "strings" + "time" +) + +// operation - rest operation +type operation struct { + HTTPServer string + HTTPMethod string + HTTPPath string +} + +// request - a http request +type request struct { + req *http.Request + config *Config + body io.ReadSeeker +} + +const ( + authHeaderPrefix = "AWS4-HMAC-SHA256" + iso8601Format = "20060102T150405Z" + yyyymmdd = "20060102" +) + +var ignoredHeaders = map[string]bool{ + "Authorization": true, + "Content-Type": true, + "Content-Length": true, + "User-Agent": true, +} + +// newRequest - instantiate a new request +func newRequest(op *operation, config *Config, body io.ReadSeeker) (*request, error) { + // if no method default to POST + method := op.HTTPMethod + if method == "" { + method = "POST" + } + + // parse URL for the combination of HTTPServer + HTTPPath + u, err := url.Parse(op.HTTPServer + op.HTTPPath) + if err != nil { + return nil, err + } + + // get a new HTTP request, for the requested method + req, err := http.NewRequest(method, u.String(), nil) + if err != nil { + return nil, err + } + + // set UserAgent + req.Header.Set("User-Agent", config.UserAgent) + + // set Accept header for response encoding style, if available + if config.AcceptType != "" { + req.Header.Set("Accept", config.AcceptType) + } + + // add body + switch { + case body == nil: + req.Body = nil + default: + req.Body = ioutil.NopCloser(body) + } + + // save for subsequent use + r := new(request) + r.config = config + r.req = req + r.body = body + + return r, nil +} + +// Do - start the request +func (r *request) Do() (resp *http.Response, err error) { + if r.config.AccessKeyID != "" && r.config.SecretAccessKey != "" { + r.SignV4() + } + client := &http.Client{} + if r.config.Transport != nil { + client.Transport = r.config.Transport + } + return client.Do(r.req) +} + +// Set - set additional headers if any +func (r *request) Set(key, value string) { + r.req.Header.Set(key, value) +} + +// Get - get header values +func (r *request) Get(key string) string { + return r.req.Header.Get(key) +} + +// SignV4 the request before Do() (version 4.0) +func (r *request) SignV4() { + t := time.Now().UTC() + // Add date if not present + if date := r.Get("Date"); date == "" { + r.Set("X-Amz-Date", t.Format(iso8601Format)) + } + + hash := func() string { + switch { + case r.body == nil: + return hex.EncodeToString(sum256([]byte{})) + default: + sum256Bytes, _ := sum256Reader(r.body) + return hex.EncodeToString(sum256Bytes) + } + } + bodyDigest := hash() + r.req.Header.Add("X-Amz-Content-Sha256", bodyDigest) + + canonicalHeaders := func() string { + var headers []string + vals := make(map[string][]string) + for k, vv := range r.req.Header { + if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok { + continue // ignored header + } + headers = append(headers, strings.ToLower(k)) + vals[strings.ToLower(k)] = vv + } + headers = append(headers, "host") + sort.Strings(headers) + + var buf bytes.Buffer + for _, k := range headers { + buf.WriteString(k) + buf.WriteByte(':') + switch { + case k == "host": + buf.WriteString(r.req.URL.Host) + fallthrough + default: + for idx, v := range vals[k] { + if idx > 0 { + buf.WriteByte(',') + } + buf.WriteString(v) + } + buf.WriteByte('\n') + } + } + return buf.String() + } + + signedHeaders := func() string { + var headers []string + for k := range r.req.Header { + if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok { + continue // ignored header + } + headers = append(headers, strings.ToLower(k)) + } + headers = append(headers, "host") + sort.Strings(headers) + return strings.Join(headers, ";") + } + + canonicalRequest := func() string { + r.req.URL.RawQuery = strings.Replace(r.req.URL.Query().Encode(), "+", "%20", -1) + canonicalRequest := strings.Join([]string{ + r.req.Method, + r.req.URL.Path, + r.req.URL.RawQuery, + canonicalHeaders(), + signedHeaders(), + bodyDigest, + }, "\n") + return canonicalRequest + } + + scope := strings.Join([]string{ + t.Format(yyyymmdd), + r.config.Region, + "s3", + "aws4_request", + }, "/") + + stringToSign := func() string { + stringToSign := authHeaderPrefix + "\n" + t.Format(iso8601Format) + "\n" + stringToSign = stringToSign + scope + "\n" + stringToSign = stringToSign + hex.EncodeToString(sum256([]byte(canonicalRequest()))) + return stringToSign + } + + signingKey := func() []byte { + secret := r.config.SecretAccessKey + date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd))) + region := sumHMAC(date, []byte(r.config.Region)) + service := sumHMAC(region, []byte("s3")) + signingKey := sumHMAC(service, []byte("aws4_request")) + return signingKey + } + + signature := func() string { + return hex.EncodeToString(sumHMAC(signingKey(), []byte(stringToSign()))) + } + + parts := []string{authHeaderPrefix + " Credential=" + r.config.AccessKeyID + "/" + scope, + "SignedHeaders=" + signedHeaders(), "Signature=" + signature(), + } + auth := strings.Join(parts, ", ") + r.Set("Authorization", auth) +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_test.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_test.go new file mode 100644 index 00000000..20dbcf06 --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/low_level_test.go @@ -0,0 +1,53 @@ +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package objectstorage_test + +import ( + "fmt" + "net/http" + "net/http/httptest" + "testing" +) + +var robotsTxtHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Last-Modified", "sometime") + fmt.Fprintf(w, "User-agent: go\nDisallow: /something/") +}) + +func TestNewRequest(t *testing.T) { +} + +func TestResponseToError(t *testing.T) { +} + +func TestCommonFunctions(t *testing.T) { +} + +func TestLowLevelBucketOperations(t *testing.T) { + ts := httptest.NewServer(robotsTxtHandler) + defer ts.Close() +} + +func TestLowLevelObjectOperations(t *testing.T) { + ts := httptest.NewServer(robotsTxtHandler) + defer ts.Close() +} + +func TestLowLevelMultiPartOperations(t *testing.T) { + ts := httptest.NewServer(robotsTxtHandler) + defer ts.Close() +} diff --git a/Godeps/_workspace/src/github.com/minio/objectstorage-go/multipart.go b/Godeps/_workspace/src/github.com/minio/objectstorage-go/multipart.go new file mode 100644 index 00000000..2c964c1b --- /dev/null +++ b/Godeps/_workspace/src/github.com/minio/objectstorage-go/multipart.go @@ -0,0 +1,97 @@ +/* + * Minimal object storage library (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package objectstorage + +import ( + "bytes" + "io" +) + +// Part - message structure for results from the MultiPart +type Part struct { + Data io.ReadSeeker + Err error + Len int64 + Num int // part number +} + +// MultiPart reads from io.Reader, partitions the data into chunks of given chunksize, and sends +// each chunk as io.ReadSeeker to the caller over a channel +// +// This method runs until an EOF or error occurs. If an error occurs, +// the method sends the error over the channel and returns. +// Before returning, the channel is always closed. +func MultiPart(reader io.Reader, chunkSize uint64) <-chan Part { + ch := make(chan Part) + go multiPartInRoutine(reader, chunkSize, ch) + return ch +} + +func multiPartInRoutine(reader io.Reader, chunkSize uint64, ch chan Part) { + defer close(ch) + part := make([]byte, chunkSize) + n, err := io.ReadFull(reader, part) + if err == io.EOF || err == io.ErrUnexpectedEOF { // short read, only single part return + ch <- Part{ + Data: bytes.NewReader(part[0:n]), + Err: nil, + Len: int64(n), + Num: 1, + } + return + } + // catastrophic error send error and return + if err != nil { + ch <- Part{ + Data: nil, + Err: err, + Num: 0, + } + return + } + // send the first part + var num = 1 + ch <- Part{ + Data: bytes.NewReader(part), + Err: nil, + Len: int64(n), + Num: num, + } + for err == nil { + var n int + part := make([]byte, chunkSize) + n, err = io.ReadFull(reader, part) + if err != nil { + if err != io.EOF && err != io.ErrUnexpectedEOF { // catastrophic error + ch <- Part{ + Data: nil, + Err: err, + Num: 0, + } + return + } + } + num++ + ch <- Part{ + Data: bytes.NewReader(part[0:n]), + Err: nil, + Len: int64(n), + Num: num, + } + + } +} diff --git a/cmd-cat.go b/cmd-cat.go index 5d9cdce0..bcbb0a06 100644 --- a/cmd-cat.go +++ b/cmd-cat.go @@ -80,7 +80,7 @@ func doCatCmd(sourceURLConfigMap map[string]*hostConfig, debug bool) (string, er defer reader.Close() hasher := md5.New() mw := io.MultiWriter(os.Stdout, hasher) - _, err = io.CopyN(mw, reader, size) + _, err = io.CopyN(mw, reader, int64(size)) if err != nil { switch e := iodine.ToError(err).(type) { case *os.PathError: diff --git a/cmd-common.go b/cmd-common.go index 7018c145..5d756d82 100644 --- a/cmd-common.go +++ b/cmd-common.go @@ -48,7 +48,7 @@ func isValidRetry(err error) bool { // StartBar -- instantiate a progressbar func startBar(size int64) *pb.ProgressBar { - bar := pb.New(int(size)) + bar := pb.New64(size) bar.SetUnits(pb.U_BYTES) bar.SetRefreshRate(time.Millisecond * 10) bar.NotPrint = true diff --git a/common-methods.go b/common-methods.go index a9b81bf8..20c915c0 100644 --- a/common-methods.go +++ b/common-methods.go @@ -27,19 +27,16 @@ import ( ) // getSourceReader - -func getSourceReader(sourceURL string, sourceConfig *hostConfig) (reader io.ReadCloser, length int64, md5hex string, err error) { +func getSourceReader(sourceURL string, sourceConfig *hostConfig) (reader io.ReadCloser, length uint64, md5hex string, err error) { sourceClnt, err := getNewClient(sourceURL, sourceConfig, globalDebugFlag) if err != nil { return nil, 0, "", iodine.New(err, map[string]string{"failedURL": sourceURL}) } - if _, err := sourceClnt.Stat(); err != nil { - return nil, 0, "", iodine.New(err, map[string]string{"failedURL": sourceURL}) - } return sourceClnt.GetObject(0, 0) } // getTargetWriter - -func getTargetWriter(targetURL string, targetConfig *hostConfig, md5hex string, length int64) (io.WriteCloser, error) { +func getTargetWriter(targetURL string, targetConfig *hostConfig, md5hex string, length uint64) (io.WriteCloser, error) { targetClnt, err := getNewClient(targetURL, targetConfig, globalDebugFlag) if err != nil { return nil, iodine.New(err, nil) diff --git a/cp-methods.go b/cp-methods.go index 1e9cf8e2..1e1c4fe5 100644 --- a/cp-methods.go +++ b/cp-methods.go @@ -24,7 +24,7 @@ import ( type sourceReader struct { reader io.ReadCloser - length int64 + length uint64 md5hex string } diff --git a/cp.go b/cp.go index c6492ce8..eece61af 100644 --- a/cp.go +++ b/cp.go @@ -27,7 +27,7 @@ import ( /// mc cp - related internal functions // doCopy -func doCopy(reader io.ReadCloser, md5hex string, length int64, targetURL string, targetConfig *hostConfig) error { +func doCopy(reader io.ReadCloser, md5hex string, length uint64, targetURL string, targetConfig *hostConfig) error { writeCloser, err := getTargetWriter(targetURL, targetConfig, md5hex, length) if err != nil { return iodine.New(err, nil) @@ -37,14 +37,14 @@ func doCopy(reader io.ReadCloser, md5hex string, length int64, targetURL string, // set up progress bar var bar *pb.ProgressBar if !globalQuietFlag { - bar = startBar(length) + bar = startBar(int64(length)) bar.Start() writers = append(writers, bar) } // write progress bar multiWriter := io.MultiWriter(writers...) // copy data to writers - _, copyErr := io.CopyN(multiWriter, reader, length) + _, copyErr := io.CopyN(multiWriter, reader, int64(length)) // close to see the error, verify it later err = writeCloser.Close() if copyErr != nil { diff --git a/pkg/client/client.go b/pkg/client/client.go index e8ac5592..2b11f419 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -34,8 +34,8 @@ type Client interface { SetBucketACL(acl string) error // Object operations - GetObject(offset, length int64) (body io.ReadCloser, size int64, md5 string, err error) - CreateObject(md5 string, size int64) (io.WriteCloser, error) + GetObject(offset, length uint64) (body io.ReadCloser, size uint64, md5 string, err error) + CreateObject(md5 string, size uint64) (io.WriteCloser, error) } // ContentOnChannel - List contents on channel diff --git a/pkg/client/errors.go b/pkg/client/errors.go index 5bac0559..85ad4fc1 100644 --- a/pkg/client/errors.go +++ b/pkg/client/errors.go @@ -50,9 +50,9 @@ func (e InvalidArgument) Error() string { // InvalidRange - invalid range requested type InvalidRange struct { - Offset int64 + Offset uint64 } func (e InvalidRange) Error() string { - return "invalid range offset: " + strconv.FormatInt(e.Offset, 10) + return "invalid range offset: " + strconv.FormatUint(e.Offset, 10) } diff --git a/pkg/client/fs/fs.go b/pkg/client/fs/fs.go index c95fa9ab..51dae855 100644 --- a/pkg/client/fs/fs.go +++ b/pkg/client/fs/fs.go @@ -57,7 +57,7 @@ func (f *fsClient) fsStat() (os.FileInfo, error) { return st, nil } -func (f *fsClient) get(content *client.Content) (io.ReadCloser, int64, string, error) { +func (f *fsClient) get(content *client.Content) (io.ReadCloser, uint64, string, error) { body, err := os.Open(f.path) if err != nil { return nil, 0, "", iodine.New(err, nil) @@ -74,14 +74,11 @@ func (f *fsClient) get(content *client.Content) (io.ReadCloser, int64, string, e return nil, 0, "", iodine.New(err, nil) } md5Str := hex.EncodeToString(h.Sum(nil)) - return body, content.Size, md5Str, nil + return body, uint64(content.Size), md5Str, nil } // GetObject download an full or part object from bucket -func (f *fsClient) GetObject(offset, length int64) (io.ReadCloser, int64, string, error) { - if offset < 0 { - return nil, 0, "", iodine.New(client.InvalidRange{Offset: offset}, nil) - } +func (f *fsClient) GetObject(offset, length uint64) (io.ReadCloser, uint64, string, error) { content, err := f.getFSMetadata() if err != nil { return nil, 0, "", iodine.New(err, nil) @@ -89,7 +86,7 @@ func (f *fsClient) GetObject(offset, length int64) (io.ReadCloser, int64, string if content.FileType.IsDir() { return nil, 0, "", iodine.New(ISFolder{path: f.path}, nil) } - if offset > content.Size || (offset+length-1) > content.Size { + if int64(offset) > content.Size || int64(offset+length-1) > content.Size { return nil, 0, "", iodine.New(client.InvalidRange{Offset: offset}, nil) } if offset == 0 && length == 0 { @@ -99,7 +96,7 @@ func (f *fsClient) GetObject(offset, length int64) (io.ReadCloser, int64, string if err != nil { return nil, 0, "", iodine.New(err, nil) } - _, err = io.CopyN(ioutil.Discard, body, offset) + _, err = io.CopyN(ioutil.Discard, body, int64(offset)) if err != nil { return nil, 0, "", iodine.New(err, nil) } diff --git a/pkg/client/fs/fs_put.go b/pkg/client/fs/fs_put.go index cc10521a..772f5767 100644 --- a/pkg/client/fs/fs_put.go +++ b/pkg/client/fs/fs_put.go @@ -30,17 +30,11 @@ import ( ) // CreateObject - upload new object to bucket -func (f *fsClient) CreateObject(md5HexString string, size int64) (io.WriteCloser, error) { +func (f *fsClient) CreateObject(md5HexString string, size uint64) (io.WriteCloser, error) { r, w := io.Pipe() blockingWriter := client.NewBlockingWriteCloser(w) go func() { // handle md5HexString match internally - if size < 0 { - err := iodine.New(client.InvalidArgument{Err: errors.New("invalid argument")}, nil) - r.CloseWithError(err) - blockingWriter.Release(err) - return - } objectDir, _ := filepath.Split(f.path) objectPath := f.path if objectDir != "" { @@ -62,7 +56,7 @@ func (f *fsClient) CreateObject(md5HexString string, size int64) (io.WriteCloser h := md5.New() mw := io.MultiWriter(fs, h) - _, err = io.CopyN(mw, r, size) + _, err = io.CopyN(mw, r, int64(size)) if err != nil { err := iodine.New(err, nil) r.CloseWithError(err) diff --git a/pkg/client/s3/.gitignore b/pkg/client/s3/.gitignore deleted file mode 100644 index d852bed5..00000000 --- a/pkg/client/s3/.gitignore +++ /dev/null @@ -1 +0,0 @@ -rootkey.csv \ No newline at end of file diff --git a/pkg/client/s3/LICENSE.GOOGLE b/pkg/client/s3/LICENSE.GOOGLE deleted file mode 100644 index 96188b24..00000000 --- a/pkg/client/s3/LICENSE.GOOGLE +++ /dev/null @@ -1,20 +0,0 @@ -This source was originally based on the following license, but the code -has diverged much and improved upon. - -Keeping this LICENSE here for historical reasons - -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ diff --git a/pkg/client/s3/auth.go b/pkg/client/s3/auth.go deleted file mode 100644 index e2089baf..00000000 --- a/pkg/client/s3/auth.go +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "bytes" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "sort" - "strings" - "time" - - "crypto/hmac" - "crypto/sha1" - "crypto/tls" - "encoding/base64" -) - -func (a *s3Client) loadKeys(cert string, key string) (*TLSConfig, error) { - certBlock, err := ioutil.ReadFile(cert) - if err != nil { - return nil, err - } - keyBlock, err := ioutil.ReadFile(key) - if err != nil { - return nil, err - } - t := &TLSConfig{} - t.CertPEMBlock = certBlock - t.KeyPEMBlock = keyBlock - return t, nil -} - -func (a *s3Client) getTLSTransport() (*http.Transport, error) { - if a.CertPEM == "" || a.KeyPEM == "" { - return &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, - }, nil - } - - tlsconfig, err := a.loadKeys(a.CertPEM, a.KeyPEM) - if err != nil { - return nil, err - } - var cert tls.Certificate - cert, err = tls.X509KeyPair(tlsconfig.CertPEMBlock, tlsconfig.KeyPEMBlock) - if err != nil { - return nil, err - } - - // Setup HTTPS client - tlsConfig := &tls.Config{ - Certificates: []tls.Certificate{cert}, - InsecureSkipVerify: true, - } - - tlsConfig.BuildNameToCertificate() - transport := &http.Transport{TLSClientConfig: tlsConfig} - return transport, nil -} - -func (a *s3Client) signRequest(req *http.Request, host string) { - hm := hmac.New(sha1.New, []byte(a.SecretAccessKey)) - ss := a.stringToSign(req, host) - //DEBUG - fmt.Printf("String to sign: %q (%x)\n", ss, ss) - hm.Write([]byte(ss)) - - authHeader := new(bytes.Buffer) - fmt.Fprintf(authHeader, "AWS %s:", a.AccessKeyID) - encoder := base64.NewEncoder(base64.StdEncoding, authHeader) - encoder.Write(hm.Sum(nil)) - // do not defer this, close it before passing down encoded authHeader - encoder.Close() - - req.Header.Set("Authorization", authHeader.String()) -} - -// From the Amazon docs: -// -// StringToSign = HTTP-Verb + "\n" + -// Content-MD5 + "\n" + -// Content-Type + "\n" + -// Date + "\n" + -// CanonicalizedAmzHeaders + -// CanonicalizedResource; -func (a *s3Client) stringToSign(req *http.Request, host string) string { - buf := new(bytes.Buffer) - buf.WriteString(req.Method) - buf.WriteByte('\n') - buf.WriteString(req.Header.Get("Content-MD5")) - buf.WriteByte('\n') - buf.WriteString(req.Header.Get("Content-Type")) - buf.WriteByte('\n') - if req.Header.Get("X-Amz-Date") == "" { - buf.WriteString(req.Header.Get("Date")) - } - buf.WriteByte('\n') - a.writeCanonicalizedAmzHeaders(buf, req) - a.writeCanonicalizedResource(buf, req, host) - return buf.String() -} - -func hasPrefixCaseInsensitive(s, pfx string) bool { - if len(pfx) > len(s) { - return false - } - shead := s[:len(pfx)] - if shead == pfx { - return true - } - shead = strings.ToLower(shead) - return shead == pfx || shead == strings.ToLower(pfx) -} - -func (a *s3Client) writeCanonicalizedAmzHeaders(buf *bytes.Buffer, req *http.Request) { - var amzHeaders []string - vals := make(map[string][]string) - for k, vv := range req.Header { - if hasPrefixCaseInsensitive(k, "x-amz-") { - lk := strings.ToLower(k) - amzHeaders = append(amzHeaders, lk) - vals[lk] = vv - } - } - sort.Strings(amzHeaders) - for _, k := range amzHeaders { - buf.WriteString(k) - buf.WriteByte(':') - for idx, v := range vals[k] { - if idx > 0 { - buf.WriteByte(',') - } - if strings.Contains(v, "\n") { - // TODO: "Unfold" long headers that - // span multiple lines (as allowed by - // RFC 2616, section 4.2) by replacing - // the folding white-space (including - // new-line) by a single space. - buf.WriteString(v) - } else { - buf.WriteString(v) - } - } - buf.WriteByte('\n') - } -} - -// Must be sorted: -var subResList = []string{ - "acl", - "location", - "logging", - "notification", - "partNumber", - "policy", - "requestPayment", - "torrent", - "uploadId", - "uploads", - "versionId", - "versioning", - "versions", - "response-content-type", - "response-content-language", - "response-expires", - "response-cache-control", - "response-content-disposition", - "response-content-encoding", - "website", -} - -// From the Amazon docs: -// -// CanonicalizedResource = [ "/" + Bucket ] + -// + -// [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"]; -func (a *s3Client) writeCanonicalizedResource(buf *bytes.Buffer, req *http.Request, host string) { - buf.WriteString(req.URL.Path) - sort.Strings(subResList) - if req.URL.RawQuery != "" { - n := 0 - vals, _ := url.ParseQuery(req.URL.RawQuery) - for _, subres := range subResList { - if vv, ok := vals[subres]; ok && len(vv) > 0 { - n++ - if n == 1 { - buf.WriteByte('?') - } else { - buf.WriteByte('&') - } - buf.WriteString(subres) - if len(vv[0]) > 0 { - buf.WriteByte('=') - buf.WriteString(url.QueryEscape(vv[0])) - } - } - } - } -} diff --git a/pkg/client/s3/auth_test.go b/pkg/client/s3/auth_test.go deleted file mode 100644 index 1ccbd96a..00000000 --- a/pkg/client/s3/auth_test.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "bufio" - "fmt" - "net/http" - "net/url" - "strings" - - . "github.com/minio/check" -) - -type reqAndExpected struct { - req, expected, host string -} - -func req(s string) *http.Request { - req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(s))) - if err != nil { - panic(fmt.Sprintf("bad request in test: %v (error: %v)", req, err)) - } - return req -} - -func (s *MySuite) TestsignRequest(c *C) { - r := req("GET /foo HTTP/1.1\n\n") - config := &Config{ - HostURL: "localhost:9000", - AccessKeyID: "key", - SecretAccessKey: "secretkey", - UserAgent: "Minio/auth_test (mc)", - } - url, _ := url.Parse("localhost:9000") - cl := &s3Client{ - &Meta{ - Config: config, - Transport: http.DefaultTransport, - }, url, - } - r.Header.Set("Date", "Sat, 02 Apr 2011 04:23:52 GMT") - cl.signRequest(r, "localhost:9000") - c.Assert(r.Header.Get("Date"), Not(Equals), "") - cl.signRequest(r, "localhost:9000") - c.Assert(r.Header.Get("Authorization"), Equals, "AWS key:kHpCR/N7Rw3PwRlDd8+5X40CFVc=") -} diff --git a/pkg/client/s3/bucket.go b/pkg/client/s3/bucket.go deleted file mode 100644 index 2680f495..00000000 --- a/pkg/client/s3/bucket.go +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "fmt" - - "net/http" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" -) - -func isValidBucketACL(acl string) bool { - switch acl { - case "private": - fallthrough - case "public-read": - fallthrough - case "public-read-write": - fallthrough - case "authenticated-read": - return true - default: - return false - } -} - -/// Bucket API operations - -// CreateBucket - create a new bucket -func (c *s3Client) CreateBucket() error { - _, object := c.url2BucketAndObject() - if object != "" { - return iodine.New(InvalidQueryURL{URL: ""}, nil) - } - requestURL, err := c.getRequestURL() - if err != nil { - return iodine.New(err, nil) - } - // new request - req, err := c.newRequest("PUT", requestURL, nil) - if err != nil { - return iodine.New(err, nil) - } - // by default while creating a bucket make it default "private" - req.Header.Add("x-amz-acl", "private") - - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - c.signRequest(req, c.Host) - } - res, err := c.Transport.RoundTrip(req) - if err != nil { - return iodine.New(err, nil) - } - if res != nil { - if res.StatusCode != http.StatusOK { - return iodine.New(ResponseToError(res), nil) - } - } - defer res.Body.Close() - return nil -} - -// SetBucketACL add canned acl's on a bucket -func (c *s3Client) SetBucketACL(acl string) error { - if !isValidBucketACL(acl) { - return iodine.New(InvalidACL{ACL: acl}, nil) - } - _, object := c.url2BucketAndObject() - if object != "" { - return iodine.New(InvalidQueryURL{URL: ""}, nil) - } - requestURL, err := c.getRequestURL() - if err != nil { - return iodine.New(err, nil) - } - - // new request - u := fmt.Sprintf("%s?acl", requestURL) - req, err := c.newRequest("PUT", u, nil) - if err != nil { - return iodine.New(err, nil) - } - - // by default without acl while creating a bucket - // make it default "private" - req.Header.Add("x-amz-acl", acl) - - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - c.signRequest(req, c.Host) - } - - res, err := c.Transport.RoundTrip(req) - if err != nil { - return iodine.New(err, nil) - } - if res != nil { - if res.StatusCode != http.StatusOK { - return iodine.New(ResponseToError(res), nil) - } - } - defer res.Body.Close() - return nil -} - -// Stat - send a 'HEAD' on a bucket or object to get its metadata -func (c *s3Client) Stat() (*client.Content, error) { - bucket, object := c.url2BucketAndObject() - return c.getMetadata(bucket, object) -} diff --git a/pkg/client/s3/bucket_object_metadata.go b/pkg/client/s3/bucket_object_metadata.go deleted file mode 100644 index 6c248504..00000000 --- a/pkg/client/s3/bucket_object_metadata.go +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "net/http" - "os" - "strconv" - "time" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" -) - -func (c *s3Client) getMetadata(bucket, object string) (content *client.Content, err error) { - if object == "" { - return c.getBucketMetadata(bucket) - } - return c.getObjectMetadata(bucket, object) -} - -func (c *s3Client) getBucketMetadata(bucket string) (content *client.Content, err error) { - queryURL, err := c.getRequestURL() - if err != nil { - return nil, iodine.New(err, nil) - } - if !c.isValidQueryURL(queryURL) { - return nil, iodine.New(InvalidQueryURL{URL: queryURL}, nil) - } - req, err := c.newRequest("HEAD", queryURL, nil) - if err != nil { - return nil, iodine.New(err, nil) - } - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - c.signRequest(req, c.Host) - } - res, err := c.Transport.RoundTrip(req) - if err != nil { - return nil, iodine.New(err, nil) - } - content = new(client.Content) - content.Name = bucket - content.FileType = os.ModeDir - - defer res.Body.Close() - switch res.StatusCode { - case http.StatusOK: - fallthrough - case http.StatusMovedPermanently: - return content, nil - default: - return nil, iodine.New(ResponseToError(res), nil) - } -} - -// getObjectMetadata - returns nil, os.ErrNotExist if not on object storage -func (c *s3Client) getObjectMetadata(bucket, object string) (content *client.Content, err error) { - queryURL, err := c.getRequestURL() - if err != nil { - return nil, iodine.New(err, nil) - } - if !c.isValidQueryURL(queryURL) { - return nil, iodine.New(InvalidQueryURL{URL: queryURL}, nil) - } - req, err := c.newRequest("HEAD", queryURL, nil) - if err != nil { - return nil, iodine.New(err, nil) - } - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - c.signRequest(req, c.Host) - } - res, err := c.Transport.RoundTrip(req) - if err != nil { - return nil, iodine.New(err, nil) - } - defer res.Body.Close() - switch res.StatusCode { - case http.StatusNotFound: - return nil, iodine.New(ObjectNotFound{Bucket: bucket, Object: object}, nil) - case http.StatusOK: - // verify for Content-Length - contentLength, err := strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64) - if err != nil { - return nil, iodine.New(err, nil) - } - // AWS S3 uses RFC1123 standard for Date in HTTP header - date, err := time.Parse(time.RFC1123, res.Header.Get("Last-Modified")) - if err != nil { - return nil, iodine.New(err, nil) - } - content = new(client.Content) - content.Name = object - content.Time = date - content.Size = contentLength - content.FileType = 0 - return content, nil - default: - return nil, iodine.New(ResponseToError(res), nil) - } -} diff --git a/pkg/client/s3/bucket_routines.go b/pkg/client/s3/bucket_routines.go deleted file mode 100644 index 7902e619..00000000 --- a/pkg/client/s3/bucket_routines.go +++ /dev/null @@ -1,342 +0,0 @@ -/* -1;3803;0c * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -package s3 - -import ( - "bytes" - "encoding/xml" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "os" - "strings" - "time" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" -) - -func (c *s3Client) listInGoRoutine(contentCh chan client.ContentOnChannel) { - defer close(contentCh) - var contents []*client.Content - bucket, objectPrefix := c.url2BucketAndObject() - content, err := c.getObjectMetadata(bucket, objectPrefix) - switch err { - case nil: // List a single object. Exact key - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - default: - if bucket == "" { - contents, err = c.listBuckets() - if err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: iodine.New(err, nil), - } - return - } - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - return - } - // List all objects matching the key prefix - contents, marker, err := c.listObjects(bucket, "", objectPrefix, "/", globalMaxKeys) - if err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: iodine.New(err, nil), - } - return - } - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - // take marker and loop through - if marker != nil { - for marker.istruncated { - contents, marker, err = c.listObjects(bucket, marker.nextMarker, objectPrefix, "/", globalMaxKeys) - if err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: iodine.New(err, nil), - } - return - } - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - } - } - } -} - -func (c *s3Client) listRecursiveInGoRoutine(contentCh chan client.ContentOnChannel) { - defer close(contentCh) - var contents []*client.Content - bucket, objectPrefix := c.url2BucketAndObject() - content, err := c.getObjectMetadata(bucket, objectPrefix) - switch err { - case nil: // List a single object. Exact key - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - default: - if bucket == "" { - contents, err = c.listBuckets() - if err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: iodine.New(err, nil), - } - return - } - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - return - } - // List all objects matching the key prefix - contents, marker, err := c.listObjects(bucket, "", objectPrefix, "", globalMaxKeys) - if err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: iodine.New(err, nil), - } - return - } - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - // take marker and loop through - if marker != nil { - for marker.istruncated { - contents, marker, err = c.listObjects(bucket, marker.nextMarker, objectPrefix, "", globalMaxKeys) - if err != nil { - contentCh <- client.ContentOnChannel{ - Content: nil, - Err: iodine.New(err, nil), - } - return - } - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - } - } - } -} - -// populate s3 response and decode results into listBucketResults{} -func (c *s3Client) decodeBucketResults(queryURL string) (*listBucketResults, error) { - if !c.isValidQueryURL(queryURL) { - return nil, iodine.New(InvalidQueryURL{URL: queryURL}, nil) - } - bres := &listBucketResults{} - req, err := c.newRequest("GET", queryURL, nil) - if err != nil { - return nil, iodine.New(err, nil) - } - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - c.signRequest(req, c.Host) - } - res, err := c.Transport.RoundTrip(req) - if err != nil { - return nil, iodine.New(err, nil) - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return nil, iodine.New(ResponseToError(res), nil) - } - var logbuf bytes.Buffer - err = xml.NewDecoder(io.TeeReader(res.Body, &logbuf)).Decode(bres) - if err != nil { - return nil, iodine.New(err, map[string]string{"XMLError": logbuf.String()}) - } - return bres, nil -} - -// filter contents out of content and provide marker for future request -func (c *s3Client) filterContents(startAt, marker, prefix, delimiter string, cts []*content) ([]*client.Content, string, error) { - var contents []*client.Content - var nextMarker string - for _, ct := range cts { - if ct.Key == marker && ct.Key != startAt { - // Skip first dup on pages 2 and higher. - continue - } - if ct.Key < startAt { - msg := fmt.Sprintf("Unexpected response from Amazon: content key %q but wanted greater than %q", ct.Key, startAt) - return nil, marker, iodine.New(client.UnexpectedError{Err: errors.New(msg)}, nil) - } - content := new(client.Content) - content.Name = ct.Key - content.Time = ct.LastModified - content.Size = ct.Size - content.FileType = 0 - contents = append(contents, content) - nextMarker = ct.Key - } - return contents, nextMarker, nil -} - -// Populare query URL for Listobjects requests -func (c *s3Client) getQueryURL(bucket, marker, prefix, delimiter string, fetchN int) string { - queryURL := c.getBucketRequestURL(bucket) + fmt.Sprintf("?max-keys=%d", fetchN) - switch true { - case marker != "": - queryURL = queryURL + fmt.Sprintf("&marker=%s", url.QueryEscape(marker)) - fallthrough - case prefix != "": - queryURL = queryURL + fmt.Sprintf("&prefix=%s", url.QueryEscape(prefix)) - fallthrough - case delimiter != "": - queryURL = queryURL + fmt.Sprintf("&delimiter=%s", url.QueryEscape(delimiter)) - } - return queryURL -} - -type nextMarker struct { - nextMarker string - istruncated bool -} - -// listObjects returns 0 to maxKeys (inclusive) contents from the -// provided bucket. Keys before startAt will be skipped. (This is the S3 -// 'marker' value). If the length of the returned contents is equal to -// maxKeys, there is no indication whether or not the returned list is truncated. -func (c *s3Client) listObjects(bucket, startAt, prefix, delimiter string, maxKeys int) (contents []*client.Content, m *nextMarker, err error) { - if maxKeys <= 0 { - return nil, nil, iodine.New(InvalidMaxKeys{MaxKeys: maxKeys}, nil) - } - marker := startAt - m = new(nextMarker) - for len(contents) < maxKeys { - fetchN := maxKeys - len(contents) - if fetchN > globalMaxKeys { - fetchN = globalMaxKeys - } - bres, err := c.decodeBucketResults(c.getQueryURL(bucket, marker, prefix, delimiter, fetchN)) - if err != nil { - return nil, nil, iodine.New(err, nil) - } - if bres.MaxKeys != fetchN || bres.Name != bucket || bres.Marker != marker { - msg := fmt.Sprintf("Unexpected parse from server: %#v", bres) - return nil, nil, iodine.New(client.UnexpectedError{Err: errors.New(msg)}, nil) - } - contents, marker, err = c.filterContents(startAt, marker, prefix, delimiter, bres.Contents) - if err != nil { - return nil, nil, iodine.New(err, nil) - } - for _, prefix := range bres.CommonPrefixes { - content := &client.Content{ - Name: prefix.Prefix, - // TODO no way of fixiing this as of now - Time: time.Now(), - Size: 0, - FileType: os.ModeDir, - } - contents = append(contents, content) - } - m.istruncated = bres.IsTruncated - m.nextMarker = marker - if !m.istruncated { - break - } - } - return contents, m, nil -} - -// Get list of buckets -func (c *s3Client) listBuckets() ([]*client.Content, error) { - requestURL, err := c.getRequestURL() - if err != nil { - return nil, iodine.New(err, nil) - } - req, err := c.newRequest("GET", requestURL, nil) - if err != nil { - return nil, iodine.New(err, nil) - } - // do not ignore signatures for 'listBuckets()' it is never a public request for amazon s3 - // so lets aggressively verify - if strings.Contains(c.Host, "amazonaws.com") && (c.AccessKeyID == "" || c.SecretAccessKey == "") { - msg := "Authorization key cannot be empty for listing buckets, please choose a valid bucketname if its a public request" - return nil, iodine.New(errors.New(msg), nil) - } - // rest we can ignore - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - c.signRequest(req, c.Host) - } - res, err := c.Transport.RoundTrip(req) - if err != nil { - return nil, iodine.New(err, nil) - } - if res != nil { - if res.StatusCode != http.StatusOK { - return nil, iodine.New(ResponseToError(res), nil) - } - } - defer res.Body.Close() - - type bucket struct { - Name string - CreationDate time.Time - } - type allMyBuckets struct { - Buckets struct { - Bucket []*bucket - } - } - var buckets allMyBuckets - if err := xml.NewDecoder(res.Body).Decode(&buckets); err != nil { - return nil, iodine.New(client.UnexpectedError{ - Err: errors.New("Malformed response received from server")}, - map[string]string{"XMLError": err.Error()}) - } - var contents []*client.Content - for _, b := range buckets.Buckets.Bucket { - content := new(client.Content) - content.Name = b.Name - content.Time = b.CreationDate - content.FileType = os.ModeDir - contents = append(contents, content) - } - return contents, nil -} diff --git a/pkg/client/s3/client_test.go b/pkg/client/s3/client_test.go deleted file mode 100644 index 2072de44..00000000 --- a/pkg/client/s3/client_test.go +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "encoding/xml" - "errors" - "io" - "io/ioutil" - "net/http" - "strings" - "testing" - "time" - - . "github.com/minio/check" - "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" -) - -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - -func listAllMyBuckets(r io.Reader) ([]*client.Content, error) { - type bucket struct { - Name string - CreationDate time.Time - } - type allMyBuckets struct { - Buckets struct { - Bucket []*bucket - } - } - - var buckets allMyBuckets - if err := xml.NewDecoder(r).Decode(&buckets); err != nil { - return nil, iodine.New(client.UnexpectedError{Err: errors.New("Malformed response received from server")}, - map[string]string{"XMLError": err.Error()}) - } - var contents []*client.Content - for _, b := range buckets.Buckets.Bucket { - content := new(client.Content) - content.Name = b.Name - content.Time = b.CreationDate - contents = append(contents, content) - } - return contents, nil -} - -func (s *MySuite) TestConfig(c *C) { - conf := new(Config) - conf.AccessKeyID = "" - conf.SecretAccessKey = "" - conf.HostURL = "http://example.com/bucket1" - conf.UserAgent = "Minio" - clnt := New(conf) - c.Assert(clnt, Not(IsNil)) -} - -func (s *MySuite) TestBucketACL(c *C) { - m := []struct { - in string - want bool - }{ - {"private", true}, - {"public-read", true}, - {"public-read-write", true}, - {"authenticated-read", true}, - {"", false}, - {"readonly", false}, - {"invalid", false}, - } - for _, bt := range m { - got := isValidBucketACL(bt.in) - c.Assert(got, Equals, bt.want) - } -} - -func (s *MySuite) TestError(c *C) { - res := "\nAccessDeniedAccess Denied/mybucket/myphoto.jpgF19772218238A85AGuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD" - response := new(http.Response) - response.Body = ioutil.NopCloser(strings.NewReader(res)) - err := ResponseToError(response) - c.Assert(err, Not(IsNil)) - c.Assert(err.Error(), Equals, "Access Denied") -} - -func (s *MySuite) TestParseBuckets(c *C) { - res := "\nownerIDFieldbobDisplayNamebucketOne2006-06-21T07:04:31.000ZbucketTwo2006-06-21T07:04:32.000Z" - buckets, err := listAllMyBuckets(strings.NewReader(res)) - c.Assert(err, IsNil) - c.Assert(len(buckets), Equals, 2) - - t1, err := time.Parse(time.RFC3339, "2006-06-21T07:04:31.000Z") - t2, err := time.Parse(time.RFC3339, "2006-06-21T07:04:32.000Z") - want := []*client.Content{ - {Name: "bucketOne", Time: t1}, - {Name: "bucketTwo", Time: t2}, - } - c.Assert(buckets, DeepEquals, want) -} - -func (s *MySuite) TestParseBucketsFail(c *C) { - res := "\nownerIDFieldbobDisplayNamebucketOne2006-06-21T07:04:31.000ZbucketTwo2006-06-21T07:04:32.000Z// - // - http://./ - *url.URL -} diff --git a/pkg/client/s3/doc.go b/pkg/client/s3/doc.go deleted file mode 100644 index 3ed7f972..00000000 --- a/pkg/client/s3/doc.go +++ /dev/null @@ -1 +0,0 @@ -package s3 diff --git a/pkg/client/s3/errors.go b/pkg/client/s3/errors.go index 56ee6fa3..3a2a1764 100644 --- a/pkg/client/s3/errors.go +++ b/pkg/client/s3/errors.go @@ -16,20 +16,7 @@ package s3 -import ( - "encoding/xml" - "net/http" - "strconv" -) - -// InvalidACL - acl invalid -type InvalidACL struct { - ACL string -} - -func (e InvalidACL) Error() string { - return "Requested ACL is " + e.ACL + " invalid" -} +import "strconv" // InvalidMaxKeys - invalid maxkeys provided type InvalidMaxKeys struct { @@ -106,39 +93,3 @@ type InvalidQueryURL struct { func (e InvalidQueryURL) Error() string { return "Invalid query URL: " + e.URL } - -/* **** SAMPLE ERROR RESPONSE **** - - - AccessDenied - Access Denied - /mybucket/myphoto.jpg - F19772218238A85A - GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD - -*/ - -// ErrorResponse is the type returned by some API operations. -type ErrorResponse struct { - Code string - Message string - Resource string - RequestID string - HostID string -} - -// ResponseToError returns a new encoded ErrorResponse structure -func ResponseToError(res *http.Response) error { - var respError ErrorResponse - decoder := xml.NewDecoder(res.Body) - err := decoder.Decode(&respError) - if err != nil { - return err - } - return respError -} - -// Error formats HTTP error string -func (e ErrorResponse) Error() string { - return e.Message -} diff --git a/pkg/client/s3/object_get.go b/pkg/client/s3/object_get.go deleted file mode 100644 index 192f65da..00000000 --- a/pkg/client/s3/object_get.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "fmt" - "io" - "strings" - - "net/http" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" -) - -/// Object API operations - -func (c *s3Client) setRange(req *http.Request, offset, length int64) (*http.Request, error) { - if offset < 0 { - return nil, iodine.New(client.InvalidRange{Offset: offset}, nil) - } - if length >= 0 { - req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) - } else { - req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) - } - return req, nil -} - -func (c *s3Client) get() (*http.Request, error) { - queryURL, err := c.getRequestURL() - if err != nil { - return nil, iodine.New(err, nil) - } - if !c.isValidQueryURL(queryURL) { - return nil, iodine.New(InvalidQueryURL{URL: queryURL}, nil) - } - req, err := c.newRequest("GET", queryURL, nil) - if err != nil { - return nil, iodine.New(err, nil) - } - return req, nil -} - -// GetObject fetches full object or part of the s3 object in bucket. -// If length is negative, the rest of the object is returned. -func (c *s3Client) GetObject(offset, length int64) (body io.ReadCloser, size int64, md5 string, err error) { - req, err := c.get() - if err != nil { - return nil, 0, "", iodine.New(err, nil) - } - if offset == 0 && length == 0 { - req, err = c.setRange(req, offset, length) - if err != nil { - return nil, 0, "", iodine.New(err, nil) - } - } - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - c.signRequest(req, c.Host) - } - res, err := c.Transport.RoundTrip(req) - if err != nil { - return nil, 0, "", iodine.New(err, nil) - } - - switch res.StatusCode { - case http.StatusOK, http.StatusPartialContent: - md5sum := strings.Trim(res.Header.Get("ETag"), "\"") // trim off the erroneous double quotes - return res.Body, res.ContentLength, md5sum, nil - default: - return nil, 0, "", iodine.New(ResponseToError(res), nil) - } -} diff --git a/pkg/client/s3/object_put.go b/pkg/client/s3/object_put.go deleted file mode 100644 index d8e4c1e7..00000000 --- a/pkg/client/s3/object_put.go +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "encoding/base64" - "encoding/hex" - "errors" - "io" - "net/http" - "strings" - - "github.com/minio/mc/pkg/client" - "github.com/minio/minio/pkg/iodine" -) - -/// Object Operations PUT - keeping this in a separate file for readability - -func (c *s3Client) put(size int64) (*http.Request, error) { - queryURL, err := c.getRequestURL() - if err != nil { - return nil, iodine.New(err, nil) - } - if !c.isValidQueryURL(queryURL) { - return nil, iodine.New(InvalidQueryURL{URL: queryURL}, nil) - } - req, err := c.newRequest("PUT", queryURL, nil) - if err != nil { - return nil, iodine.New(err, nil) - } - req.ContentLength = size - return req, nil -} - -// CreateObject - upload new object to bucket -func (c *s3Client) CreateObject(md5HexString string, size int64) (io.WriteCloser, error) { - // if size is negative - if size < 0 { - return nil, iodine.New(client.InvalidArgument{Err: errors.New("invalid argument")}, nil) - } - // starting Pipe session - r, w := io.Pipe() - blockingWriter := client.NewBlockingWriteCloser(w) - go func() { - req, err := c.put(size) - if err != nil { - err := iodine.New(err, nil) - r.CloseWithError(err) - blockingWriter.Release(err) - return - } - // set Content-MD5 only if md5 is provided - if strings.TrimSpace(md5HexString) != "" { - md5, err := hex.DecodeString(md5HexString) - if err != nil { - err := iodine.New(err, nil) - r.CloseWithError(err) - blockingWriter.Release(err) - return - } - req.Header.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5)) - } - if c.AccessKeyID != "" && c.SecretAccessKey != "" { - c.signRequest(req, c.Host) - } - req.Body = r - // this is necessary for debug, since the underlying transport is a wrapper - res, err := c.Transport.RoundTrip(req) - if err != nil { - err := iodine.New(err, nil) - r.CloseWithError(err) - blockingWriter.Release(err) - return - } - if res.StatusCode != http.StatusOK { - err := iodine.New(ResponseToError(res), nil) - r.CloseWithError(err) - blockingWriter.Release(err) - return - } - r.Close() - blockingWriter.Release(nil) - }() - return blockingWriter, nil -} diff --git a/pkg/client/s3/request.go b/pkg/client/s3/request.go deleted file mode 100644 index 092f6f1d..00000000 --- a/pkg/client/s3/request.go +++ /dev/null @@ -1,95 +0,0 @@ -package s3 - -import ( - "errors" - "fmt" - "io" - "net/http" - "net/url" - "strings" - "time" - - "github.com/minio/minio/pkg/iodine" -) - -func (c *s3Client) isValidQueryURL(queryURL string) bool { - u, err := url.Parse(queryURL) - if err != nil { - return false - } - if !strings.Contains(u.Scheme, "http") { - return false - } - return true -} - -// url2BucketAndObject gives bucketName and objectName from URL path -func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { - splits := strings.SplitN(c.Path, "/", 3) - switch len(splits) { - case 0, 1: - bucketName = "" - objectName = "" - case 2: - bucketName = splits[1] - objectName = "" - case 3: - bucketName = splits[1] - objectName = splits[2] - } - return bucketName, objectName -} - -func (c *s3Client) getBucketRequestURL(bucket string) string { - return fmt.Sprintf("%s://%s/%s", c.Scheme, c.Host, bucket) -} - -// getObjectRequestURL constructs a URL using bucket and object -func (c *s3Client) getObjectRequestURL(bucket, object string) string { - return c.getBucketRequestURL(bucket) + "/" + object -} - -func (c *s3Client) mustGetRequestURL() string { - requestURL, _ := c.getRequestURL() - return requestURL -} - -// getRequestURL constructs a URL. URL is appropriately encoded based on the host's object storage implementation. -func (c *s3Client) getRequestURL() (string, error) { - bucket, object := c.url2BucketAndObject() - // Avoid bucket names with "." in them - // Citing - http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html - // - // ===================== - // When using virtual hosted–style buckets with SSL, the SSL wild card certificate - // only matches buckets that do not contain periods. To work around this, use HTTP - // or write your own certificate verification logic. - // ===================== - // - switch { - case bucket == "" && object == "": - return fmt.Sprintf("%s://%s/", c.Scheme, c.Host), nil - case bucket != "" && object == "": - return c.getBucketRequestURL(bucket), nil - case bucket != "" && object != "": - return c.getObjectRequestURL(bucket, object), nil - } - return "", iodine.New(errors.New("Unexpected error, please report this.."), nil) -} - -// Instantiate a new request -func (c *s3Client) newRequest(method, url string, body io.ReadCloser) (*http.Request, error) { - errParams := map[string]string{ - "url": url, - "method": method, - "userAgent": c.UserAgent, - } - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, iodine.New(err, errParams) - } - - req.Header.Set("User-Agent", c.UserAgent) - req.Header.Set("X-Amz-Date", time.Now().UTC().Format(http.TimeFormat)) - return req, nil -} diff --git a/pkg/client/s3/s3.go b/pkg/client/s3/s3.go new file mode 100644 index 00000000..cc6baeb7 --- /dev/null +++ b/pkg/client/s3/s3.go @@ -0,0 +1,270 @@ +/* + * Minio Client (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package s3 + +import ( + "io" + "net/http" + "net/url" + "os" + "strings" + + "github.com/minio/mc/pkg/client" + "github.com/minio/minio/pkg/iodine" + "github.com/minio/objectstorage-go" +) + +// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html +type Config struct { + AccessKeyID string + SecretAccessKey string + HostURL string + UserAgent string + Debug bool + + // Used for SSL transport layer + CertPEM string + KeyPEM string +} + +// TLSConfig - TLS cert and key configuration +type TLSConfig struct { + CertPEMBlock []byte + KeyPEMBlock []byte +} + +type s3Client struct { + api objectstorage.API + hostURL *url.URL +} + +// New returns an initialized s3Client structure. if debug use a internal trace transport +func New(config *Config) client.Client { + u, err := url.Parse(config.HostURL) + if err != nil { + return nil + } + var transport http.RoundTripper + switch { + case config.Debug == true: + transport = GetNewTraceTransport(nil, GetNewTraceTransport(NewTrace(false, true, nil), http.DefaultTransport)) + default: + transport = http.DefaultTransport + } + objectstorageConf := new(objectstorage.Config) + objectstorageConf.AccessKeyID = config.AccessKeyID + objectstorageConf.SecretAccessKey = config.SecretAccessKey + objectstorageConf.UserAgent = config.UserAgent + objectstorageConf.Region = "us-east-1" + objectstorageConf.Transport = transport + objectstorageConf.Endpoint = u.Scheme + "://" + u.Host + api := objectstorage.New(objectstorageConf) + return &s3Client{api: api, hostURL: u} +} + +// GetObject - get object +func (c *s3Client) GetObject(offset, length uint64) (io.ReadCloser, uint64, string, error) { + bucket, object := c.url2BucketAndObject() + reader, metadata, err := c.api.GetObject(bucket, object, offset, length) + if err != nil { + return nil, 0, "", iodine.New(err, nil) + } + return reader, uint64(metadata.Size), metadata.ETag, nil +} + +// CreateObject - create object +func (c *s3Client) CreateObject(md5 string, size uint64) (io.WriteCloser, error) { + // md5 is purposefully ignored since AmazonS3 does not return proper md5sum + // for a multipart upload and there is no need to cross verify + bucket, object := c.url2BucketAndObject() + r, w := io.Pipe() + // TODO - bump this value from default, if neede + // objectstorage.DefaultPartSize = 1024 * 1024 * 100 + blockingWriter := client.NewBlockingWriteCloser(w) + go func() { + _, err := c.api.CreateObject(bucket, object, size, r) + if err != nil { + err := iodine.New(err, nil) + r.CloseWithError(err) + blockingWriter.Release(err) + return + } + blockingWriter.Release(nil) + r.Close() + }() + return blockingWriter, nil +} + +// CreateBucket - create a new bucket +func (c *s3Client) CreateBucket() error { + bucket, object := c.url2BucketAndObject() + if object != "" { + return iodine.New(InvalidQueryURL{URL: c.hostURL.String()}, nil) + } + err := c.api.CreateBucket(bucket, "private", "") + return iodine.New(err, nil) +} + +// SetBucketACL add canned acl's on a bucket +func (c *s3Client) SetBucketACL(acl string) error { + bucket, object := c.url2BucketAndObject() + if object != "" { + return iodine.New(InvalidQueryURL{URL: c.hostURL.String()}, nil) + } + err := c.api.SetBucketACL(bucket, acl) + return iodine.New(err, nil) +} + +// Stat - send a 'HEAD' on a bucket or object to get its metadata +func (c *s3Client) Stat() (*client.Content, error) { + bucket, object := c.url2BucketAndObject() + if object != "" { + metadata, err := c.api.StatObject(bucket, object) + if err != nil { + return nil, iodine.New(err, nil) + } + objectMetadata := new(client.Content) + objectMetadata.Name = metadata.Key + objectMetadata.Time = metadata.LastModified + objectMetadata.Size = metadata.Size + objectMetadata.FileType = 0 + return objectMetadata, nil + } + err := c.api.StatBucket(bucket) + if err != nil { + return nil, iodine.New(err, nil) + } + bucketMetadata := new(client.Content) + bucketMetadata.Name = bucket + bucketMetadata.FileType = os.ModeDir + return bucketMetadata, nil +} + +// url2BucketAndObject gives bucketName and objectName from URL path +func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { + splits := strings.SplitN(c.hostURL.Path, "/", 3) + switch len(splits) { + case 0, 1: + bucketName = "" + objectName = "" + case 2: + bucketName = splits[1] + objectName = "" + case 3: + bucketName = splits[1] + objectName = splits[2] + } + return bucketName, objectName +} + +/// Bucket API operations + +// List - list at delimited path not recursive +func (c *s3Client) List() <-chan client.ContentOnChannel { + contentCh := make(chan client.ContentOnChannel) + go c.listInGoRoutine(contentCh) + return contentCh +} + +// ListRecursive - list buckets and objects recursively +func (c *s3Client) ListRecursive() <-chan client.ContentOnChannel { + contentCh := make(chan client.ContentOnChannel) + go c.listRecursiveInGoRoutine(contentCh) + return contentCh +} + +func (c *s3Client) listInGoRoutine(contentCh chan client.ContentOnChannel) { + defer close(contentCh) + bucket, object := c.url2BucketAndObject() + switch { + case bucket == "" && object == "": + for bucket := range c.api.ListBuckets() { + if bucket.Err != nil { + contentCh <- client.ContentOnChannel{ + Content: nil, + Err: bucket.Err, + } + return + } + content := new(client.Content) + content.Name = bucket.Data.Name + content.Size = 0 + content.Time = bucket.Data.CreationDate + content.FileType = os.ModeDir + contentCh <- client.ContentOnChannel{ + Content: content, + Err: nil, + } + } + default: + metadata, err := c.api.StatObject(bucket, object) + switch err.(type) { + case nil: + content := new(client.Content) + content.Name = metadata.Key + content.Time = metadata.LastModified + content.Size = metadata.Size + content.FileType = 0 + contentCh <- client.ContentOnChannel{ + Content: content, + Err: nil, + } + default: + for object := range c.api.ListObjects(bucket, object, false) { + if object.Err != nil { + contentCh <- client.ContentOnChannel{ + Content: nil, + Err: object.Err, + } + return + } + content := new(client.Content) + content.Name = object.Data.Key + content.Size = object.Data.Size + content.Time = object.Data.LastModified + content.FileType = 0 + contentCh <- client.ContentOnChannel{ + Content: content, + Err: nil, + } + } + } + } +} + +func (c *s3Client) listRecursiveInGoRoutine(contentCh chan client.ContentOnChannel) { + defer close(contentCh) + bucket, object := c.url2BucketAndObject() + for object := range c.api.ListObjects(bucket, object, true) { + if object.Err != nil { + contentCh <- client.ContentOnChannel{ + Content: nil, + Err: object.Err, + } + return + } + content := new(client.Content) + content.Name = object.Data.Key + content.Size = object.Data.Size + content.Time = object.Data.LastModified + content.FileType = 0 + contentCh <- client.ContentOnChannel{ + Content: content, + Err: nil, + } + } +} diff --git a/pkg/client/s3/s3verify.go b/pkg/client/s3/s3verify.go deleted file mode 100644 index 54bb1111..00000000 --- a/pkg/client/s3/s3verify.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import "net/http" - -// Only generic HTTP S3 fields are validated using this mechanism. S3 -// command specific checks should be added to their own appropriate -// files. -type s3Verify struct { -} - -/* -Example AWS S3 Request / Response -================================= - $ mc --debug ls https://zek.s3.amazonaws.com - GET /?max-keys=1000 HTTP/1.1 - Host: zek.s3.amazonaws.com - User-Agent: Minio Client - Authorization: AWS **PASSWORD**STRIPPED** - Date: Thu, 12 Mar 2015 23:04:23 GMT - Accept-Encoding: gzip - - HTTP/1.1 200 OK - Transfer-Encoding: chunked - Content-Type: application/xml - Date: Thu, 12 Mar 2015 23:04:24 GMT - Server: AmazonS3 - X-Amz-Id-2: NFc3FTxx4dD+z348qOv532aIaq4VufRnZEnq2kGOloTKhHYhBBZ6qe8mcmZcR+L3Us4N5j0WNtk= - X-Amz-Request-Id: 5E9A737908F886D0 - - 2015-03-11 01:28:03 -0700 PDT 1.10 KB color.go - 2015-03-08 03:31:50 -0700 PDT 11.09 KB apache/license.txt -*/ - -// HTTP S3 request validator. -func (t s3Verify) Request(req *http.Request) error { - // No Auth key is a valid case - /* - if req.Header.Get("Authorization") == "" { - return iodine.New(AuthorizationKeyEmpty{Err: errors.New("authorization key empty")}, nil) - } - if !strings.HasPrefix(req.Header.Get("Authorization"), "AWS") { - return iodine.New(InvalidAuthorizationKey{Err: errors.New("invalid authorization key")}, nil) - } - */ - return nil -} - -// HTTP S3 response validator. -func (t s3Verify) Response(res *http.Response) error { - return nil -} diff --git a/pkg/client/s3/trace.go b/pkg/client/s3/trace.go index a5b12a49..2b5c9e5b 100644 --- a/pkg/client/s3/trace.go +++ b/pkg/client/s3/trace.go @@ -46,7 +46,7 @@ func NewTrace(bodyTraceFlag, requestTransportFlag bool, writer io.Writer) HTTPTr // Request - Trace HTTP Request func (t Trace) Request(req *http.Request) (err error) { origAuthKey := req.Header.Get("Authorization") - req.Header.Set("Authorization", "AWS **PASSWORD**STRIPPED**") + req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=**REDACTED**, SignedHeaders=**REDACTED**, Signature=**REDACTED**") if t.RequestTransportFlag { reqTrace, err := httputil.DumpRequestOut(req, t.BodyTraceFlag)