Merge pull request #122 from harshavardhana/pr_out_new_changes_coming

This commit is contained in:
Harshavardhana
2015-03-15 01:06:57 -07:00
15 changed files with 171 additions and 180 deletions
+37 -16
View File
@@ -75,7 +75,11 @@ func getNewClient(c *cli.Context) (*s3.Client, error) {
switch c.GlobalBool("debug") {
case true:
trace := s3Trace{BodyTraceFlag: false, RequestTransportFlag: true, Writer: nil}
trace := s3.Trace{
BodyTraceFlag: false,
RequestTransportFlag: true,
Writer: nil,
}
traceTransport := s3.GetNewTraceTransport(trace, http.DefaultTransport)
client = s3.GetNewClient(&config.S3.Auth, traceTransport)
case false:
@@ -101,19 +105,27 @@ func parseArgs(c *cli.Context) (args *cmdArgs, err error) {
args.quiet = c.GlobalBool("quiet")
switch len(c.Args()) {
case 0:
return args, nil
case 1:
if strings.HasPrefix(c.Args().Get(0), "s3://") {
if strings.HasPrefix(c.Args().Get(0), "http") || strings.HasPrefix(c.Args().Get(0), "https") {
uri, err := url.Parse(c.Args().Get(0))
if err != nil {
return nil, err
}
if uri.Scheme != "s3" {
if !strings.HasPrefix(uri.Scheme, "http") && !strings.HasPrefix(uri.Scheme, "https") {
return nil, errInvalidScheme
}
args.source.bucket = uri.Host
args.source.key = strings.TrimPrefix(uri.Path, "/")
args.source.scheme = uri.Scheme
if uri.Scheme != "" {
if uri.Host == "" {
return nil, errHostname
}
}
args.source.host = uri.Host
uriSplits := strings.Split(uri.Path, "/")
if len(uriSplits) > 1 {
args.source.bucket = uriSplits[1]
args.source.key = path.Join(uriSplits[2:]...)
}
} else {
return nil, errInvalidScheme
}
@@ -125,15 +137,20 @@ func parseArgs(c *cli.Context) (args *cmdArgs, err error) {
return nil, err
}
switch true {
case uri.Scheme == "s3":
case uri.Scheme == "http" || uri.Scheme == "https":
if uri.Host == "" {
if uri.Path == "" {
return nil, errInvalidScheme
}
return nil, errInvalidScheme
}
args.source.bucket = uri.Host
args.source.key = strings.TrimPrefix(uri.Path, "/")
args.source.scheme = uri.Scheme
args.source.host = uri.Host
uriSplits := strings.Split(uri.Path, "/")
if len(uriSplits) > 1 {
args.source.bucket = uriSplits[1]
args.source.key = path.Join(uriSplits[2:]...)
}
case uri.Scheme == "":
if uri.Host != "" {
return nil, errInvalidScheme
@@ -144,9 +161,8 @@ func parseArgs(c *cli.Context) (args *cmdArgs, err error) {
if uri.Path == "." {
return nil, errFskey
}
args.source.bucket = uri.Host
args.source.key = strings.TrimPrefix(uri.Path, "/")
case uri.Scheme != "s3":
case uri.Scheme != "http" && uri.Scheme != "https":
return nil, errInvalidScheme
}
fallthrough
@@ -156,15 +172,20 @@ func parseArgs(c *cli.Context) (args *cmdArgs, err error) {
return nil, err
}
switch true {
case uri.Scheme == "s3":
case uri.Scheme == "http" || uri.Scheme == "https":
if uri.Host == "" {
if uri.Path == "" {
return nil, errInvalidScheme
}
return nil, errInvalidScheme
}
args.destination.bucket = uri.Host
args.destination.key = strings.TrimPrefix(uri.Path, "/")
args.destination.host = uri.Host
args.destination.scheme = uri.Scheme
uriSplits := strings.Split(uri.Path, "/")
if len(uriSplits) > 1 {
args.destination.bucket = uriSplits[1]
args.destination.key = path.Join(uriSplits[2:]...)
}
case uri.Scheme == "":
if uri.Host != "" {
return nil, errInvalidScheme
@@ -175,7 +196,7 @@ func parseArgs(c *cli.Context) (args *cmdArgs, err error) {
args.destination.key = strings.TrimPrefix(uri.Path, "/")
}
args.destination.bucket = uri.Host
case uri.Scheme != "s3":
case uri.Scheme != "http" && uri.Scheme != "https":
return nil, errInvalidScheme
}
}
+2 -11
View File
@@ -50,27 +50,18 @@ func getMcConfig() (config *mcConfig, err error) {
return nil, err
}
if config.S3.Auth.Endpoint == "" {
config.S3.Auth.Endpoint = "s3.amazonaws.com"
}
return config, nil
}
func parseConfigureInput(c *cli.Context) (config *mcConfig, err error) {
accessKey := c.String("accesskey")
secretKey := c.String("secretkey")
endpoint := c.String("endpoint")
pathstyle := c.Bool("pathstyle")
config = &mcConfig{
Version: "0.1.0",
S3: s3Config{
Auth: s3.Auth{
AccessKey: accessKey,
SecretAccessKey: secretKey,
Endpoint: endpoint,
S3ForcePathStyle: pathstyle,
AccessKey: accessKey,
SecretAccessKey: secretKey,
},
},
}
+30 -17
View File
@@ -79,16 +79,17 @@ func firstMode(s3c *s3.Client, args *cmdArgs) error {
return err
}
// s3://<bucket> is specified without key
// http://<bucket>.<hostname> is specified without key
if args.destination.key == "" {
args.destination.key = args.source.key
}
s3c.Host = args.destination.host
s3c.Scheme = args.destination.scheme
err = s3c.Put(args.destination.bucket, args.destination.key, size, source)
if err != nil {
return err
}
msg := fmt.Sprintf("%s uploaded -- to bucket:(s3://%s/%s)", args.source.key,
msg := fmt.Sprintf("%s uploaded -- to bucket:(http://%s/%s)", args.source.key,
args.destination.bucket, args.destination.key)
info(msg)
return nil
@@ -182,6 +183,8 @@ func thirdMode(s3c *s3.Client, args *cmdArgs) error {
var objectSize int64
var err error
s3c.Host = args.source.host
s3c.Scheme = args.source.scheme
// Send HEAD request to validate if file exists.
objectSize, _, err = s3c.Stat(args.source.bucket, args.source.key)
if err != nil {
@@ -193,13 +196,19 @@ func thirdMode(s3c *s3.Client, args *cmdArgs) error {
}
// Check if the object already exists
s3c.Host = args.destination.host
s3c.Scheme = args.destination.scheme
_, _, err = s3c.Stat(args.destination.bucket, args.destination.key)
switch os.IsNotExist(err) {
case true:
s3c.Host = args.source.host
s3c.Scheme = args.source.scheme
objectReader, _, err = s3c.Get(args.source.bucket, args.source.key)
if err != nil {
return err
}
s3c.Host = args.destination.host
s3c.Scheme = args.destination.scheme
err = s3c.Put(args.destination.bucket, args.destination.key, objectSize, objectReader)
if err != nil {
return err
@@ -208,7 +217,7 @@ func thirdMode(s3c *s3.Client, args *cmdArgs) error {
return fmt.Errorf("Ranges not supported")
}
msg := fmt.Sprintf("s3://%s/%s uploaded -- to bucket:(s3://%s/%s)", args.source.bucket, args.source.key,
msg := fmt.Sprintf("http://%s/%s uploaded -- to bucket:(http://%s/%s)", args.source.bucket, args.source.key,
args.destination.bucket, args.destination.key)
info(msg)
return nil
@@ -236,7 +245,16 @@ func fourthMode(s3c *s3.Client, args *cmdArgs) error {
}
func doFsCopy(c *cli.Context) {
s3c, err := getNewClient(c)
var args *cmdArgs
var err error
var s3c *s3.Client
args, err = parseArgs(c)
if err != nil {
fatal(err.Error())
}
s3c, err = getNewClient(c)
if err != nil {
fatal(err.Error())
}
@@ -244,31 +262,26 @@ func doFsCopy(c *cli.Context) {
if len(c.Args()) != 2 {
fatal("Invalid number of args")
}
var cmdargs *cmdArgs
cmdargs, err = parseArgs(c)
if err != nil {
fatal(err.Error())
}
switch getMode(c.Bool("recursive"), cmdargs) {
s3c.Host = args.source.host
s3c.Scheme = args.source.scheme
switch getMode(c.Bool("recursive"), args) {
case first:
err := firstMode(s3c, cmdargs)
err := firstMode(s3c, args)
if err != nil {
fatal(err.Error())
}
case second:
err := secondMode(s3c, cmdargs)
err := secondMode(s3c, args)
if err != nil {
fatal(err.Error())
}
case third:
err := thirdMode(s3c, cmdargs)
err := thirdMode(s3c, args)
if err != nil {
fatal(err.Error())
}
case fourth:
err := fourthMode(s3c, cmdargs)
err := fourthMode(s3c, args)
if err != nil {
fatal(err.Error())
}
+4 -1
View File
@@ -23,7 +23,10 @@ var (
errFskey = errors.New("Key is needed to get the file")
// uri
errInvalidScheme = errors.New("Invalid URI scheme only s3:// supported")
errInvalidScheme = errors.New("Invalid URI scheme only http{s}:// supported")
// host
errHostname = errors.New("No hostname specified")
// common
errInvalidbucket = errors.New("Invalid bucket name")
+8 -4
View File
@@ -54,14 +54,18 @@ func printObject(date time.Time, v int64, key string) {
func doFsList(c *cli.Context) {
var items []*s3.Item
s3c, err := getNewClient(c)
if err != nil {
fatal(err.Error())
}
args, err := parseArgs(c)
if err != nil {
fatal(err.Error())
}
s3c, err := getNewClient(c)
if err != nil {
fatal(err.Error())
}
s3c.Host = args.source.host
s3c.Scheme = args.source.scheme
switch true {
case args.source.bucket == "": // List all buckets
buckets, err := s3c.ListBuckets()
+11 -9
View File
@@ -22,18 +22,20 @@ import (
)
func doFsMb(c *cli.Context) {
switch len(c.Args()) {
case 1:
if !s3.IsValidBucket(c.Args().Get(0)) {
fatal(errInvalidbucket.Error())
}
default:
fatal("Needs an argument <BucketName>")
args, err := parseArgs(c)
if err != nil {
fatal(err.Error())
}
bucketName := c.Args().Get(0)
s3c, err := getNewClient(c)
err = s3c.PutBucket(bucketName)
if !s3.IsValidBucket(args.source.bucket) {
fatal(errInvalidbucket.Error())
}
s3c.Host = args.source.host
s3c.Scheme = args.source.scheme
err = s3c.PutBucket(args.source.bucket)
if err != nil {
fatal(err.Error())
}
+2 -9
View File
@@ -67,21 +67,14 @@ var configure = cli.Command{
Value: "",
Usage: "AWS secret key id",
},
cli.StringFlag{
Name: "endpoint, e",
Value: "s3.amazonaws.com",
Usage: "S3 Endpoint URL default is 's3.amazonaws.com'",
},
cli.BoolFlag{
Name: "pathstyle, p",
Usage: "Force path style API requests",
},
},
}
type object struct {
bucket string
key string
host string
scheme string
}
type cmdArgs struct {
+4 -3
View File
@@ -49,7 +49,7 @@ func (w *walk) putWalk(p string, i os.FileInfo, err error) error {
if err != nil {
return err
}
msg := fmt.Sprintf("%s uploaded -- to bucket:s3://%s/%s", key, bucketname, key)
msg := fmt.Sprintf("%s uploaded -- to bucket:http://%s/%s", key, bucketname, key)
info(msg)
return nil
}
@@ -81,8 +81,6 @@ func doRecursiveCp(s3c *s3.Client, args *cmdArgs) error {
var st os.FileInfo
var buckets []*s3.Bucket
p := &walk{s3c, args}
switch true {
case args.source.bucket == "":
input := path.Clean(args.source.key)
@@ -97,6 +95,9 @@ func doRecursiveCp(s3c *s3.Client, args *cmdArgs) error {
return fmt.Errorf("Should be a directory")
}
s3c.Host = args.destination.host
s3c.Scheme = args.destination.scheme
p := &walk{s3c, args}
buckets, err = s3c.ListBuckets()
if !isBucketExists(args.destination.bucket, buckets) {
// Create bucketname, before uploading files
+15 -36
View File
@@ -60,15 +60,9 @@ type Auth struct {
AccessKey string
SecretAccessKey string
// If empty, the standard US region of "s3.amazonaws.com" is used.
Endpoint string
// Used for SSL transport layer
CertPEM string
KeyPEM string
// Force path style
S3ForcePathStyle bool
}
// TLSConfig - TLS cert and key configuration
@@ -77,19 +71,6 @@ type TLSConfig struct {
KeyPEMBlock []byte
}
const standardUSRegionAWS = "s3.amazonaws.com"
func (a *Auth) endpoint() string {
// Prefix with https for Amazon endpoints
if a.Endpoint != "" {
if strings.HasSuffix(a.Endpoint, "amazonaws.com") {
return "https://" + a.Endpoint
}
return "http://" + a.Endpoint
}
return "https://" + standardUSRegionAWS
}
func (a *Auth) loadKeys(cert string, key string) (*TLSConfig, error) {
certBlock, err := ioutil.ReadFile(cert)
if err != nil {
@@ -137,12 +118,12 @@ func (a *Auth) getTLSTransport() (*http.Transport, error) {
return transport, nil
}
func (a *Auth) signRequest(req *http.Request) {
func (a *Auth) signRequest(req *http.Request, host string) {
if date := req.Header.Get("Date"); date == "" {
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
}
hm := hmac.New(sha1.New, []byte(a.SecretAccessKey))
ss := a.stringToSign(req)
ss := a.stringToSign(req, host)
//fmt.Printf("String to sign: %q (%x)\n", ss, ss)
io.WriteString(hm, ss)
@@ -171,7 +152,7 @@ func firstNonEmptyString(strs ...string) string {
// Date + "\n" +
// CanonicalizedAmzHeaders +
// CanonicalizedResource;
func (a *Auth) stringToSign(req *http.Request) string {
func (a *Auth) stringToSign(req *http.Request, host string) string {
buf := new(bytes.Buffer)
buf.WriteString(req.Method)
buf.WriteByte('\n')
@@ -184,7 +165,7 @@ func (a *Auth) stringToSign(req *http.Request) string {
}
buf.WriteByte('\n')
a.writeCanonicalizedAmzHeaders(buf, req)
a.writeCanonicalizedResource(buf, req)
a.writeCanonicalizedResource(buf, req, host)
return buf.String()
}
@@ -241,8 +222,8 @@ var subResList = []string{"acl", "lifecycle", "location", "logging", "notificati
// CanonicalizedResource = [ "/" + Bucket ] +
// <HTTP-Request-URI, from the protocol name up to the query string> +
// [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"];
func (a *Auth) writeCanonicalizedResource(buf *bytes.Buffer, req *http.Request) {
bucket := a.bucketFromEndpoint(req)
func (a *Auth) writeCanonicalizedResource(buf *bytes.Buffer, req *http.Request, host string) {
bucket := a.bucketFromEndpoint(req, host)
if bucket != "" {
buf.WriteByte('/')
buf.WriteString(bucket)
@@ -274,27 +255,25 @@ func hasDotSuffix(s string, suffix string) bool {
return len(s) >= len(suffix)+1 && strings.HasSuffix(s, suffix) && s[len(s)-len(suffix)-1] == '.'
}
func (a *Auth) bucketFromEndpoint(req *http.Request) string {
host := req.Host
if host == "" {
func (a *Auth) bucketFromEndpoint(req *http.Request, host string) string {
reqHost := req.Host
if reqHost == "" {
host = req.URL.Host
}
if host == strings.TrimPrefix(a.endpoint(), "http://") {
if reqHost == strings.TrimPrefix(host, "http://") {
return ""
}
if host == strings.TrimPrefix(a.endpoint(), "https://") {
if reqHost == strings.TrimPrefix(host, "https://") {
return ""
}
if hostSuffix := strings.TrimPrefix(a.endpoint(), "https://"); hasDotSuffix(host, hostSuffix) {
return host[:len(host)-len(hostSuffix)-1]
if reqHostSuffix := strings.TrimPrefix(host, "https://"); hasDotSuffix(reqHost, reqHostSuffix) {
return reqHost[:len(reqHost)-len(reqHostSuffix)-1]
}
if lastColon := strings.LastIndex(host, ":"); lastColon != -1 {
return host[:lastColon]
}
reqHost, _, _ = net.SplitHostPort(reqHost)
return host
return reqHost
}
+15 -15
View File
@@ -47,7 +47,7 @@ import (
)
type reqAndExpected struct {
req, expected string
req, expected, host string
}
func req(s string) *http.Request {
@@ -66,7 +66,7 @@ Host: johnsmith.s3.amazonaws.com
Date: Tue, 27 Mar 2007 19:36:42 +0000
`,
"GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n/johnsmith/photos/puppy.jpg"},
"GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n/johnsmith/photos/puppy.jpg", "s3.amazonaws.com"},
{`PUT /photos/puppy.jpg HTTP/1.1
Content-Type: image/jpeg
Content-Length: 94328
@@ -74,14 +74,14 @@ Host: johnsmith.s3.amazonaws.com
Date: Tue, 27 Mar 2007 21:15:45 +0000
`,
"PUT\n\nimage/jpeg\nTue, 27 Mar 2007 21:15:45 +0000\n/johnsmith/photos/puppy.jpg"},
"PUT\n\nimage/jpeg\nTue, 27 Mar 2007 21:15:45 +0000\n/johnsmith/photos/puppy.jpg", "s3.amazonaws.com"},
{`GET /?prefix=photos&max-keys=50&marker=puppy HTTP/1.1
User-Agent: Mozilla/5.0
Host: johnsmith.s3.amazonaws.com
Date: Tue, 27 Mar 2007 19:42:41 +0000
`,
"GET\n\n\nTue, 27 Mar 2007 19:42:41 +0000\n/johnsmith/"},
"GET\n\n\nTue, 27 Mar 2007 19:42:41 +0000\n/johnsmith/", "s3.amazonaws.com"},
{`DELETE /johnsmith/photos/puppy.jpg HTTP/1.1
User-Agent: dotnet
Host: s3.amazonaws.com
@@ -89,7 +89,7 @@ Date: Tue, 27 Mar 2007 21:20:27 +0000
x-amz-date: Tue, 27 Mar 2007 21:20:26 +0000
`,
"DELETE\n\n\n\nx-amz-date:Tue, 27 Mar 2007 21:20:26 +0000\n/johnsmith/photos/puppy.jpg"},
"DELETE\n\n\n\nx-amz-date:Tue, 27 Mar 2007 21:20:26 +0000\n/johnsmith/photos/puppy.jpg", "s3.amazonaws.com"},
{`PUT /db-backup.dat.gz HTTP/1.1
User-Agent: curl/7.15.5
Host: static.johnsmith.net:8080
@@ -106,10 +106,10 @@ Content-Encoding: gzip
Content-Length: 5913339
`,
"PUT\n4gJE4saaMU4BqNR0kLY+lw==\napplication/x-download\nTue, 27 Mar 2007 21:06:08 +0000\nx-amz-acl:public-read\nx-amz-meta-checksumalgorithm:crc32\nx-amz-meta-filechecksum:0x02661779\nx-amz-meta-reviewedby:joe@johnsmith.net,jane@johnsmith.net\n/static.johnsmith.net/db-backup.dat.gz"},
"PUT\n4gJE4saaMU4BqNR0kLY+lw==\napplication/x-download\nTue, 27 Mar 2007 21:06:08 +0000\nx-amz-acl:public-read\nx-amz-meta-checksumalgorithm:crc32\nx-amz-meta-filechecksum:0x02661779\nx-amz-meta-reviewedby:joe@johnsmith.net,jane@johnsmith.net\n/db-backup.dat.gz", "static.johnsmith.net:8080"},
}
for idx, test := range tests {
got := a.stringToSign(req(test.req))
got := a.stringToSign(req(test.req), test.host)
if got != test.expected {
t.Errorf("test %d: expected %q", idx, test.expected)
t.Errorf("test %d: got %q", idx, got)
@@ -120,14 +120,14 @@ Content-Length: 5913339
func TestBucketFromHostname(t *testing.T) {
var a Auth
tests := []reqAndExpected{
{"GET / HTTP/1.0\n\n", ""},
{"GET / HTTP/1.0\nHost: s3.amazonaws.com\n\n", ""},
{"GET / HTTP/1.0\nHost: foo.s3.amazonaws.com\n\n", "foo"},
{"GET / HTTP/1.0\nHost: foo.com:123\n\n", "foo.com"},
{"GET / HTTP/1.0\nHost: bar.com\n\n", "bar.com"},
{"GET / HTTP/1.0\n\n", "", ""},
{"GET / HTTP/1.0\nHost: s3.amazonaws.com\n\n", "", "s3.amazonaws.com"},
{"GET / HTTP/1.0\nHost: foo.s3.amazonaws.com\n\n", "foo", "s3.amazonaws.com"},
{"GET / HTTP/1.0\nHost: foo.com:123\n\n", "foo.com", "foo.com"},
{"GET / HTTP/1.0\nHost: bar.com\n\n", "", "bar.com"},
}
for idx, test := range tests {
got := a.bucketFromEndpoint(req(test.req))
got := a.bucketFromEndpoint(req(test.req), test.host)
if got != test.expected {
t.Errorf("test %d: expected %q; got %q", idx, test.expected, got)
}
@@ -137,12 +137,12 @@ func TestBucketFromHostname(t *testing.T) {
func TestsignRequest(t *testing.T) {
r := req("GET /foo HTTP/1.1\n\n")
auth := &Auth{AccessKey: "key", SecretAccessKey: "secretkey"}
auth.signRequest(r)
auth.signRequest(r, "localhost:9000")
if r.Header.Get("Date") == "" {
t.Error("expected a Date set")
}
r.Header.Set("Date", "Sat, 02 Apr 2011 04:23:52 GMT")
auth.signRequest(r)
auth.signRequest(r, "localhost:9000")
if e, g := r.Header.Get("Authorization"), "AWS key:kHpCR/N7Rw3PwRlDd8+5X40CFVc="; e != g {
t.Errorf("got header %q; expected %q", g, e)
}
+9 -8
View File
@@ -63,10 +63,11 @@ func (a bySize) Less(i, j int) bool { return a[i].Size < a[j].Size }
// ListBuckets - Get list of buckets
func (c *Client) ListBuckets() ([]*Bucket, error) {
req := newReq(c.endpoint() + "/")
c.Auth.signRequest(req)
url := fmt.Sprintf("%s://%s/", c.Scheme, c.Host)
req := newReq(url)
c.Auth.signRequest(req, c.Host)
res, err := c.transport().RoundTrip(req)
res, err := c.Transport.RoundTrip(req)
if err != nil {
return nil, err
}
@@ -82,12 +83,12 @@ func (c *Client) ListBuckets() ([]*Bucket, error) {
func (c *Client) PutBucket(bucket string) error {
var url string
if IsValidBucket(bucket) && !strings.Contains(bucket, ".") {
url = fmt.Sprintf("%s/%s", c.endpoint(), bucket)
url = fmt.Sprintf("%s://%s/%s", c.Scheme, c.Host, bucket)
}
req := newReq(url)
req.Method = "PUT"
c.Auth.signRequest(req)
res, err := c.transport().RoundTrip(req)
c.Auth.signRequest(req, c.Host)
res, err := c.Transport.RoundTrip(req)
if err != nil {
return err
}
@@ -142,8 +143,8 @@ func (c *Client) ListObjects(bucket string, startAt, prefix, delimiter string, m
for try := 1; try <= maxTries; try++ {
time.Sleep(time.Duration(try-1) * 100 * time.Millisecond)
req := newReq(urlReq)
c.Auth.signRequest(req)
res, err := c.transport().RoundTrip(req)
c.Auth.signRequest(req, c.Host)
res, err := c.Transport.RoundTrip(req)
if err != nil {
if try < maxTries {
continue
+15 -33
View File
@@ -88,6 +88,12 @@ type listBucketResults struct {
type Client struct {
*Auth // AWS auth credentials
Transport http.RoundTripper // or nil for the default behavior
// Supports URL in following formats
// - http://<ipaddress>/<bucketname>/<object>
// - http://<bucketname>.<domain>/<object>
Host string
Scheme string
}
// GetNewClient returns an initialized S3.Client structure.
@@ -95,54 +101,30 @@ func GetNewClient(auth *Auth, transport http.RoundTripper) *Client {
return &Client{
Auth: auth,
Transport: GetNewTraceTransport(s3Verify{}, transport),
// Transport: transport,
}
}
func (c *Client) transport() http.RoundTripper {
if c.Transport != nil {
return c.Transport
}
return http.DefaultTransport
}
// bucketURL returns the URL prefix of the bucket, with trailing slash
func (c *Client) bucketURL(bucket string) string {
var url string
if IsValidBucket(bucket) && !strings.Contains(bucket, ".") {
// if localhost forcePathStyle
if strings.Contains(c.endpoint(), "localhost") || strings.Contains(c.endpoint(), "127.0.0.1") {
url = fmt.Sprintf("%s/%s", c.endpoint(), bucket)
goto ret
// if localhost use PathStyle
if strings.Contains(c.Host, "localhost") || strings.Contains(c.Host, "127.0.0.1") {
return fmt.Sprintf("%s://%s/%s", c.Scheme, c.Host, bucket)
}
host, _, _ := net.SplitHostPort(c.Endpoint)
// Verify if its ip address, use PathStyle
host, _, _ := net.SplitHostPort(c.Host)
if net.ParseIP(host) != nil {
url = fmt.Sprintf("%s/%s", c.endpoint(), bucket)
goto ret
}
if !c.S3ForcePathStyle {
if strings.Contains(c.endpoint(), "amazonaws.com") {
url = fmt.Sprintf("https://%s.%s/", bucket, strings.TrimPrefix(c.endpoint(), "https://"))
} else {
url = fmt.Sprintf("http://%s.%s/", bucket, strings.TrimPrefix(c.endpoint(), "http://"))
}
} else {
url = fmt.Sprintf("%s/%s", c.endpoint(), bucket)
return fmt.Sprintf("%s://%s/%s", c.Scheme, c.Host, bucket)
}
// For DNS hostname or amazonaws.com use subdomain style
url = fmt.Sprintf("%s://%s.%s/", c.Scheme, bucket, c.Host)
}
ret:
return url
}
func (c *Client) keyURL(bucket, key string) string {
// if localhost forcePathStyle
host, _, _ := net.SplitHostPort(c.Endpoint)
ok := (strings.Contains(c.endpoint(), "localhost") || strings.Contains(bucket, "127.0.0.1") || c.S3ForcePathStyle || net.ParseIP(host) != nil)
if ok {
return c.bucketURL(bucket) + "/" + key
}
return c.bucketURL(bucket) + key
return c.bucketURL(bucket) + "/" + key
}
func newReq(url string) *http.Request {
+8 -8
View File
@@ -74,9 +74,9 @@ func (c *Client) Put(bucket, key string, size int64, contents io.Reader) error {
req.Body = ioutil.NopCloser(sink)
b64 := base64.StdEncoding.EncodeToString(h.Sum(nil))
req.Header.Set("Content-MD5", b64)
c.Auth.signRequest(req)
c.Auth.signRequest(req, c.Host)
res, err := c.transport().RoundTrip(req)
res, err := c.Transport.RoundTrip(req)
if res != nil && res.Body != nil {
defer res.Body.Close()
}
@@ -95,8 +95,8 @@ func (c *Client) Put(bucket, key string, size int64, contents io.Reader) error {
func (c *Client) Stat(bucket, key string) (size int64, date time.Time, reterr error) {
req := newReq(c.keyURL(bucket, key))
req.Method = "HEAD"
c.Auth.signRequest(req)
res, err := c.transport().RoundTrip(req)
c.Auth.signRequest(req, c.Host)
res, err := c.Transport.RoundTrip(req)
if res != nil && res.Body != nil {
defer res.Body.Close()
}
@@ -129,8 +129,8 @@ func (c *Client) Stat(bucket, key string) (size int64, date time.Time, reterr er
// Get - download a requested object from a given bucket
func (c *Client) Get(bucket, key string) (body io.ReadCloser, size int64, err error) {
req := newReq(c.keyURL(bucket, key))
c.Auth.signRequest(req)
res, err := c.transport().RoundTrip(req)
c.Auth.signRequest(req, c.Host)
res, err := c.Transport.RoundTrip(req)
if err != nil {
return
}
@@ -159,9 +159,9 @@ func (c *Client) GetPartial(bucket, key string, offset, length int64) (body io.R
} else {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
}
c.Auth.signRequest(req)
c.Auth.signRequest(req, c.Host)
res, err := c.transport().RoundTrip(req)
res, err := c.Transport.RoundTrip(req)
if err != nil {
return
}
+1 -1
View File
@@ -31,7 +31,7 @@ type s3Verify struct {
/*
Example AWS S3 Request / Response
=================================
$ mc --debug ls s3://zek
$ mc --debug ls https://zek.s3.amazonaws.com
GET /?max-keys=1000 HTTP/1.1
Host: zek.s3.amazonaws.com
User-Agent: Minio Client
+10 -9
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package main
package s3
import (
"fmt"
@@ -23,14 +23,15 @@ import (
"net/http/httputil"
)
type s3Trace struct {
// Trace - tracing structure
type Trace struct {
BodyTraceFlag bool // Include Body
RequestTransportFlag bool // Include additional http.Transport adds such as User-Agent
Writer io.Writer // Console device to write to
Writer io.Writer // Console device to write
}
// Trace HTTP Request
func (t s3Trace) Request(req *http.Request) (err error) {
// 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**")
@@ -50,8 +51,8 @@ func (t s3Trace) Request(req *http.Request) (err error) {
return err
}
// Trace HTTP Response
func (t s3Trace) Response(res *http.Response) (err error) {
// Response - Trace HTTP Response
func (t Trace) Response(res *http.Response) (err error) {
resTrace, err := httputil.DumpResponse(res, t.BodyTraceFlag)
if err == nil {
t.print(resTrace)
@@ -59,8 +60,8 @@ func (t s3Trace) Response(res *http.Response) (err error) {
return err
}
// Trace HTTP Response
func (t s3Trace) print(data []byte) {
// print HTTP Response
func (t Trace) print(data []byte) {
if t.Writer != nil {
fmt.Fprintf(t.Writer, "%s", data)
} else {