You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

458 lines
11 KiB

4 years ago
6 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
  1. package cos
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "encoding/xml"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "reflect"
  13. "strings"
  14. "text/template"
  15. "strconv"
  16. "github.com/google/go-querystring/query"
  17. "github.com/mozillazg/go-httpheader"
  18. )
  19. const (
  20. // Version current go sdk version
  21. Version = "0.7.27"
  22. userAgent = "cos-go-sdk-v5/" + Version
  23. contentTypeXML = "application/xml"
  24. defaultServiceBaseURL = "http://service.cos.myqcloud.com"
  25. )
  26. var bucketURLTemplate = template.Must(
  27. template.New("bucketURLFormat").Parse(
  28. "{{.Schema}}://{{.BucketName}}.cos.{{.Region}}.myqcloud.com",
  29. ),
  30. )
  31. // BaseURL 访问各 API 所需的基础 URL
  32. type BaseURL struct {
  33. // 访问 bucket, object 相关 API 的基础 URL(不包含 path 部分): http://example.com
  34. BucketURL *url.URL
  35. // 访问 service API 的基础 URL(不包含 path 部分): http://example.com
  36. ServiceURL *url.URL
  37. // 访问 job API 的基础 URL (不包含 path 部分): http://example.com
  38. BatchURL *url.URL
  39. // 访问 CI 的基础 URL
  40. CIURL *url.URL
  41. }
  42. // NewBucketURL 生成 BaseURL 所需的 BucketURL
  43. //
  44. // bucketName: bucket名称, bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
  45. // Region: 区域代码: ap-beijing-1,ap-beijing,ap-shanghai,ap-guangzhou...
  46. // secure: 是否使用 https
  47. func NewBucketURL(bucketName, region string, secure bool) *url.URL {
  48. schema := "https"
  49. if !secure {
  50. schema = "http"
  51. }
  52. w := bytes.NewBuffer(nil)
  53. bucketURLTemplate.Execute(w, struct {
  54. Schema string
  55. BucketName string
  56. Region string
  57. }{
  58. schema, bucketName, region,
  59. })
  60. u, _ := url.Parse(w.String())
  61. return u
  62. }
  63. type Config struct {
  64. EnableCRC bool
  65. RequestBodyClose bool
  66. }
  67. // Client is a client manages communication with the COS API.
  68. type Client struct {
  69. client *http.Client
  70. Host string
  71. UserAgent string
  72. BaseURL *BaseURL
  73. common service
  74. Service *ServiceService
  75. Bucket *BucketService
  76. Object *ObjectService
  77. Batch *BatchService
  78. CI *CIService
  79. Conf *Config
  80. }
  81. type service struct {
  82. client *Client
  83. }
  84. // NewClient returns a new COS API client.
  85. func NewClient(uri *BaseURL, httpClient *http.Client) *Client {
  86. if httpClient == nil {
  87. httpClient = &http.Client{}
  88. }
  89. baseURL := &BaseURL{}
  90. if uri != nil {
  91. baseURL.BucketURL = uri.BucketURL
  92. baseURL.ServiceURL = uri.ServiceURL
  93. baseURL.BatchURL = uri.BatchURL
  94. baseURL.CIURL = uri.CIURL
  95. }
  96. if baseURL.ServiceURL == nil {
  97. baseURL.ServiceURL, _ = url.Parse(defaultServiceBaseURL)
  98. }
  99. c := &Client{
  100. client: httpClient,
  101. UserAgent: userAgent,
  102. BaseURL: baseURL,
  103. Conf: &Config{
  104. EnableCRC: true,
  105. RequestBodyClose: false,
  106. },
  107. }
  108. c.common.client = c
  109. c.Service = (*ServiceService)(&c.common)
  110. c.Bucket = (*BucketService)(&c.common)
  111. c.Object = (*ObjectService)(&c.common)
  112. c.Batch = (*BatchService)(&c.common)
  113. c.CI = (*CIService)(&c.common)
  114. return c
  115. }
  116. type Credential struct {
  117. SecretID string
  118. SecretKey string
  119. SessionToken string
  120. }
  121. func (c *Client) GetCredential() *Credential {
  122. auth, ok := c.client.Transport.(*AuthorizationTransport)
  123. if !ok {
  124. return nil
  125. }
  126. auth.rwLocker.Lock()
  127. defer auth.rwLocker.Unlock()
  128. return &Credential{
  129. SecretID: auth.SecretID,
  130. SecretKey: auth.SecretKey,
  131. SessionToken: auth.SessionToken,
  132. }
  133. }
  134. func (c *Client) newRequest(ctx context.Context, baseURL *url.URL, uri, method string, body interface{}, optQuery interface{}, optHeader interface{}) (req *http.Request, err error) {
  135. uri, err = addURLOptions(uri, optQuery)
  136. if err != nil {
  137. return
  138. }
  139. u, _ := url.Parse(uri)
  140. urlStr := baseURL.ResolveReference(u).String()
  141. var reader io.Reader
  142. contentType := ""
  143. contentMD5 := ""
  144. if body != nil {
  145. // 上传文件
  146. if r, ok := body.(io.Reader); ok {
  147. reader = r
  148. } else {
  149. b, err := xml.Marshal(body)
  150. if err != nil {
  151. return nil, err
  152. }
  153. contentType = contentTypeXML
  154. reader = bytes.NewReader(b)
  155. contentMD5 = base64.StdEncoding.EncodeToString(calMD5Digest(b))
  156. }
  157. }
  158. req, err = http.NewRequest(method, urlStr, reader)
  159. if err != nil {
  160. return
  161. }
  162. req.Header, err = addHeaderOptions(req.Header, optHeader)
  163. if err != nil {
  164. return
  165. }
  166. if v := req.Header.Get("Content-Length"); req.ContentLength == 0 && v != "" && v != "0" {
  167. req.ContentLength, _ = strconv.ParseInt(v, 10, 64)
  168. }
  169. if contentMD5 != "" {
  170. req.Header["Content-MD5"] = []string{contentMD5}
  171. }
  172. if v := req.Header.Get("User-Agent"); v == "" || !strings.HasPrefix(v, userAgent) {
  173. if c.UserAgent != "" {
  174. req.Header.Set("User-Agent", c.UserAgent)
  175. }
  176. }
  177. if req.Header.Get("Content-Type") == "" && contentType != "" {
  178. req.Header.Set("Content-Type", contentType)
  179. }
  180. if c.Host != "" {
  181. req.Host = c.Host
  182. }
  183. if c.Conf.RequestBodyClose {
  184. req.Close = true
  185. }
  186. return
  187. }
  188. func (c *Client) doAPI(ctx context.Context, req *http.Request, result interface{}, closeBody bool) (*Response, error) {
  189. req = req.WithContext(ctx)
  190. resp, err := c.client.Do(req)
  191. if err != nil {
  192. // If we got an error, and the context has been canceled,
  193. // the context's error is probably more useful.
  194. select {
  195. case <-ctx.Done():
  196. return nil, ctx.Err()
  197. default:
  198. }
  199. return nil, err
  200. }
  201. defer func() {
  202. if closeBody {
  203. // Close the body to let the Transport reuse the connection
  204. io.Copy(ioutil.Discard, resp.Body)
  205. resp.Body.Close()
  206. }
  207. }()
  208. response := newResponse(resp)
  209. err = checkResponse(resp)
  210. if err != nil {
  211. // even though there was an error, we still return the response
  212. // in case the caller wants to inspect it further
  213. return response, err
  214. }
  215. // need CRC64 verification
  216. if reader, ok := req.Body.(*teeReader); ok {
  217. if c.Conf.EnableCRC && reader.writer != nil {
  218. localcrc := reader.Crc64()
  219. scoscrc := response.Header.Get("x-cos-hash-crc64ecma")
  220. icoscrc, _ := strconv.ParseUint(scoscrc, 10, 64)
  221. if icoscrc != localcrc {
  222. return response, fmt.Errorf("verification failed, want:%v, return:%v", localcrc, icoscrc)
  223. }
  224. }
  225. }
  226. if result != nil {
  227. if w, ok := result.(io.Writer); ok {
  228. io.Copy(w, resp.Body)
  229. } else {
  230. err = xml.NewDecoder(resp.Body).Decode(result)
  231. if err == io.EOF {
  232. err = nil // ignore EOF errors caused by empty response body
  233. }
  234. }
  235. }
  236. return response, err
  237. }
  238. type sendOptions struct {
  239. // 基础 URL
  240. baseURL *url.URL
  241. // URL 中除基础 URL 外的剩余部分
  242. uri string
  243. // 请求方法
  244. method string
  245. body interface{}
  246. // url 查询参数
  247. optQuery interface{}
  248. // http header 参数
  249. optHeader interface{}
  250. // 用 result 反序列化 resp.Body
  251. result interface{}
  252. // 是否禁用自动调用 resp.Body.Close()
  253. // 自动调用 Close() 是为了能够重用连接
  254. disableCloseBody bool
  255. }
  256. func (c *Client) send(ctx context.Context, opt *sendOptions) (resp *Response, err error) {
  257. req, err := c.newRequest(ctx, opt.baseURL, opt.uri, opt.method, opt.body, opt.optQuery, opt.optHeader)
  258. if err != nil {
  259. return
  260. }
  261. resp, err = c.doAPI(ctx, req, opt.result, !opt.disableCloseBody)
  262. return
  263. }
  264. // addURLOptions adds the parameters in opt as URL query parameters to s. opt
  265. // must be a struct whose fields may contain "url" tags.
  266. func addURLOptions(s string, opt interface{}) (string, error) {
  267. v := reflect.ValueOf(opt)
  268. if v.Kind() == reflect.Ptr && v.IsNil() {
  269. return s, nil
  270. }
  271. u, err := url.Parse(s)
  272. if err != nil {
  273. return s, err
  274. }
  275. qs, err := query.Values(opt)
  276. if err != nil {
  277. return s, err
  278. }
  279. // 保留原有的参数,并且放在前面。因为 cos 的 url 路由是以第一个参数作为路由的
  280. // e.g. /?uploads
  281. q := u.RawQuery
  282. rq := qs.Encode()
  283. if q != "" {
  284. if rq != "" {
  285. u.RawQuery = fmt.Sprintf("%s&%s", q, qs.Encode())
  286. }
  287. } else {
  288. u.RawQuery = rq
  289. }
  290. return u.String(), nil
  291. }
  292. // addHeaderOptions adds the parameters in opt as Header fields to req. opt
  293. // must be a struct whose fields may contain "header" tags.
  294. func addHeaderOptions(header http.Header, opt interface{}) (http.Header, error) {
  295. v := reflect.ValueOf(opt)
  296. if v.Kind() == reflect.Ptr && v.IsNil() {
  297. return header, nil
  298. }
  299. h, err := httpheader.Header(opt)
  300. if err != nil {
  301. return nil, err
  302. }
  303. for key, values := range h {
  304. for _, value := range values {
  305. header.Add(key, value)
  306. }
  307. }
  308. return header, nil
  309. }
  310. // Owner defines Bucket/Object's owner
  311. type Owner struct {
  312. UIN string `xml:"uin,omitempty"`
  313. ID string `xml:",omitempty"`
  314. DisplayName string `xml:",omitempty"`
  315. }
  316. // Initiator same to the Owner struct
  317. type Initiator Owner
  318. // Response API 响应
  319. type Response struct {
  320. *http.Response
  321. }
  322. func newResponse(resp *http.Response) *Response {
  323. return &Response{
  324. Response: resp,
  325. }
  326. }
  327. // ACLHeaderOptions is the option of ACLHeader
  328. type ACLHeaderOptions struct {
  329. XCosACL string `header:"x-cos-acl,omitempty" url:"-" xml:"-"`
  330. XCosGrantRead string `header:"x-cos-grant-read,omitempty" url:"-" xml:"-"`
  331. XCosGrantWrite string `header:"x-cos-grant-write,omitempty" url:"-" xml:"-"`
  332. XCosGrantFullControl string `header:"x-cos-grant-full-control,omitempty" url:"-" xml:"-"`
  333. XCosGrantReadACP string `header:"x-cos-grant-read-acp,omitempty" url:"-" xml:"-"`
  334. XCosGrantWriteACP string `header:"x-cos-grant-write-acp,omitempty" url:"-" xml:"-"`
  335. }
  336. // ACLGrantee is the param of ACLGrant
  337. type ACLGrantee struct {
  338. Type string `xml:"type,attr"`
  339. UIN string `xml:"uin,omitempty"`
  340. URI string `xml:"URI,omitempty"`
  341. ID string `xml:",omitempty"`
  342. DisplayName string `xml:",omitempty"`
  343. SubAccount string `xml:"Subaccount,omitempty"`
  344. }
  345. // ACLGrant is the param of ACLXml
  346. type ACLGrant struct {
  347. Grantee *ACLGrantee
  348. Permission string
  349. }
  350. // ACLXml is the ACL body struct
  351. type ACLXml struct {
  352. XMLName xml.Name `xml:"AccessControlPolicy"`
  353. Owner *Owner
  354. AccessControlList []ACLGrant `xml:"AccessControlList>Grant,omitempty"`
  355. }
  356. func decodeACL(resp *Response, res *ACLXml) {
  357. ItemMap := map[string]string{
  358. "ACL": "x-cos-acl",
  359. "READ": "x-cos-grant-read",
  360. "WRITE": "x-cos-grant-write",
  361. "READ_ACP": "x-cos-grant-read-acp",
  362. "WRITE_ACP": "x-cos-grant-write-acp",
  363. "FULL_CONTROL": "x-cos-grant-full-control",
  364. }
  365. publicACL := make(map[string]int)
  366. resACL := make(map[string][]string)
  367. for _, item := range res.AccessControlList {
  368. if item.Grantee == nil {
  369. continue
  370. }
  371. if item.Grantee.ID == "qcs::cam::anyone:anyone" || item.Grantee.URI == "http://cam.qcloud.com/groups/global/AllUsers" {
  372. publicACL[item.Permission] = 1
  373. } else if item.Grantee.ID != res.Owner.ID {
  374. resACL[item.Permission] = append(resACL[item.Permission], "id=\""+item.Grantee.ID+"\"")
  375. }
  376. }
  377. if publicACL["FULL_CONTROL"] == 1 || (publicACL["READ"] == 1 && publicACL["WRITE"] == 1) {
  378. resACL["ACL"] = []string{"public-read-write"}
  379. } else if publicACL["READ"] == 1 {
  380. resACL["ACL"] = []string{"public-read"}
  381. } else {
  382. resACL["ACL"] = []string{"private"}
  383. }
  384. for item, header := range ItemMap {
  385. if len(resp.Header.Get(header)) > 0 || len(resACL[item]) == 0 {
  386. continue
  387. }
  388. resp.Header.Set(header, uniqueGrantID(resACL[item]))
  389. }
  390. }
  391. func uniqueGrantID(grantIDs []string) string {
  392. res := []string{}
  393. filter := make(map[string]int)
  394. for _, id := range grantIDs {
  395. if filter[id] != 0 {
  396. continue
  397. }
  398. filter[id] = 1
  399. res = append(res, id)
  400. }
  401. return strings.Join(res, ",")
  402. }