Debian Codegraph @

oss/client.go

raw symbols SCIP
1 package oss
2
3 import (
4 "bytes"
5 "crypto/hmac"
6 "crypto/md5"
7 "crypto/sha1"
8 "encoding/base64"
9 "encoding/xml"
10 "fmt"
11 "io"
12 "io/ioutil"
13 "log"
14 "mime"
15 "net"
16 "net/http"
17 "net/http/httputil"
18 "net/url"
19 "os"
20 "path"
21 "strconv"
22 "strings"
23 "time"
24
25 "github.com/denverdino/aliyungo/common"
26 "github.com/denverdino/aliyungo/util"
27 )
28
29 const DefaultContentType = "application/octet-stream"
30
31 // The Client type encapsulates operations with an OSS region.
32 type Client struct {
33 AccessKeyId string
34 AccessKeySecret string
35 SecurityToken string
36 Region Region
37 Internal bool
38 Secure bool
39 ConnectTimeout time.Duration
40
41 endpoint string
42 debug bool
43 }
44
45 // The Bucket type encapsulates operations with an bucket.
46 type Bucket struct {
47 *Client
48 Name string
49 }
50
51 // The Owner type represents the owner of the object in an bucket.
52 type Owner struct {
53 ID string
54 DisplayName string
55 }
56
57 // Options struct
58 //
59 type Options struct {
60 ServerSideEncryption bool
61 Meta map[string][]string
62 ContentEncoding string
63 CacheControl string
64 ContentMD5 string
65 ContentDisposition string
66 //Range string
67 //Expires int
68 }
69
70 type CopyOptions struct {
71 Headers http.Header
72 CopySourceOptions string
73 MetadataDirective string
74 //ContentType string
75 }
76
77 // CopyObjectResult is the output from a Copy request
78 type CopyObjectResult struct {
79 ETag string
80 LastModified string
81 }
82
83 var attempts = util.AttemptStrategy{
84 Min: 5,
85 Total: 5 * time.Second,
86 Delay: 200 * time.Millisecond,
87 }
88
89 // NewOSSClient creates a new OSS.
90
91 func NewOSSClientForAssumeRole(region Region, internal bool, accessKeyId string, accessKeySecret string, securityToken string, secure bool) *Client {
92 return &Client{
93 AccessKeyId: accessKeyId,
94 AccessKeySecret: accessKeySecret,
95 SecurityToken: securityToken,
96 Region: region,
97 Internal: internal,
98 debug: false,
99 Secure: secure,
100 }
101 }
102
103 func NewOSSClient(region Region, internal bool, accessKeyId string, accessKeySecret string, secure bool) *Client {
104 return &Client{
105 AccessKeyId: accessKeyId,
106 AccessKeySecret: accessKeySecret,
107 Region: region,
108 Internal: internal,
109 debug: false,
110 Secure: secure,
111 }
112 }
113
114 // SetDebug sets debug mode to log the request/response message
115 func (client *Client) SetDebug(debug bool) {
116 client.debug = debug
117 }
118
119 // Bucket returns a Bucket with the given name.
120 func (client *Client) Bucket(name string) *Bucket {
121 name = strings.ToLower(name)
122 return &Bucket{
123 Client: client,
124 Name: name,
125 }
126 }
127
128 type BucketInfo struct {
129 Name string
130 CreationDate string
131 ExtranetEndpoint string
132 IntranetEndpoint string
133 Location string
134 Grant string `xml:"AccessControlList>Grant"`
135 }
136
137 type GetServiceResp struct {
138 Owner Owner
139 Buckets []BucketInfo `xml:">Bucket"`
140 }
141
142 type GetBucketInfoResp struct {
143 Bucket BucketInfo
144 }
145
146 // GetService gets a list of all buckets owned by an account.
147 func (client *Client) GetService() (*GetServiceResp, error) {
148 bucket := client.Bucket("")
149
150 r, err := bucket.Get("")
151 if err != nil {
152 return nil, err
153 }
154
155 // Parse the XML response.
156 var resp GetServiceResp
157 if err = xml.Unmarshal(r, &resp); err != nil {
158 return nil, err
159 }
160
161 return &resp, nil
162 }
163
164 type ACL string
165
166 const (
167 Private = ACL("private")
168 PublicRead = ACL("public-read")
169 PublicReadWrite = ACL("public-read-write")
170 AuthenticatedRead = ACL("authenticated-read")
171 BucketOwnerRead = ACL("bucket-owner-read")
172 BucketOwnerFull = ACL("bucket-owner-full-control")
173 )
174
175 var createBucketConfiguration = `<CreateBucketConfiguration>
176 <LocationConstraint>%s</LocationConstraint>
177 </CreateBucketConfiguration>`
178
179 // locationConstraint returns an io.Reader specifying a LocationConstraint if
180 // required for the region.
181 func (client *Client) locationConstraint() io.Reader {
182 constraint := fmt.Sprintf(createBucketConfiguration, client.Region)
183 return strings.NewReader(constraint)
184 }
185
186 // override default endpoint
187 func (client *Client) SetEndpoint(endpoint string) {
188 // TODO check endpoint
189 client.endpoint = endpoint
190 }
191
192 // Info query basic information about the bucket
193 //
194 // You can read doc at https://help.aliyun.com/document_detail/31968.html
195 func (b *Bucket) Info() (BucketInfo, error) {
196 params := make(url.Values)
197 params.Set("bucketInfo", "")
198 r, err := b.GetWithParams("/", params)
199
200 if err != nil {
201 return BucketInfo{}, err
202 }
203
204 // Parse the XML response.
205 var resp GetBucketInfoResp
206 if err = xml.Unmarshal(r, &resp); err != nil {
207 return BucketInfo{}, err
208 }
209
210 return resp.Bucket, nil
211 }
212
213 // PutBucket creates a new bucket.
214 //
215 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/bucket&PutBucket
216 func (b *Bucket) PutBucket(perm ACL) error {
217 headers := make(http.Header)
218 if perm != "" {
219 headers.Set("x-oss-acl", string(perm))
220 }
221 req := &request{
222 method: "PUT",
223 bucket: b.Name,
224 path: "/",
225 headers: headers,
226 payload: b.Client.locationConstraint(),
227 }
228 return b.Client.query(req, nil)
229 }
230
231 // DelBucket removes an existing bucket. All objects in the bucket must
232 // be removed before the bucket itself can be removed.
233 //
234 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/bucket&DeleteBucket
235 func (b *Bucket) DelBucket() (err error) {
236 for attempt := attempts.Start(); attempt.Next(); {
237 req := &request{
238 method: "DELETE",
239 bucket: b.Name,
240 path: "/",
241 }
242
243 err = b.Client.query(req, nil)
244 if !shouldRetry(err) {
245 break
246 }
247 }
248 return err
249 }
250
251 // Get retrieves an object from an bucket.
252 //
253 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/object&GetObject
254 func (b *Bucket) Get(path string) (data []byte, err error) {
255 body, err := b.GetReader(path)
256 if err != nil {
257 return nil, err
258 }
259 data, err = ioutil.ReadAll(body)
260 body.Close()
261 return data, err
262 }
263
264 // GetReader retrieves an object from an bucket,
265 // returning the body of the HTTP response.
266 // It is the caller's responsibility to call Close on rc when
267 // finished reading.
268 func (b *Bucket) GetReader(path string) (rc io.ReadCloser, err error) {
269 resp, err := b.GetResponse(path)
270 if resp != nil {
271 return resp.Body, err
272 }
273 return nil, err
274 }
275
276 // GetResponse retrieves an object from an bucket,
277 // returning the HTTP response.
278 // It is the caller's responsibility to call Close on rc when
279 // finished reading
280 func (b *Bucket) GetResponse(path string) (resp *http.Response, err error) {
281 return b.GetResponseWithHeaders(path, make(http.Header))
282 }
283
284 // GetResponseWithHeaders retrieves an object from an bucket
285 // Accepts custom headers to be sent as the second parameter
286 // returning the body of the HTTP response.
287 // It is the caller's responsibility to call Close on rc when
288 // finished reading
289 func (b *Bucket) GetResponseWithHeaders(path string, headers http.Header) (resp *http.Response, err error) {
290 for attempt := attempts.Start(); attempt.Next(); {
291 req := &request{
292 bucket: b.Name,
293 path: path,
294 headers: headers,
295 }
296 err = b.Client.prepare(req)
297 if err != nil {
298 return nil, err
299 }
300
301 resp, err := b.Client.run(req, nil)
302 if shouldRetry(err) && attempt.HasNext() {
303 continue
304 }
305 if err != nil {
306 return nil, err
307 }
308 return resp, nil
309 }
310 panic("unreachable")
311 }
312
313 // Get retrieves an object from an bucket.
314 func (b *Bucket) GetWithParams(path string, params url.Values) (data []byte, err error) {
315 resp, err := b.GetResponseWithParamsAndHeaders(path, params, nil)
316 if err != nil {
317 return nil, err
318 }
319 data, err = ioutil.ReadAll(resp.Body)
320 resp.Body.Close()
321 return data, err
322 }
323
324 func (b *Bucket) GetResponseWithParamsAndHeaders(path string, params url.Values, headers http.Header) (resp *http.Response, err error) {
325 for attempt := attempts.Start(); attempt.Next(); {
326 req := &request{
327 bucket: b.Name,
328 path: path,
329 params: params,
330 headers: headers,
331 }
332 err = b.Client.prepare(req)
333 if err != nil {
334 return nil, err
335 }
336
337 resp, err := b.Client.run(req, nil)
338 if shouldRetry(err) && attempt.HasNext() {
339 continue
340 }
341 if err != nil {
342 return nil, err
343 }
344 return resp, nil
345 }
346 panic("unreachable")
347 }
348
349 // Exists checks whether or not an object exists on an bucket using a HEAD request.
350 func (b *Bucket) Exists(path string) (exists bool, err error) {
351 for attempt := attempts.Start(); attempt.Next(); {
352 req := &request{
353 method: "HEAD",
354 bucket: b.Name,
355 path: path,
356 }
357 err = b.Client.prepare(req)
358 if err != nil {
359 return
360 }
361
362 resp, err := b.Client.run(req, nil)
363
364 if shouldRetry(err) && attempt.HasNext() {
365 continue
366 }
367
368 if err != nil {
369 // We can treat a 403 or 404 as non existence
370 if e, ok := err.(*Error); ok && (e.StatusCode == 403 || e.StatusCode == 404) {
371 return false, nil
372 }
373 return false, err
374 }
375
376 if resp.StatusCode/100 == 2 {
377 exists = true
378 }
379 if resp.Body != nil {
380 resp.Body.Close()
381 }
382 return exists, err
383 }
384 return false, fmt.Errorf("OSS Currently Unreachable")
385 }
386
387 // Head HEADs an object in the bucket, returns the response with
388 //
389 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/object&HeadObject
390 func (b *Bucket) Head(path string, headers http.Header) (*http.Response, error) {
391
392 for attempt := attempts.Start(); attempt.Next(); {
393 req := &request{
394 method: "HEAD",
395 bucket: b.Name,
396 path: path,
397 headers: headers,
398 }
399 err := b.Client.prepare(req)
400 if err != nil {
401 return nil, err
402 }
403
404 resp, err := b.Client.run(req, nil)
405 if shouldRetry(err) && attempt.HasNext() {
406 continue
407 }
408 if err != nil {
409 return nil, err
410 }
411 if resp != nil && resp.Body != nil {
412 resp.Body.Close()
413 }
414 return resp, err
415 }
416 return nil, fmt.Errorf("OSS Currently Unreachable")
417 }
418
419 // Put inserts an object into the bucket.
420 //
421 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/object&PutObject
422 func (b *Bucket) Put(path string, data []byte, contType string, perm ACL, options Options) error {
423 body := bytes.NewBuffer(data)
424 return b.PutReader(path, body, int64(len(data)), contType, perm, options)
425 }
426
427 // PutCopy puts a copy of an object given by the key path into bucket b using b.Path as the target key
428 //
429 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/object&CopyObject
430 func (b *Bucket) PutCopy(path string, perm ACL, options CopyOptions, source string) (*CopyObjectResult, error) {
431 headers := make(http.Header)
432
433 headers.Set("x-oss-object-acl", string(perm))
434 headers.Set("x-oss-copy-source", source)
435
436 options.addHeaders(headers)
437 req := &request{
438 method: "PUT",
439 bucket: b.Name,
440 path: path,
441 headers: headers,
442 timeout: 5 * time.Minute,
443 }
444 resp := &CopyObjectResult{}
445 err := b.Client.query(req, resp)
446 if err != nil {
447 return resp, err
448 }
449 return resp, nil
450 }
451
452 // PutReader inserts an object into the bucket by consuming data
453 // from r until EOF.
454 func (b *Bucket) PutReader(path string, r io.Reader, length int64, contType string, perm ACL, options Options) error {
455 headers := make(http.Header)
456 headers.Set("Content-Length", strconv.FormatInt(length, 10))
457 headers.Set("Content-Type", contType)
458 headers.Set("x-oss-object-acl", string(perm))
459
460 options.addHeaders(headers)
461 req := &request{
462 method: "PUT",
463 bucket: b.Name,
464 path: path,
465 headers: headers,
466 payload: r,
467 }
468 return b.Client.query(req, nil)
469 }
470
471 // PutFile creates/updates object with file
472 func (b *Bucket) PutFile(path string, file *os.File, perm ACL, options Options) error {
473 var contentType string
474 if dotPos := strings.LastIndex(file.Name(), "."); dotPos == -1 {
475 contentType = DefaultContentType
476 } else {
477 if mimeType := mime.TypeByExtension(file.Name()[dotPos:]); mimeType == "" {
478 contentType = DefaultContentType
479 } else {
480 contentType = mimeType
481 }
482 }
483 stats, err := file.Stat()
484 if err != nil {
485 log.Printf("Unable to read file %s stats.\n", file.Name())
486 return err
487 }
488
489 return b.PutReader(path, file, stats.Size(), contentType, perm, options)
490 }
491
492 // addHeaders adds o's specified fields to headers
493 func (o Options) addHeaders(headers http.Header) {
494 if o.ServerSideEncryption {
495 headers.Set("x-oss-server-side-encryption", "AES256")
496 }
497 if len(o.ContentEncoding) != 0 {
498 headers.Set("Content-Encoding", o.ContentEncoding)
499 }
500 if len(o.CacheControl) != 0 {
501 headers.Set("Cache-Control", o.CacheControl)
502 }
503 if len(o.ContentMD5) != 0 {
504 headers.Set("Content-MD5", o.ContentMD5)
505 }
506 if len(o.ContentDisposition) != 0 {
507 headers.Set("Content-Disposition", o.ContentDisposition)
508 }
509
510 for k, v := range o.Meta {
511 for _, mv := range v {
512 headers.Add("x-oss-meta-"+k, mv)
513 }
514 }
515 }
516
517 // addHeaders adds o's specified fields to headers
518 func (o CopyOptions) addHeaders(headers http.Header) {
519 if len(o.MetadataDirective) != 0 {
520 headers.Set("x-oss-metadata-directive", o.MetadataDirective)
521 }
522 if len(o.CopySourceOptions) != 0 {
523 headers.Set("x-oss-copy-source-range", o.CopySourceOptions)
524 }
525 if o.Headers != nil {
526 for k, v := range o.Headers {
527 newSlice := make([]string, len(v))
528 copy(newSlice, v)
529 headers[k] = newSlice
530 }
531 }
532 }
533
534 func makeXMLBuffer(doc []byte) *bytes.Buffer {
535 buf := new(bytes.Buffer)
536 buf.WriteString(xml.Header)
537 buf.Write(doc)
538 return buf
539 }
540
541 type IndexDocument struct {
542 Suffix string `xml:"Suffix"`
543 }
544
545 type ErrorDocument struct {
546 Key string `xml:"Key"`
547 }
548
549 type RoutingRule struct {
550 ConditionKeyPrefixEquals string `xml:"Condition>KeyPrefixEquals"`
551 RedirectReplaceKeyPrefixWith string `xml:"Redirect>ReplaceKeyPrefixWith,omitempty"`
552 RedirectReplaceKeyWith string `xml:"Redirect>ReplaceKeyWith,omitempty"`
553 }
554
555 type RedirectAllRequestsTo struct {
556 HostName string `xml:"HostName"`
557 Protocol string `xml:"Protocol,omitempty"`
558 }
559
560 type WebsiteConfiguration struct {
561 XMLName xml.Name `xml:"http://doc.oss-cn-hangzhou.aliyuncs.com WebsiteConfiguration"`
562 IndexDocument *IndexDocument `xml:"IndexDocument,omitempty"`
563 ErrorDocument *ErrorDocument `xml:"ErrorDocument,omitempty"`
564 RoutingRules *[]RoutingRule `xml:"RoutingRules>RoutingRule,omitempty"`
565 RedirectAllRequestsTo *RedirectAllRequestsTo `xml:"RedirectAllRequestsTo,omitempty"`
566 }
567
568 // PutBucketWebsite configures a bucket as a website.
569 //
570 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/bucket&PutBucketWebsite
571 func (b *Bucket) PutBucketWebsite(configuration WebsiteConfiguration) error {
572 doc, err := xml.Marshal(configuration)
573 if err != nil {
574 return err
575 }
576
577 buf := makeXMLBuffer(doc)
578
579 return b.PutBucketSubresource("website", buf, int64(buf.Len()))
580 }
581
582 func (b *Bucket) PutBucketSubresource(subresource string, r io.Reader, length int64) error {
583 headers := make(http.Header)
584 headers.Set("Content-Length", strconv.FormatInt(length, 10))
585
586 req := &request{
587 path: "/",
588 method: "PUT",
589 bucket: b.Name,
590 headers: headers,
591 payload: r,
592 params: url.Values{subresource: {""}},
593 }
594
595 return b.Client.query(req, nil)
596 }
597
598 // Del removes an object from the bucket.
599 //
600 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/object&DeleteObject
601 func (b *Bucket) Del(path string) error {
602 req := &request{
603 method: "DELETE",
604 bucket: b.Name,
605 path: path,
606 }
607 return b.Client.query(req, nil)
608 }
609
610 type Delete struct {
611 Quiet bool `xml:"Quiet,omitempty"`
612 Objects []Object `xml:"Object"`
613 }
614
615 type Object struct {
616 Key string `xml:"Key"`
617 VersionId string `xml:"VersionId,omitempty"`
618 }
619
620 // DelMulti removes up to 1000 objects from the bucket.
621 //
622 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/object&DeleteMultipleObjects
623 func (b *Bucket) DelMulti(objects Delete) error {
624 doc, err := xml.Marshal(objects)
625 if err != nil {
626 return err
627 }
628
629 buf := makeXMLBuffer(doc)
630 digest := md5.New()
631 size, err := digest.Write(buf.Bytes())
632 if err != nil {
633 return err
634 }
635
636 headers := make(http.Header)
637 headers.Set("Content-Length", strconv.FormatInt(int64(size), 10))
638 headers.Set("Content-MD5", base64.StdEncoding.EncodeToString(digest.Sum(nil)))
639 headers.Set("Content-Type", "text/xml")
640
641 req := &request{
642 path: "/",
643 method: "POST",
644 params: url.Values{"delete": {""}},
645 bucket: b.Name,
646 headers: headers,
647 payload: buf,
648 }
649
650 return b.Client.query(req, nil)
651 }
652
653 // The ListResp type holds the results of a List bucket operation.
654 type ListResp struct {
655 Name string
656 Prefix string
657 Delimiter string
658 Marker string
659 MaxKeys int
660 // IsTruncated is true if the results have been truncated because
661 // there are more keys and prefixes than can fit in MaxKeys.
662 // N.B. this is the opposite sense to that documented (incorrectly) in
663 // http://goo.gl/YjQTc
664 IsTruncated bool
665 Contents []Key
666 CommonPrefixes []string `xml:">Prefix"`
667 // if IsTruncated is true, pass NextMarker as marker argument to List()
668 // to get the next set of keys
669 NextMarker string
670 }
671
672 // The Key type represents an item stored in an bucket.
673 type Key struct {
674 Key string
675 LastModified string
676 Type string
677 Size int64
678 // ETag gives the hex-encoded MD5 sum of the contents,
679 // surrounded with double-quotes.
680 ETag string
681 StorageClass string
682 Owner Owner
683 }
684
685 // List returns information about objects in an bucket.
686 //
687 // The prefix parameter limits the response to keys that begin with the
688 // specified prefix.
689 //
690 // The delim parameter causes the response to group all of the keys that
691 // share a common prefix up to the next delimiter in a single entry within
692 // the CommonPrefixes field. You can use delimiters to separate a bucket
693 // into different groupings of keys, similar to how folders would work.
694 //
695 // The marker parameter specifies the key to start with when listing objects
696 // in a bucket. OSS lists objects in alphabetical order and
697 // will return keys alphabetically greater than the marker.
698 //
699 // The max parameter specifies how many keys + common prefixes to return in
700 // the response, at most 1000. The default is 100.
701 //
702 // For example, given these keys in a bucket:
703 //
704 // index.html
705 // index2.html
706 // photos/2006/January/sample.jpg
707 // photos/2006/February/sample2.jpg
708 // photos/2006/February/sample3.jpg
709 // photos/2006/February/sample4.jpg
710 //
711 // Listing this bucket with delimiter set to "/" would yield the
712 // following result:
713 //
714 // &ListResp{
715 // Name: "sample-bucket",
716 // MaxKeys: 1000,
717 // Delimiter: "/",
718 // Contents: []Key{
719 // {Key: "index.html", "index2.html"},
720 // },
721 // CommonPrefixes: []string{
722 // "photos/",
723 // },
724 // }
725 //
726 // Listing the same bucket with delimiter set to "/" and prefix set to
727 // "photos/2006/" would yield the following result:
728 //
729 // &ListResp{
730 // Name: "sample-bucket",
731 // MaxKeys: 1000,
732 // Delimiter: "/",
733 // Prefix: "photos/2006/",
734 // CommonPrefixes: []string{
735 // "photos/2006/February/",
736 // "photos/2006/January/",
737 // },
738 // }
739 //
740 //
741 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/bucket&GetBucket
742 func (b *Bucket) List(prefix, delim, marker string, max int) (result *ListResp, err error) {
743 params := make(url.Values)
744 params.Set("prefix", prefix)
745 params.Set("delimiter", delim)
746 params.Set("marker", marker)
747 if max != 0 {
748 params.Set("max-keys", strconv.FormatInt(int64(max), 10))
749 }
750 result = &ListResp{}
751 for attempt := attempts.Start(); attempt.Next(); {
752 req := &request{
753 bucket: b.Name,
754 params: params,
755 }
756 err = b.Client.query(req, result)
757 if !shouldRetry(err) {
758 break
759 }
760 }
761 if err != nil {
762 return nil, err
763 }
764 // if NextMarker is not returned, it should be set to the name of last key,
765 // so let's do it so that each caller doesn't have to
766 if result.IsTruncated && result.NextMarker == "" {
767 n := len(result.Contents)
768 if n > 0 {
769 result.NextMarker = result.Contents[n-1].Key
770 }
771 }
772 return result, nil
773 }
774
775 type GetLocationResp struct {
776 Location string `xml:",innerxml"`
777 }
778
779 func (b *Bucket) Location() (string, error) {
780 params := make(url.Values)
781 params.Set("location", "")
782 r, err := b.GetWithParams("/", params)
783
784 if err != nil {
785 return "", err
786 }
787
788 // Parse the XML response.
789 var resp GetLocationResp
790 if err = xml.Unmarshal(r, &resp); err != nil {
791 return "", err
792 }
793
794 if resp.Location == "" {
795 return string(Hangzhou), nil
796 }
797 return resp.Location, nil
798 }
799
800 func (b *Bucket) Path(path string) string {
801 if !strings.HasPrefix(path, "/") {
802 path = "/" + path
803 }
804 return "/" + b.Name + path
805 }
806
807 // URL returns a non-signed URL that allows retriving the
808 // object at path. It only works if the object is publicly
809 // readable (see SignedURL).
810 func (b *Bucket) URL(path string) string {
811 req := &request{
812 bucket: b.Name,
813 path: path,
814 }
815 err := b.Client.prepare(req)
816 if err != nil {
817 panic(err)
818 }
819 u, err := req.url()
820 if err != nil {
821 panic(err)
822 }
823 u.RawQuery = ""
824 return u.String()
825 }
826
827 // SignedURL returns a signed URL that allows anyone holding the URL
828 // to retrieve the object at path. The signature is valid until expires.
829 func (b *Bucket) SignedURL(path string, expires time.Time) string {
830 return b.SignedURLWithArgs(path, expires, nil, nil)
831 }
832
833 // SignedURLWithArgs returns a signed URL that allows anyone holding the URL
834 // to retrieve the object at path. The signature is valid until expires.
835 func (b *Bucket) SignedURLWithArgs(path string, expires time.Time, params url.Values, headers http.Header) string {
836 return b.SignedURLWithMethod("GET", path, expires, params, headers)
837 }
838
839 // SignedURLWithMethod returns a signed URL that allows anyone holding the URL
840 // to either retrieve the object at path or make a HEAD request against it. The signature is valid until expires.
841 func (b *Bucket) SignedURLWithMethod(method, path string, expires time.Time, params url.Values, headers http.Header) string {
842 var uv = url.Values{}
843
844 if params != nil {
845 uv = params
846 }
847
848 uv.Set("Expires", strconv.FormatInt(expires.Unix(), 10))
849 uv.Set("OSSAccessKeyId", b.AccessKeyId)
850
851 req := &request{
852 method: method,
853 bucket: b.Name,
854 path: path,
855 params: uv,
856 headers: headers,
857 }
858 err := b.Client.prepare(req)
859 if err != nil {
860 panic(err)
861 }
862 u, err := req.url()
863 if err != nil {
864 panic(err)
865 }
866
867 return u.String()
868 }
869
870 // UploadSignedURL returns a signed URL that allows anyone holding the URL
871 // to upload the object at path. The signature is valid until expires.
872 // contenttype is a string like image/png
873 // name is the resource name in OSS terminology like images/ali.png [obviously excluding the bucket name itself]
874 func (b *Bucket) UploadSignedURL(name, method, contentType string, expires time.Time) string {
875 //TODO TESTING
876 expireDate := expires.Unix()
877 if method != "POST" {
878 method = "PUT"
879 }
880
881 tokenData := ""
882
883 stringToSign := method + "\n\n" + contentType + "\n" + strconv.FormatInt(expireDate, 10) + "\n" + tokenData + "/" + path.Join(b.Name, name)
884 secretKey := b.AccessKeySecret
885 accessId := b.AccessKeyId
886 mac := hmac.New(sha1.New, []byte(secretKey))
887 mac.Write([]byte(stringToSign))
888 macsum := mac.Sum(nil)
889 signature := base64.StdEncoding.EncodeToString(macsum)
890 signature = strings.TrimSpace(signature)
891
892 signedurl, err := url.Parse(b.Region.GetEndpoint(b.Internal, b.Name, b.Secure))
893 if err != nil {
894 log.Println("ERROR sining url for OSS upload", err)
895 return ""
896 }
897 signedurl.Path = name
898 params := url.Values{}
899 params.Add("OSSAccessKeyId", accessId)
900 params.Add("Expires", strconv.FormatInt(expireDate, 10))
901 params.Add("Signature", signature)
902
903 signedurl.RawQuery = params.Encode()
904 return signedurl.String()
905 }
906
907 // PostFormArgsEx returns the action and input fields needed to allow anonymous
908 // uploads to a bucket within the expiration limit
909 // Additional conditions can be specified with conds
910 func (b *Bucket) PostFormArgsEx(path string, expires time.Time, redirect string, conds []string) (action string, fields map[string]string) {
911 conditions := []string{}
912 fields = map[string]string{
913 "AWSAccessKeyId": b.AccessKeyId,
914 "key": path,
915 }
916
917 if conds != nil {
918 conditions = append(conditions, conds...)
919 }
920
921 conditions = append(conditions, fmt.Sprintf("{\"key\": \"%s\"}", path))
922 conditions = append(conditions, fmt.Sprintf("{\"bucket\": \"%s\"}", b.Name))
923 if redirect != "" {
924 conditions = append(conditions, fmt.Sprintf("{\"success_action_redirect\": \"%s\"}", redirect))
925 fields["success_action_redirect"] = redirect
926 }
927
928 vExpiration := expires.Format("2006-01-02T15:04:05Z")
929 vConditions := strings.Join(conditions, ",")
930 policy := fmt.Sprintf("{\"expiration\": \"%s\", \"conditions\": [%s]}", vExpiration, vConditions)
931 policy64 := base64.StdEncoding.EncodeToString([]byte(policy))
932 fields["policy"] = policy64
933
934 signer := hmac.New(sha1.New, []byte(b.AccessKeySecret))
935 signer.Write([]byte(policy64))
936 fields["signature"] = base64.StdEncoding.EncodeToString(signer.Sum(nil))
937
938 action = fmt.Sprintf("%s/%s/", b.Client.Region, b.Name)
939 return
940 }
941
942 // PostFormArgs returns the action and input fields needed to allow anonymous
943 // uploads to a bucket within the expiration limit
944 func (b *Bucket) PostFormArgs(path string, expires time.Time, redirect string) (action string, fields map[string]string) {
945 return b.PostFormArgsEx(path, expires, redirect, nil)
946 }
947
948 type request struct {
949 method string
950 bucket string
951 path string
952 params url.Values
953 headers http.Header
954 baseurl string
955 payload io.Reader
956 prepared bool
957 timeout time.Duration
958 }
959
960 func (req *request) url() (*url.URL, error) {
961 u, err := url.Parse(req.baseurl)
962 if err != nil {
963 return nil, fmt.Errorf("bad OSS endpoint URL %q: %v", req.baseurl, err)
964 }
965 u.RawQuery = req.params.Encode()
966 u.Path = req.path
967 return u, nil
968 }
969
970 // query prepares and runs the req request.
971 // If resp is not nil, the XML data contained in the response
972 // body will be unmarshalled on it.
973 func (client *Client) query(req *request, resp interface{}) error {
974 err := client.prepare(req)
975 if err != nil {
976 return err
977 }
978 r, err := client.run(req, resp)
979 if r != nil && r.Body != nil {
980 r.Body.Close()
981 }
982 return err
983 }
984
985 // Sets baseurl on req from bucket name and the region endpoint
986 func (client *Client) setBaseURL(req *request) error {
987
988 if client.endpoint == "" {
989 req.baseurl = client.Region.GetEndpoint(client.Internal, req.bucket, client.Secure)
990 } else {
991 req.baseurl = fmt.Sprintf("%s://%s", getProtocol(client.Secure), client.endpoint)
992 }
993
994 return nil
995 }
996
997 // partiallyEscapedPath partially escapes the OSS path allowing for all OSS REST API calls.
998 //
999 // Some commands including:
1000 // GET Bucket acl http://goo.gl/aoXflF
1001 // GET Bucket cors http://goo.gl/UlmBdx
1002 // GET Bucket lifecycle http://goo.gl/8Fme7M
1003 // GET Bucket policy http://goo.gl/ClXIo3
1004 // GET Bucket location http://goo.gl/5lh8RD
1005 // GET Bucket Logging http://goo.gl/sZ5ckF
1006 // GET Bucket notification http://goo.gl/qSSZKD
1007 // GET Bucket tagging http://goo.gl/QRvxnM
1008 // require the first character after the bucket name in the path to be a literal '?' and
1009 // not the escaped hex representation '%3F'.
1010 func partiallyEscapedPath(path string) string {
1011 pathEscapedAndSplit := strings.Split((&url.URL{Path: path}).String(), "/")
1012 if len(pathEscapedAndSplit) >= 3 {
1013 if len(pathEscapedAndSplit[2]) >= 3 {
1014 // Check for the one "?" that should not be escaped.
1015 if pathEscapedAndSplit[2][0:3] == "%3F" {
1016 pathEscapedAndSplit[2] = "?" + pathEscapedAndSplit[2][3:]
1017 }
1018 }
1019 }
1020 return strings.Replace(strings.Join(pathEscapedAndSplit, "/"), "+", "%2B", -1)
1021 }
1022
1023 // prepare sets up req to be delivered to OSS.
1024 func (client *Client) prepare(req *request) error {
1025 // Copy so they can be mutated without affecting on retries.
1026 headers := copyHeader(req.headers)
1027 if len(client.SecurityToken) != 0 {
1028 headers.Set("x-oss-security-token", client.SecurityToken)
1029 }
1030
1031 params := make(url.Values)
1032
1033 for k, v := range req.params {
1034 params[k] = v
1035 }
1036
1037 req.params = params
1038 req.headers = headers
1039
1040 if !req.prepared {
1041 req.prepared = true
1042 if req.method == "" {
1043 req.method = "GET"
1044 }
1045
1046 if !strings.HasPrefix(req.path, "/") {
1047 req.path = "/" + req.path
1048 }
1049
1050 err := client.setBaseURL(req)
1051 if err != nil {
1052 return err
1053 }
1054 }
1055
1056 req.headers.Set("Date", util.GetGMTime())
1057 client.signRequest(req)
1058
1059 return nil
1060 }
1061
1062 // Prepares an *http.Request for doHttpRequest
1063 func (client *Client) setupHttpRequest(req *request) (*http.Request, error) {
1064 // Copy so that signing the http request will not mutate it
1065
1066 u, err := req.url()
1067 if err != nil {
1068 return nil, err
1069 }
1070 u.Opaque = fmt.Sprintf("//%s%s", u.Host, partiallyEscapedPath(u.Path))
1071
1072 hreq := http.Request{
1073 URL: u,
1074 Method: req.method,
1075 ProtoMajor: 1,
1076 ProtoMinor: 1,
1077 Close: true,
1078 Header: req.headers,
1079 Form: req.params,
1080 }
1081
1082 hreq.Header.Set("X-SDK-Client", `AliyunGO/`+common.Version)
1083
1084 contentLength := req.headers.Get("Content-Length")
1085
1086 if contentLength != "" {
1087 hreq.ContentLength, _ = strconv.ParseInt(contentLength, 10, 64)
1088 req.headers.Del("Content-Length")
1089 }
1090
1091 if req.payload != nil {
1092 hreq.Body = ioutil.NopCloser(req.payload)
1093 }
1094
1095 return &hreq, nil
1096 }
1097
1098 // doHttpRequest sends hreq and returns the http response from the server.
1099 // If resp is not nil, the XML data contained in the response
1100 // body will be unmarshalled on it.
1101 func (client *Client) doHttpRequest(c *http.Client, hreq *http.Request, resp interface{}) (*http.Response, error) {
1102
1103 if client.debug {
1104 log.Printf("%s %s ...\n", hreq.Method, hreq.URL.String())
1105 }
1106 hresp, err := c.Do(hreq)
1107 if err != nil {
1108 return nil, err
1109 }
1110 if client.debug {
1111 log.Printf("%s %s %d\n", hreq.Method, hreq.URL.String(), hresp.StatusCode)
1112 contentType := hresp.Header.Get("Content-Type")
1113 if contentType == "application/xml" || contentType == "text/xml" {
1114 dump, _ := httputil.DumpResponse(hresp, true)
1115 log.Printf("%s\n", dump)
1116 } else {
1117 log.Printf("Response Content-Type: %s\n", contentType)
1118 }
1119 }
1120 if hresp.StatusCode != 200 && hresp.StatusCode != 204 && hresp.StatusCode != 206 {
1121 return nil, client.buildError(hresp)
1122 }
1123 if resp != nil {
1124 err = xml.NewDecoder(hresp.Body).Decode(resp)
1125 hresp.Body.Close()
1126
1127 if client.debug {
1128 log.Printf("aliyungo.oss> decoded xml into %#v", resp)
1129 }
1130
1131 }
1132 return hresp, err
1133 }
1134
1135 // run sends req and returns the http response from the server.
1136 // If resp is not nil, the XML data contained in the response
1137 // body will be unmarshalled on it.
1138 func (client *Client) run(req *request, resp interface{}) (*http.Response, error) {
1139 if client.debug {
1140 log.Printf("Running OSS request: %#v", req)
1141 }
1142
1143 hreq, err := client.setupHttpRequest(req)
1144 if err != nil {
1145 return nil, err
1146 }
1147
1148 c := &http.Client{
1149 Transport: &http.Transport{
1150 Dial: func(netw, addr string) (c net.Conn, err error) {
1151 if client.ConnectTimeout > 0 {
1152 c, err = net.DialTimeout(netw, addr, client.ConnectTimeout)
1153 } else {
1154 c, err = net.Dial(netw, addr)
1155 }
1156 if err != nil {
1157 return
1158 }
1159 return
1160 },
1161 Proxy: http.ProxyFromEnvironment,
1162 },
1163 Timeout: req.timeout,
1164 }
1165
1166 return client.doHttpRequest(c, hreq, resp)
1167 }
1168
1169 // Error represents an error in an operation with OSS.
1170 type Error struct {
1171 StatusCode int // HTTP status code (200, 403, ...)
1172 Code string // OSS error code ("UnsupportedOperation", ...)
1173 Message string // The human-oriented error message
1174 BucketName string
1175 RequestId string
1176 HostId string
1177 }
1178
1179 func (e *Error) Error() string {
1180 return fmt.Sprintf("Aliyun API Error: RequestId: %s Status Code: %d Code: %s Message: %s", e.RequestId, e.StatusCode, e.Code, e.Message)
1181 }
1182
1183 func (client *Client) buildError(r *http.Response) error {
1184 if client.debug {
1185 log.Printf("got error (status code %v)", r.StatusCode)
1186 data, err := ioutil.ReadAll(r.Body)
1187 if err != nil {
1188 log.Printf("\tread error: %v", err)
1189 } else {
1190 log.Printf("\tdata:\n%s\n\n", data)
1191 }
1192 r.Body = ioutil.NopCloser(bytes.NewBuffer(data))
1193 }
1194
1195 err := Error{}
1196 // TODO return error if Unmarshal fails?
1197 xml.NewDecoder(r.Body).Decode(&err)
1198 r.Body.Close()
1199 err.StatusCode = r.StatusCode
1200 if err.Message == "" {
1201 err.Message = r.Status
1202 }
1203 if client.debug {
1204 log.Printf("err: %#v\n", err)
1205 }
1206 return &err
1207 }
1208
1209 type TimeoutError interface {
1210 error
1211 Timeout() bool // Is the error a timeout?
1212 }
1213
1214 func shouldRetry(err error) bool {
1215 if err == nil {
1216 return false
1217 }
1218
1219 _, ok := err.(TimeoutError)
1220 if ok {
1221 return true
1222 }
1223
1224 switch err {
1225 case io.ErrUnexpectedEOF, io.EOF:
1226 return true
1227 }
1228 switch e := err.(type) {
1229 case *net.DNSError:
1230 return true
1231 case *net.OpError:
1232 switch e.Op {
1233 case "read", "write":
1234 return true
1235 }
1236 case *url.Error:
1237 // url.Error can be returned either by net/url if a URL cannot be
1238 // parsed, or by net/http if the response is closed before the headers
1239 // are received or parsed correctly. In that later case, e.Op is set to
1240 // the HTTP method name with the first letter uppercased. We don't want
1241 // to retry on POST operations, since those are not idempotent, all the
1242 // other ones should be safe to retry.
1243 switch e.Op {
1244 case "Get", "Put", "Delete", "Head":
1245 return shouldRetry(e.Err)
1246 default:
1247 return false
1248 }
1249 case *Error:
1250 switch e.Code {
1251 case "InternalError", "NoSuchUpload", "NoSuchBucket":
1252 return true
1253 }
1254 }
1255 return false
1256 }
1257
1258 func hasCode(err error, code string) bool {
1259 e, ok := err.(*Error)
1260 return ok && e.Code == code
1261 }
1262
1263 func copyHeader(header http.Header) (newHeader http.Header) {
1264 newHeader = make(http.Header)
1265 for k, v := range header {
1266 newSlice := make([]string, len(v))
1267 copy(newSlice, v)
1268 newHeader[k] = newSlice
1269 }
1270 return
1271 }
1272
1273 type AccessControlPolicy struct {
1274 Owner Owner
1275 Grants []string `xml:"AccessControlList>Grant"`
1276 }
1277
1278 // ACL returns ACL of bucket
1279 //
1280 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/bucket&GetBucketAcl
1281 func (b *Bucket) ACL() (result *AccessControlPolicy, err error) {
1282
1283 params := make(url.Values)
1284 params.Set("acl", "")
1285
1286 r, err := b.GetWithParams("/", params)
1287 if err != nil {
1288 return nil, err
1289 }
1290
1291 // Parse the XML response.
1292 var resp AccessControlPolicy
1293 if err = xml.Unmarshal(r, &resp); err != nil {
1294 return nil, err
1295 }
1296
1297 return &resp, nil
1298 }
1299
1300 func (b *Bucket) GetContentLength(sourcePath string) (int64, error) {
1301 resp, err := b.Head(sourcePath, nil)
1302 if err != nil {
1303 return 0, err
1304 }
1305
1306 currentLength := resp.ContentLength
1307
1308 return currentLength, err
1309 }
1310
1311 func (b *Bucket) CopyLargeFile(sourcePath string, destPath string, contentType string, perm ACL, options Options) error {
1312 return b.CopyLargeFileInParallel(sourcePath, destPath, contentType, perm, options, 1)
1313 }
1314
1315 const defaultChunkSize = int64(128 * 1024 * 1024) //128MB
1316 const maxCopytSize = int64(128 * 1024 * 1024) //128MB
1317
1318 // Copy large file in the same bucket
1319 func (b *Bucket) CopyLargeFileInParallel(sourcePath string, destPath string, contentType string, perm ACL, options Options, maxConcurrency int) error {
1320
1321 if maxConcurrency < 1 {
1322 maxConcurrency = 1
1323 }
1324
1325 currentLength, err := b.GetContentLength(sourcePath)
1326
1327 log.Printf("Parallel Copy large file[size: %d] from %s to %s\n", currentLength, sourcePath, destPath)
1328
1329 if err != nil {
1330 return err
1331 }
1332
1333 if currentLength < maxCopytSize {
1334 _, err := b.PutCopy(destPath, perm,
1335 CopyOptions{},
1336 b.Path(sourcePath))
1337 return err
1338 }
1339
1340 multi, err := b.InitMulti(destPath, contentType, perm, options)
1341 if err != nil {
1342 return err
1343 }
1344
1345 numParts := (currentLength + defaultChunkSize - 1) / defaultChunkSize
1346 completedParts := make([]Part, numParts)
1347
1348 errChan := make(chan error, numParts)
1349 limiter := make(chan struct{}, maxConcurrency)
1350
1351 var start int64 = 0
1352 var to int64 = 0
1353 var partNumber = 0
1354 sourcePathForCopy := b.Path(sourcePath)
1355
1356 for start = 0; start < currentLength; start = to {
1357 to = start + defaultChunkSize
1358 if to > currentLength {
1359 to = currentLength
1360 }
1361 partNumber++
1362
1363 rangeStr := fmt.Sprintf("bytes=%d-%d", start, to-1)
1364 limiter <- struct{}{}
1365 go func(partNumber int, rangeStr string) {
1366 _, part, err := multi.PutPartCopyWithContentLength(partNumber,
1367 CopyOptions{CopySourceOptions: rangeStr},
1368 sourcePathForCopy, currentLength)
1369 if err == nil {
1370 completedParts[partNumber-1] = part
1371 } else {
1372 log.Printf("Unable in PutPartCopy of part %d for %s: %v\n", partNumber, sourcePathForCopy, err)
1373 }
1374 errChan <- err
1375 <-limiter
1376 }(partNumber, rangeStr)
1377 }
1378
1379 fullyCompleted := true
1380 for range completedParts {
1381 err := <-errChan
1382 if err != nil {
1383 fullyCompleted = false
1384 }
1385 }
1386
1387 if fullyCompleted {
1388 err = multi.Complete(completedParts)
1389 } else {
1390 err = multi.Abort()
1391 }
1392
1393 return err
1394 }