您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

1077 行
34 KiB

  1. // Copyright 2014 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package storage
  15. import (
  16. "bytes"
  17. "crypto"
  18. "crypto/rand"
  19. "crypto/rsa"
  20. "crypto/sha256"
  21. "crypto/x509"
  22. "encoding/base64"
  23. "encoding/pem"
  24. "errors"
  25. "fmt"
  26. "io"
  27. "net/http"
  28. "net/url"
  29. "reflect"
  30. "regexp"
  31. "sort"
  32. "strconv"
  33. "strings"
  34. "time"
  35. "unicode/utf8"
  36. "cloud.google.com/go/internal/trace"
  37. "google.golang.org/api/option"
  38. htransport "google.golang.org/api/transport/http"
  39. "cloud.google.com/go/internal/optional"
  40. "cloud.google.com/go/internal/version"
  41. "golang.org/x/net/context"
  42. "google.golang.org/api/googleapi"
  43. raw "google.golang.org/api/storage/v1"
  44. )
  45. var (
  46. ErrBucketNotExist = errors.New("storage: bucket doesn't exist")
  47. ErrObjectNotExist = errors.New("storage: object doesn't exist")
  48. )
  49. const userAgent = "gcloud-golang-storage/20151204"
  50. const (
  51. // ScopeFullControl grants permissions to manage your
  52. // data and permissions in Google Cloud Storage.
  53. ScopeFullControl = raw.DevstorageFullControlScope
  54. // ScopeReadOnly grants permissions to
  55. // view your data in Google Cloud Storage.
  56. ScopeReadOnly = raw.DevstorageReadOnlyScope
  57. // ScopeReadWrite grants permissions to manage your
  58. // data in Google Cloud Storage.
  59. ScopeReadWrite = raw.DevstorageReadWriteScope
  60. )
  61. var xGoogHeader = fmt.Sprintf("gl-go/%s gccl/%s", version.Go(), version.Repo)
  62. func setClientHeader(headers http.Header) {
  63. headers.Set("x-goog-api-client", xGoogHeader)
  64. }
  65. // Client is a client for interacting with Google Cloud Storage.
  66. //
  67. // Clients should be reused instead of created as needed.
  68. // The methods of Client are safe for concurrent use by multiple goroutines.
  69. type Client struct {
  70. hc *http.Client
  71. raw *raw.Service
  72. }
  73. // NewClient creates a new Google Cloud Storage client.
  74. // The default scope is ScopeFullControl. To use a different scope, like ScopeReadOnly, use option.WithScopes.
  75. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
  76. o := []option.ClientOption{
  77. option.WithScopes(ScopeFullControl),
  78. option.WithUserAgent(userAgent),
  79. }
  80. opts = append(o, opts...)
  81. hc, ep, err := htransport.NewClient(ctx, opts...)
  82. if err != nil {
  83. return nil, fmt.Errorf("dialing: %v", err)
  84. }
  85. rawService, err := raw.New(hc)
  86. if err != nil {
  87. return nil, fmt.Errorf("storage client: %v", err)
  88. }
  89. if ep != "" {
  90. rawService.BasePath = ep
  91. }
  92. return &Client{
  93. hc: hc,
  94. raw: rawService,
  95. }, nil
  96. }
  97. // Close closes the Client.
  98. //
  99. // Close need not be called at program exit.
  100. func (c *Client) Close() error {
  101. // Set fields to nil so that subsequent uses
  102. // will panic.
  103. c.hc = nil
  104. c.raw = nil
  105. return nil
  106. }
  107. // SignedURLOptions allows you to restrict the access to the signed URL.
  108. type SignedURLOptions struct {
  109. // GoogleAccessID represents the authorizer of the signed URL generation.
  110. // It is typically the Google service account client email address from
  111. // the Google Developers Console in the form of "xxx@developer.gserviceaccount.com".
  112. // Required.
  113. GoogleAccessID string
  114. // PrivateKey is the Google service account private key. It is obtainable
  115. // from the Google Developers Console.
  116. // At https://console.developers.google.com/project/<your-project-id>/apiui/credential,
  117. // create a service account client ID or reuse one of your existing service account
  118. // credentials. Click on the "Generate new P12 key" to generate and download
  119. // a new private key. Once you download the P12 file, use the following command
  120. // to convert it into a PEM file.
  121. //
  122. // $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes
  123. //
  124. // Provide the contents of the PEM file as a byte slice.
  125. // Exactly one of PrivateKey or SignBytes must be non-nil.
  126. PrivateKey []byte
  127. // SignBytes is a function for implementing custom signing.
  128. // If your application is running on Google App Engine, you can use appengine's internal signing function:
  129. // ctx := appengine.NewContext(request)
  130. // acc, _ := appengine.ServiceAccount(ctx)
  131. // url, err := SignedURL("bucket", "object", &SignedURLOptions{
  132. // GoogleAccessID: acc,
  133. // SignBytes: func(b []byte) ([]byte, error) {
  134. // _, signedBytes, err := appengine.SignBytes(ctx, b)
  135. // return signedBytes, err
  136. // },
  137. // // etc.
  138. // })
  139. //
  140. // Exactly one of PrivateKey or SignBytes must be non-nil.
  141. SignBytes func([]byte) ([]byte, error)
  142. // Method is the HTTP method to be used with the signed URL.
  143. // Signed URLs can be used with GET, HEAD, PUT, and DELETE requests.
  144. // Required.
  145. Method string
  146. // Expires is the expiration time on the signed URL. It must be
  147. // a datetime in the future.
  148. // Required.
  149. Expires time.Time
  150. // ContentType is the content type header the client must provide
  151. // to use the generated signed URL.
  152. // Optional.
  153. ContentType string
  154. // Headers is a list of extension headers the client must provide
  155. // in order to use the generated signed URL.
  156. // Optional.
  157. Headers []string
  158. // MD5 is the base64 encoded MD5 checksum of the file.
  159. // If provided, the client should provide the exact value on the request
  160. // header in order to use the signed URL.
  161. // Optional.
  162. MD5 string
  163. }
  164. var (
  165. canonicalHeaderRegexp = regexp.MustCompile(`(?i)^(x-goog-[^:]+):(.*)?$`)
  166. excludedCanonicalHeaders = map[string]bool{
  167. "x-goog-encryption-key": true,
  168. "x-goog-encryption-key-sha256": true,
  169. }
  170. )
  171. // sanitizeHeaders applies the specifications for canonical extension headers at
  172. // https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers.
  173. func sanitizeHeaders(hdrs []string) []string {
  174. headerMap := map[string][]string{}
  175. for _, hdr := range hdrs {
  176. // No leading or trailing whitespaces.
  177. sanitizedHeader := strings.TrimSpace(hdr)
  178. // Only keep canonical headers, discard any others.
  179. headerMatches := canonicalHeaderRegexp.FindStringSubmatch(sanitizedHeader)
  180. if len(headerMatches) == 0 {
  181. continue
  182. }
  183. header := strings.ToLower(strings.TrimSpace(headerMatches[1]))
  184. if excludedCanonicalHeaders[headerMatches[1]] {
  185. // Do not keep any deliberately excluded canonical headers when signing.
  186. continue
  187. }
  188. value := strings.TrimSpace(headerMatches[2])
  189. if len(value) > 0 {
  190. // Remove duplicate headers by appending the values of duplicates
  191. // in their order of appearance.
  192. headerMap[header] = append(headerMap[header], value)
  193. }
  194. }
  195. var sanitizedHeaders []string
  196. for header, values := range headerMap {
  197. // There should be no spaces around the colon separating the
  198. // header name from the header value or around the values
  199. // themselves. The values should be separated by commas.
  200. // NOTE: The semantics for headers without a value are not clear.
  201. // However from specifications these should be edge-cases
  202. // anyway and we should assume that there will be no
  203. // canonical headers using empty values. Any such headers
  204. // are discarded at the regexp stage above.
  205. sanitizedHeaders = append(
  206. sanitizedHeaders,
  207. fmt.Sprintf("%s:%s", header, strings.Join(values, ",")),
  208. )
  209. }
  210. sort.Strings(sanitizedHeaders)
  211. return sanitizedHeaders
  212. }
  213. // SignedURL returns a URL for the specified object. Signed URLs allow
  214. // the users access to a restricted resource for a limited time without having a
  215. // Google account or signing in. For more information about the signed
  216. // URLs, see https://cloud.google.com/storage/docs/accesscontrol#Signed-URLs.
  217. func SignedURL(bucket, name string, opts *SignedURLOptions) (string, error) {
  218. if opts == nil {
  219. return "", errors.New("storage: missing required SignedURLOptions")
  220. }
  221. if opts.GoogleAccessID == "" {
  222. return "", errors.New("storage: missing required GoogleAccessID")
  223. }
  224. if (opts.PrivateKey == nil) == (opts.SignBytes == nil) {
  225. return "", errors.New("storage: exactly one of PrivateKey or SignedBytes must be set")
  226. }
  227. if opts.Method == "" {
  228. return "", errors.New("storage: missing required method option")
  229. }
  230. if opts.Expires.IsZero() {
  231. return "", errors.New("storage: missing required expires option")
  232. }
  233. if opts.MD5 != "" {
  234. md5, err := base64.StdEncoding.DecodeString(opts.MD5)
  235. if err != nil || len(md5) != 16 {
  236. return "", errors.New("storage: invalid MD5 checksum")
  237. }
  238. }
  239. opts.Headers = sanitizeHeaders(opts.Headers)
  240. signBytes := opts.SignBytes
  241. if opts.PrivateKey != nil {
  242. key, err := parseKey(opts.PrivateKey)
  243. if err != nil {
  244. return "", err
  245. }
  246. signBytes = func(b []byte) ([]byte, error) {
  247. sum := sha256.Sum256(b)
  248. return rsa.SignPKCS1v15(
  249. rand.Reader,
  250. key,
  251. crypto.SHA256,
  252. sum[:],
  253. )
  254. }
  255. }
  256. u := &url.URL{
  257. Path: fmt.Sprintf("/%s/%s", bucket, name),
  258. }
  259. buf := &bytes.Buffer{}
  260. fmt.Fprintf(buf, "%s\n", opts.Method)
  261. fmt.Fprintf(buf, "%s\n", opts.MD5)
  262. fmt.Fprintf(buf, "%s\n", opts.ContentType)
  263. fmt.Fprintf(buf, "%d\n", opts.Expires.Unix())
  264. if len(opts.Headers) > 0 {
  265. fmt.Fprintf(buf, "%s\n", strings.Join(opts.Headers, "\n"))
  266. }
  267. fmt.Fprintf(buf, "%s", u.String())
  268. b, err := signBytes(buf.Bytes())
  269. if err != nil {
  270. return "", err
  271. }
  272. encoded := base64.StdEncoding.EncodeToString(b)
  273. u.Scheme = "https"
  274. u.Host = "storage.googleapis.com"
  275. q := u.Query()
  276. q.Set("GoogleAccessId", opts.GoogleAccessID)
  277. q.Set("Expires", fmt.Sprintf("%d", opts.Expires.Unix()))
  278. q.Set("Signature", string(encoded))
  279. u.RawQuery = q.Encode()
  280. return u.String(), nil
  281. }
  282. // ObjectHandle provides operations on an object in a Google Cloud Storage bucket.
  283. // Use BucketHandle.Object to get a handle.
  284. type ObjectHandle struct {
  285. c *Client
  286. bucket string
  287. object string
  288. acl ACLHandle
  289. gen int64 // a negative value indicates latest
  290. conds *Conditions
  291. encryptionKey []byte // AES-256 key
  292. userProject string // for requester-pays buckets
  293. readCompressed bool // Accept-Encoding: gzip
  294. }
  295. // ACL provides access to the object's access control list.
  296. // This controls who can read and write this object.
  297. // This call does not perform any network operations.
  298. func (o *ObjectHandle) ACL() *ACLHandle {
  299. return &o.acl
  300. }
  301. // Generation returns a new ObjectHandle that operates on a specific generation
  302. // of the object.
  303. // By default, the handle operates on the latest generation. Not
  304. // all operations work when given a specific generation; check the API
  305. // endpoints at https://cloud.google.com/storage/docs/json_api/ for details.
  306. func (o *ObjectHandle) Generation(gen int64) *ObjectHandle {
  307. o2 := *o
  308. o2.gen = gen
  309. return &o2
  310. }
  311. // If returns a new ObjectHandle that applies a set of preconditions.
  312. // Preconditions already set on the ObjectHandle are ignored.
  313. // Operations on the new handle will only occur if the preconditions are
  314. // satisfied. See https://cloud.google.com/storage/docs/generations-preconditions
  315. // for more details.
  316. func (o *ObjectHandle) If(conds Conditions) *ObjectHandle {
  317. o2 := *o
  318. o2.conds = &conds
  319. return &o2
  320. }
  321. // Key returns a new ObjectHandle that uses the supplied encryption
  322. // key to encrypt and decrypt the object's contents.
  323. //
  324. // Encryption key must be a 32-byte AES-256 key.
  325. // See https://cloud.google.com/storage/docs/encryption for details.
  326. func (o *ObjectHandle) Key(encryptionKey []byte) *ObjectHandle {
  327. o2 := *o
  328. o2.encryptionKey = encryptionKey
  329. return &o2
  330. }
  331. // Attrs returns meta information about the object.
  332. // ErrObjectNotExist will be returned if the object is not found.
  333. func (o *ObjectHandle) Attrs(ctx context.Context) (attrs *ObjectAttrs, err error) {
  334. ctx = trace.StartSpan(ctx, "cloud.google.com/go/storage.Object.Attrs")
  335. defer func() { trace.EndSpan(ctx, err) }()
  336. if err := o.validate(); err != nil {
  337. return nil, err
  338. }
  339. call := o.c.raw.Objects.Get(o.bucket, o.object).Projection("full").Context(ctx)
  340. if err := applyConds("Attrs", o.gen, o.conds, call); err != nil {
  341. return nil, err
  342. }
  343. if o.userProject != "" {
  344. call.UserProject(o.userProject)
  345. }
  346. if err := setEncryptionHeaders(call.Header(), o.encryptionKey, false); err != nil {
  347. return nil, err
  348. }
  349. var obj *raw.Object
  350. setClientHeader(call.Header())
  351. err = runWithRetry(ctx, func() error { obj, err = call.Do(); return err })
  352. if e, ok := err.(*googleapi.Error); ok && e.Code == http.StatusNotFound {
  353. return nil, ErrObjectNotExist
  354. }
  355. if err != nil {
  356. return nil, err
  357. }
  358. return newObject(obj), nil
  359. }
  360. // Update updates an object with the provided attributes.
  361. // All zero-value attributes are ignored.
  362. // ErrObjectNotExist will be returned if the object is not found.
  363. func (o *ObjectHandle) Update(ctx context.Context, uattrs ObjectAttrsToUpdate) (oa *ObjectAttrs, err error) {
  364. ctx = trace.StartSpan(ctx, "cloud.google.com/go/storage.Object.Update")
  365. defer func() { trace.EndSpan(ctx, err) }()
  366. if err := o.validate(); err != nil {
  367. return nil, err
  368. }
  369. var attrs ObjectAttrs
  370. // Lists of fields to send, and set to null, in the JSON.
  371. var forceSendFields, nullFields []string
  372. if uattrs.ContentType != nil {
  373. attrs.ContentType = optional.ToString(uattrs.ContentType)
  374. // For ContentType, sending the empty string is a no-op.
  375. // Instead we send a null.
  376. if attrs.ContentType == "" {
  377. nullFields = append(nullFields, "ContentType")
  378. } else {
  379. forceSendFields = append(forceSendFields, "ContentType")
  380. }
  381. }
  382. if uattrs.ContentLanguage != nil {
  383. attrs.ContentLanguage = optional.ToString(uattrs.ContentLanguage)
  384. // For ContentLanguage it's an error to send the empty string.
  385. // Instead we send a null.
  386. if attrs.ContentLanguage == "" {
  387. nullFields = append(nullFields, "ContentLanguage")
  388. } else {
  389. forceSendFields = append(forceSendFields, "ContentLanguage")
  390. }
  391. }
  392. if uattrs.ContentEncoding != nil {
  393. attrs.ContentEncoding = optional.ToString(uattrs.ContentEncoding)
  394. forceSendFields = append(forceSendFields, "ContentEncoding")
  395. }
  396. if uattrs.ContentDisposition != nil {
  397. attrs.ContentDisposition = optional.ToString(uattrs.ContentDisposition)
  398. forceSendFields = append(forceSendFields, "ContentDisposition")
  399. }
  400. if uattrs.CacheControl != nil {
  401. attrs.CacheControl = optional.ToString(uattrs.CacheControl)
  402. forceSendFields = append(forceSendFields, "CacheControl")
  403. }
  404. if uattrs.Metadata != nil {
  405. attrs.Metadata = uattrs.Metadata
  406. if len(attrs.Metadata) == 0 {
  407. // Sending the empty map is a no-op. We send null instead.
  408. nullFields = append(nullFields, "Metadata")
  409. } else {
  410. forceSendFields = append(forceSendFields, "Metadata")
  411. }
  412. }
  413. if uattrs.ACL != nil {
  414. attrs.ACL = uattrs.ACL
  415. // It's an error to attempt to delete the ACL, so
  416. // we don't append to nullFields here.
  417. forceSendFields = append(forceSendFields, "Acl")
  418. }
  419. rawObj := attrs.toRawObject(o.bucket)
  420. rawObj.ForceSendFields = forceSendFields
  421. rawObj.NullFields = nullFields
  422. call := o.c.raw.Objects.Patch(o.bucket, o.object, rawObj).Projection("full").Context(ctx)
  423. if err := applyConds("Update", o.gen, o.conds, call); err != nil {
  424. return nil, err
  425. }
  426. if o.userProject != "" {
  427. call.UserProject(o.userProject)
  428. }
  429. if err := setEncryptionHeaders(call.Header(), o.encryptionKey, false); err != nil {
  430. return nil, err
  431. }
  432. var obj *raw.Object
  433. setClientHeader(call.Header())
  434. err = runWithRetry(ctx, func() error { obj, err = call.Do(); return err })
  435. if e, ok := err.(*googleapi.Error); ok && e.Code == http.StatusNotFound {
  436. return nil, ErrObjectNotExist
  437. }
  438. if err != nil {
  439. return nil, err
  440. }
  441. return newObject(obj), nil
  442. }
  443. // ObjectAttrsToUpdate is used to update the attributes of an object.
  444. // Only fields set to non-nil values will be updated.
  445. // Set a field to its zero value to delete it.
  446. //
  447. // For example, to change ContentType and delete ContentEncoding and
  448. // Metadata, use
  449. // ObjectAttrsToUpdate{
  450. // ContentType: "text/html",
  451. // ContentEncoding: "",
  452. // Metadata: map[string]string{},
  453. // }
  454. type ObjectAttrsToUpdate struct {
  455. ContentType optional.String
  456. ContentLanguage optional.String
  457. ContentEncoding optional.String
  458. ContentDisposition optional.String
  459. CacheControl optional.String
  460. Metadata map[string]string // set to map[string]string{} to delete
  461. ACL []ACLRule
  462. }
  463. // Delete deletes the single specified object.
  464. func (o *ObjectHandle) Delete(ctx context.Context) error {
  465. if err := o.validate(); err != nil {
  466. return err
  467. }
  468. call := o.c.raw.Objects.Delete(o.bucket, o.object).Context(ctx)
  469. if err := applyConds("Delete", o.gen, o.conds, call); err != nil {
  470. return err
  471. }
  472. if o.userProject != "" {
  473. call.UserProject(o.userProject)
  474. }
  475. // Encryption doesn't apply to Delete.
  476. setClientHeader(call.Header())
  477. err := runWithRetry(ctx, func() error { return call.Do() })
  478. switch e := err.(type) {
  479. case nil:
  480. return nil
  481. case *googleapi.Error:
  482. if e.Code == http.StatusNotFound {
  483. return ErrObjectNotExist
  484. }
  485. }
  486. return err
  487. }
  488. // ReadCompressed when true causes the read to happen without decompressing.
  489. func (o *ObjectHandle) ReadCompressed(compressed bool) *ObjectHandle {
  490. o2 := *o
  491. o2.readCompressed = compressed
  492. return &o2
  493. }
  494. // NewWriter returns a storage Writer that writes to the GCS object
  495. // associated with this ObjectHandle.
  496. //
  497. // A new object will be created unless an object with this name already exists.
  498. // Otherwise any previous object with the same name will be replaced.
  499. // The object will not be available (and any previous object will remain)
  500. // until Close has been called.
  501. //
  502. // Attributes can be set on the object by modifying the returned Writer's
  503. // ObjectAttrs field before the first call to Write. If no ContentType
  504. // attribute is specified, the content type will be automatically sniffed
  505. // using net/http.DetectContentType.
  506. //
  507. // It is the caller's responsibility to call Close when writing is done.
  508. func (o *ObjectHandle) NewWriter(ctx context.Context) *Writer {
  509. return &Writer{
  510. ctx: ctx,
  511. o: o,
  512. donec: make(chan struct{}),
  513. ObjectAttrs: ObjectAttrs{Name: o.object},
  514. ChunkSize: googleapi.DefaultUploadChunkSize,
  515. }
  516. }
  517. func (o *ObjectHandle) validate() error {
  518. if o.bucket == "" {
  519. return errors.New("storage: bucket name is empty")
  520. }
  521. if o.object == "" {
  522. return errors.New("storage: object name is empty")
  523. }
  524. if !utf8.ValidString(o.object) {
  525. return fmt.Errorf("storage: object name %q is not valid UTF-8", o.object)
  526. }
  527. return nil
  528. }
  529. // parseKey converts the binary contents of a private key file to an
  530. // *rsa.PrivateKey. It detects whether the private key is in a PEM container or
  531. // not. If so, it extracts the private key from PEM container before
  532. // conversion. It only supports PEM containers with no passphrase.
  533. func parseKey(key []byte) (*rsa.PrivateKey, error) {
  534. if block, _ := pem.Decode(key); block != nil {
  535. key = block.Bytes
  536. }
  537. parsedKey, err := x509.ParsePKCS8PrivateKey(key)
  538. if err != nil {
  539. parsedKey, err = x509.ParsePKCS1PrivateKey(key)
  540. if err != nil {
  541. return nil, err
  542. }
  543. }
  544. parsed, ok := parsedKey.(*rsa.PrivateKey)
  545. if !ok {
  546. return nil, errors.New("oauth2: private key is invalid")
  547. }
  548. return parsed, nil
  549. }
  550. func toRawObjectACL(oldACL []ACLRule) []*raw.ObjectAccessControl {
  551. var acl []*raw.ObjectAccessControl
  552. if len(oldACL) > 0 {
  553. acl = make([]*raw.ObjectAccessControl, len(oldACL))
  554. for i, rule := range oldACL {
  555. acl[i] = &raw.ObjectAccessControl{
  556. Entity: string(rule.Entity),
  557. Role: string(rule.Role),
  558. }
  559. }
  560. }
  561. return acl
  562. }
  563. // toRawObject copies the editable attributes from o to the raw library's Object type.
  564. func (o *ObjectAttrs) toRawObject(bucket string) *raw.Object {
  565. acl := toRawObjectACL(o.ACL)
  566. return &raw.Object{
  567. Bucket: bucket,
  568. Name: o.Name,
  569. ContentType: o.ContentType,
  570. ContentEncoding: o.ContentEncoding,
  571. ContentLanguage: o.ContentLanguage,
  572. CacheControl: o.CacheControl,
  573. ContentDisposition: o.ContentDisposition,
  574. StorageClass: o.StorageClass,
  575. Acl: acl,
  576. Metadata: o.Metadata,
  577. }
  578. }
  579. // ObjectAttrs represents the metadata for a Google Cloud Storage (GCS) object.
  580. type ObjectAttrs struct {
  581. // Bucket is the name of the bucket containing this GCS object.
  582. // This field is read-only.
  583. Bucket string
  584. // Name is the name of the object within the bucket.
  585. // This field is read-only.
  586. Name string
  587. // ContentType is the MIME type of the object's content.
  588. ContentType string
  589. // ContentLanguage is the content language of the object's content.
  590. ContentLanguage string
  591. // CacheControl is the Cache-Control header to be sent in the response
  592. // headers when serving the object data.
  593. CacheControl string
  594. // ACL is the list of access control rules for the object.
  595. ACL []ACLRule
  596. // Owner is the owner of the object. This field is read-only.
  597. //
  598. // If non-zero, it is in the form of "user-<userId>".
  599. Owner string
  600. // Size is the length of the object's content. This field is read-only.
  601. Size int64
  602. // ContentEncoding is the encoding of the object's content.
  603. ContentEncoding string
  604. // ContentDisposition is the optional Content-Disposition header of the object
  605. // sent in the response headers.
  606. ContentDisposition string
  607. // MD5 is the MD5 hash of the object's content. This field is read-only,
  608. // except when used from a Writer. If set on a Writer, the uploaded
  609. // data is rejected if its MD5 hash does not match this field.
  610. MD5 []byte
  611. // CRC32C is the CRC32 checksum of the object's content using
  612. // the Castagnoli93 polynomial. This field is read-only, except when
  613. // used from a Writer. If set on a Writer and Writer.SendCRC32C
  614. // is true, the uploaded data is rejected if its CRC32c hash does not
  615. // match this field.
  616. CRC32C uint32
  617. // MediaLink is an URL to the object's content. This field is read-only.
  618. MediaLink string
  619. // Metadata represents user-provided metadata, in key/value pairs.
  620. // It can be nil if no metadata is provided.
  621. Metadata map[string]string
  622. // Generation is the generation number of the object's content.
  623. // This field is read-only.
  624. Generation int64
  625. // Metageneration is the version of the metadata for this
  626. // object at this generation. This field is used for preconditions
  627. // and for detecting changes in metadata. A metageneration number
  628. // is only meaningful in the context of a particular generation
  629. // of a particular object. This field is read-only.
  630. Metageneration int64
  631. // StorageClass is the storage class of the object.
  632. // This value defines how objects in the bucket are stored and
  633. // determines the SLA and the cost of storage. Typical values are
  634. // "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE", "STANDARD"
  635. // and "DURABLE_REDUCED_AVAILABILITY".
  636. // It defaults to "STANDARD", which is equivalent to "MULTI_REGIONAL"
  637. // or "REGIONAL" depending on the bucket's location settings.
  638. StorageClass string
  639. // Created is the time the object was created. This field is read-only.
  640. Created time.Time
  641. // Deleted is the time the object was deleted.
  642. // If not deleted, it is the zero value. This field is read-only.
  643. Deleted time.Time
  644. // Updated is the creation or modification time of the object.
  645. // For buckets with versioning enabled, changing an object's
  646. // metadata does not change this property. This field is read-only.
  647. Updated time.Time
  648. // CustomerKeySHA256 is the base64-encoded SHA-256 hash of the
  649. // customer-supplied encryption key for the object. It is empty if there is
  650. // no customer-supplied encryption key.
  651. // See // https://cloud.google.com/storage/docs/encryption for more about
  652. // encryption in Google Cloud Storage.
  653. CustomerKeySHA256 string
  654. // Cloud KMS key name, in the form
  655. // projects/P/locations/L/keyRings/R/cryptoKeys/K, used to encrypt this object,
  656. // if the object is encrypted by such a key.
  657. //
  658. // Providing both a KMSKeyName and a customer-supplied encryption key (via
  659. // ObjectHandle.Key) will result in an error when writing an object.
  660. KMSKeyName string
  661. // Prefix is set only for ObjectAttrs which represent synthetic "directory
  662. // entries" when iterating over buckets using Query.Delimiter. See
  663. // ObjectIterator.Next. When set, no other fields in ObjectAttrs will be
  664. // populated.
  665. Prefix string
  666. }
  667. // convertTime converts a time in RFC3339 format to time.Time.
  668. // If any error occurs in parsing, the zero-value time.Time is silently returned.
  669. func convertTime(t string) time.Time {
  670. var r time.Time
  671. if t != "" {
  672. r, _ = time.Parse(time.RFC3339, t)
  673. }
  674. return r
  675. }
  676. func newObject(o *raw.Object) *ObjectAttrs {
  677. if o == nil {
  678. return nil
  679. }
  680. acl := make([]ACLRule, len(o.Acl))
  681. for i, rule := range o.Acl {
  682. acl[i] = ACLRule{
  683. Entity: ACLEntity(rule.Entity),
  684. Role: ACLRole(rule.Role),
  685. }
  686. }
  687. owner := ""
  688. if o.Owner != nil {
  689. owner = o.Owner.Entity
  690. }
  691. md5, _ := base64.StdEncoding.DecodeString(o.Md5Hash)
  692. crc32c, _ := decodeUint32(o.Crc32c)
  693. var sha256 string
  694. if o.CustomerEncryption != nil {
  695. sha256 = o.CustomerEncryption.KeySha256
  696. }
  697. return &ObjectAttrs{
  698. Bucket: o.Bucket,
  699. Name: o.Name,
  700. ContentType: o.ContentType,
  701. ContentLanguage: o.ContentLanguage,
  702. CacheControl: o.CacheControl,
  703. ACL: acl,
  704. Owner: owner,
  705. ContentEncoding: o.ContentEncoding,
  706. ContentDisposition: o.ContentDisposition,
  707. Size: int64(o.Size),
  708. MD5: md5,
  709. CRC32C: crc32c,
  710. MediaLink: o.MediaLink,
  711. Metadata: o.Metadata,
  712. Generation: o.Generation,
  713. Metageneration: o.Metageneration,
  714. StorageClass: o.StorageClass,
  715. CustomerKeySHA256: sha256,
  716. KMSKeyName: o.KmsKeyName,
  717. Created: convertTime(o.TimeCreated),
  718. Deleted: convertTime(o.TimeDeleted),
  719. Updated: convertTime(o.Updated),
  720. }
  721. }
  722. // Decode a uint32 encoded in Base64 in big-endian byte order.
  723. func decodeUint32(b64 string) (uint32, error) {
  724. d, err := base64.StdEncoding.DecodeString(b64)
  725. if err != nil {
  726. return 0, err
  727. }
  728. if len(d) != 4 {
  729. return 0, fmt.Errorf("storage: %q does not encode a 32-bit value", d)
  730. }
  731. return uint32(d[0])<<24 + uint32(d[1])<<16 + uint32(d[2])<<8 + uint32(d[3]), nil
  732. }
  733. // Encode a uint32 as Base64 in big-endian byte order.
  734. func encodeUint32(u uint32) string {
  735. b := []byte{byte(u >> 24), byte(u >> 16), byte(u >> 8), byte(u)}
  736. return base64.StdEncoding.EncodeToString(b)
  737. }
  738. // Query represents a query to filter objects from a bucket.
  739. type Query struct {
  740. // Delimiter returns results in a directory-like fashion.
  741. // Results will contain only objects whose names, aside from the
  742. // prefix, do not contain delimiter. Objects whose names,
  743. // aside from the prefix, contain delimiter will have their name,
  744. // truncated after the delimiter, returned in prefixes.
  745. // Duplicate prefixes are omitted.
  746. // Optional.
  747. Delimiter string
  748. // Prefix is the prefix filter to query objects
  749. // whose names begin with this prefix.
  750. // Optional.
  751. Prefix string
  752. // Versions indicates whether multiple versions of the same
  753. // object will be included in the results.
  754. Versions bool
  755. }
  756. // contentTyper implements ContentTyper to enable an
  757. // io.ReadCloser to specify its MIME type.
  758. type contentTyper struct {
  759. io.Reader
  760. t string
  761. }
  762. func (c *contentTyper) ContentType() string {
  763. return c.t
  764. }
  765. // Conditions constrain methods to act on specific generations of
  766. // objects.
  767. //
  768. // The zero value is an empty set of constraints. Not all conditions or
  769. // combinations of conditions are applicable to all methods.
  770. // See https://cloud.google.com/storage/docs/generations-preconditions
  771. // for details on how these operate.
  772. type Conditions struct {
  773. // Generation constraints.
  774. // At most one of the following can be set to a non-zero value.
  775. // GenerationMatch specifies that the object must have the given generation
  776. // for the operation to occur.
  777. // If GenerationMatch is zero, it has no effect.
  778. // Use DoesNotExist to specify that the object does not exist in the bucket.
  779. GenerationMatch int64
  780. // GenerationNotMatch specifies that the object must not have the given
  781. // generation for the operation to occur.
  782. // If GenerationNotMatch is zero, it has no effect.
  783. GenerationNotMatch int64
  784. // DoesNotExist specifies that the object must not exist in the bucket for
  785. // the operation to occur.
  786. // If DoesNotExist is false, it has no effect.
  787. DoesNotExist bool
  788. // Metadata generation constraints.
  789. // At most one of the following can be set to a non-zero value.
  790. // MetagenerationMatch specifies that the object must have the given
  791. // metageneration for the operation to occur.
  792. // If MetagenerationMatch is zero, it has no effect.
  793. MetagenerationMatch int64
  794. // MetagenerationNotMatch specifies that the object must not have the given
  795. // metageneration for the operation to occur.
  796. // If MetagenerationNotMatch is zero, it has no effect.
  797. MetagenerationNotMatch int64
  798. }
  799. func (c *Conditions) validate(method string) error {
  800. if *c == (Conditions{}) {
  801. return fmt.Errorf("storage: %s: empty conditions", method)
  802. }
  803. if !c.isGenerationValid() {
  804. return fmt.Errorf("storage: %s: multiple conditions specified for generation", method)
  805. }
  806. if !c.isMetagenerationValid() {
  807. return fmt.Errorf("storage: %s: multiple conditions specified for metageneration", method)
  808. }
  809. return nil
  810. }
  811. func (c *Conditions) isGenerationValid() bool {
  812. n := 0
  813. if c.GenerationMatch != 0 {
  814. n++
  815. }
  816. if c.GenerationNotMatch != 0 {
  817. n++
  818. }
  819. if c.DoesNotExist {
  820. n++
  821. }
  822. return n <= 1
  823. }
  824. func (c *Conditions) isMetagenerationValid() bool {
  825. return c.MetagenerationMatch == 0 || c.MetagenerationNotMatch == 0
  826. }
  827. // applyConds modifies the provided call using the conditions in conds.
  828. // call is something that quacks like a *raw.WhateverCall.
  829. func applyConds(method string, gen int64, conds *Conditions, call interface{}) error {
  830. cval := reflect.ValueOf(call)
  831. if gen >= 0 {
  832. if !setConditionField(cval, "Generation", gen) {
  833. return fmt.Errorf("storage: %s: generation not supported", method)
  834. }
  835. }
  836. if conds == nil {
  837. return nil
  838. }
  839. if err := conds.validate(method); err != nil {
  840. return err
  841. }
  842. switch {
  843. case conds.GenerationMatch != 0:
  844. if !setConditionField(cval, "IfGenerationMatch", conds.GenerationMatch) {
  845. return fmt.Errorf("storage: %s: ifGenerationMatch not supported", method)
  846. }
  847. case conds.GenerationNotMatch != 0:
  848. if !setConditionField(cval, "IfGenerationNotMatch", conds.GenerationNotMatch) {
  849. return fmt.Errorf("storage: %s: ifGenerationNotMatch not supported", method)
  850. }
  851. case conds.DoesNotExist:
  852. if !setConditionField(cval, "IfGenerationMatch", int64(0)) {
  853. return fmt.Errorf("storage: %s: DoesNotExist not supported", method)
  854. }
  855. }
  856. switch {
  857. case conds.MetagenerationMatch != 0:
  858. if !setConditionField(cval, "IfMetagenerationMatch", conds.MetagenerationMatch) {
  859. return fmt.Errorf("storage: %s: ifMetagenerationMatch not supported", method)
  860. }
  861. case conds.MetagenerationNotMatch != 0:
  862. if !setConditionField(cval, "IfMetagenerationNotMatch", conds.MetagenerationNotMatch) {
  863. return fmt.Errorf("storage: %s: ifMetagenerationNotMatch not supported", method)
  864. }
  865. }
  866. return nil
  867. }
  868. func applySourceConds(gen int64, conds *Conditions, call *raw.ObjectsRewriteCall) error {
  869. if gen >= 0 {
  870. call.SourceGeneration(gen)
  871. }
  872. if conds == nil {
  873. return nil
  874. }
  875. if err := conds.validate("CopyTo source"); err != nil {
  876. return err
  877. }
  878. switch {
  879. case conds.GenerationMatch != 0:
  880. call.IfSourceGenerationMatch(conds.GenerationMatch)
  881. case conds.GenerationNotMatch != 0:
  882. call.IfSourceGenerationNotMatch(conds.GenerationNotMatch)
  883. case conds.DoesNotExist:
  884. call.IfSourceGenerationMatch(0)
  885. }
  886. switch {
  887. case conds.MetagenerationMatch != 0:
  888. call.IfSourceMetagenerationMatch(conds.MetagenerationMatch)
  889. case conds.MetagenerationNotMatch != 0:
  890. call.IfSourceMetagenerationNotMatch(conds.MetagenerationNotMatch)
  891. }
  892. return nil
  893. }
  894. // setConditionField sets a field on a *raw.WhateverCall.
  895. // We can't use anonymous interfaces because the return type is
  896. // different, since the field setters are builders.
  897. func setConditionField(call reflect.Value, name string, value interface{}) bool {
  898. m := call.MethodByName(name)
  899. if !m.IsValid() {
  900. return false
  901. }
  902. m.Call([]reflect.Value{reflect.ValueOf(value)})
  903. return true
  904. }
  905. // conditionsQuery returns the generation and conditions as a URL query
  906. // string suitable for URL.RawQuery. It assumes that the conditions
  907. // have been validated.
  908. func conditionsQuery(gen int64, conds *Conditions) string {
  909. // URL escapes are elided because integer strings are URL-safe.
  910. var buf []byte
  911. appendParam := func(s string, n int64) {
  912. if len(buf) > 0 {
  913. buf = append(buf, '&')
  914. }
  915. buf = append(buf, s...)
  916. buf = strconv.AppendInt(buf, n, 10)
  917. }
  918. if gen >= 0 {
  919. appendParam("generation=", gen)
  920. }
  921. if conds == nil {
  922. return string(buf)
  923. }
  924. switch {
  925. case conds.GenerationMatch != 0:
  926. appendParam("ifGenerationMatch=", conds.GenerationMatch)
  927. case conds.GenerationNotMatch != 0:
  928. appendParam("ifGenerationNotMatch=", conds.GenerationNotMatch)
  929. case conds.DoesNotExist:
  930. appendParam("ifGenerationMatch=", 0)
  931. }
  932. switch {
  933. case conds.MetagenerationMatch != 0:
  934. appendParam("ifMetagenerationMatch=", conds.MetagenerationMatch)
  935. case conds.MetagenerationNotMatch != 0:
  936. appendParam("ifMetagenerationNotMatch=", conds.MetagenerationNotMatch)
  937. }
  938. return string(buf)
  939. }
  940. // composeSourceObj wraps a *raw.ComposeRequestSourceObjects, but adds the methods
  941. // that modifyCall searches for by name.
  942. type composeSourceObj struct {
  943. src *raw.ComposeRequestSourceObjects
  944. }
  945. func (c composeSourceObj) Generation(gen int64) {
  946. c.src.Generation = gen
  947. }
  948. func (c composeSourceObj) IfGenerationMatch(gen int64) {
  949. // It's safe to overwrite ObjectPreconditions, since its only field is
  950. // IfGenerationMatch.
  951. c.src.ObjectPreconditions = &raw.ComposeRequestSourceObjectsObjectPreconditions{
  952. IfGenerationMatch: gen,
  953. }
  954. }
  955. func setEncryptionHeaders(headers http.Header, key []byte, copySource bool) error {
  956. if key == nil {
  957. return nil
  958. }
  959. // TODO(jbd): Ask the API team to return a more user-friendly error
  960. // and avoid doing this check at the client level.
  961. if len(key) != 32 {
  962. return errors.New("storage: not a 32-byte AES-256 key")
  963. }
  964. var cs string
  965. if copySource {
  966. cs = "copy-source-"
  967. }
  968. headers.Set("x-goog-"+cs+"encryption-algorithm", "AES256")
  969. headers.Set("x-goog-"+cs+"encryption-key", base64.StdEncoding.EncodeToString(key))
  970. keyHash := sha256.Sum256(key)
  971. headers.Set("x-goog-"+cs+"encryption-key-sha256", base64.StdEncoding.EncodeToString(keyHash[:]))
  972. return nil
  973. }
  974. // TODO(jbd): Add storage.objects.watch.