conn.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. package oss
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/base64"
  6. "encoding/json"
  7. "encoding/xml"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "net/http"
  14. "net/url"
  15. "os"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. // Conn defines OSS Conn
  22. type Conn struct {
  23. config *Config
  24. url *urlMaker
  25. client *http.Client
  26. }
  27. var signKeyList = []string{"acl", "uploads", "location", "cors", "logging", "website", "referer", "lifecycle", "delete", "append", "tagging", "objectMeta", "uploadId", "partNumber", "security-token", "position", "img", "style", "styleName", "replication", "replicationProgress", "replicationLocation", "cname", "bucketInfo", "comp", "qos", "live", "status", "vod", "startTime", "endTime", "symlink", "x-oss-process", "response-content-type", "response-content-language", "response-expires", "response-cache-control", "response-content-disposition", "response-content-encoding", "udf", "udfName", "udfImage", "udfId", "udfImageDesc", "udfApplication", "comp", "udfApplicationLog", "restore", "callback", "callback-var"}
  28. // init initializes Conn
  29. func (conn *Conn) init(config *Config, urlMaker *urlMaker) error {
  30. // New transport
  31. transport := newTransport(conn, config)
  32. // Proxy
  33. if conn.config.IsUseProxy {
  34. proxyURL, err := url.Parse(config.ProxyHost)
  35. if err != nil {
  36. return err
  37. }
  38. transport.Proxy = http.ProxyURL(proxyURL)
  39. }
  40. conn.config = config
  41. conn.url = urlMaker
  42. conn.client = &http.Client{Transport: transport}
  43. return nil
  44. }
  45. // Do sends request and returns the response
  46. func (conn Conn) Do(method, bucketName, objectName string, params map[string]interface{}, headers map[string]string,
  47. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  48. urlParams := conn.getURLParams(params)
  49. subResource := conn.getSubResource(params)
  50. uri := conn.url.getURL(bucketName, objectName, urlParams)
  51. resource := conn.url.getResource(bucketName, objectName, subResource)
  52. return conn.doRequest(method, uri, resource, headers, data, initCRC, listener)
  53. }
  54. // DoURL sends the request with signed URL and returns the response result.
  55. func (conn Conn) DoURL(method HTTPMethod, signedURL string, headers map[string]string,
  56. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  57. // Get URI from signedURL
  58. uri, err := url.ParseRequestURI(signedURL)
  59. if err != nil {
  60. return nil, err
  61. }
  62. m := strings.ToUpper(string(method))
  63. req := &http.Request{
  64. Method: m,
  65. URL: uri,
  66. Proto: "HTTP/1.1",
  67. ProtoMajor: 1,
  68. ProtoMinor: 1,
  69. Header: make(http.Header),
  70. Host: uri.Host,
  71. }
  72. tracker := &readerTracker{completedBytes: 0}
  73. fd, crc := conn.handleBody(req, data, initCRC, listener, tracker)
  74. if fd != nil {
  75. defer func() {
  76. fd.Close()
  77. os.Remove(fd.Name())
  78. }()
  79. }
  80. if conn.config.IsAuthProxy {
  81. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  82. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  83. req.Header.Set("Proxy-Authorization", basic)
  84. }
  85. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  86. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  87. if headers != nil {
  88. for k, v := range headers {
  89. req.Header.Set(k, v)
  90. }
  91. }
  92. // Transfer started
  93. event := newProgressEvent(TransferStartedEvent, 0, req.ContentLength)
  94. publishProgress(listener, event)
  95. resp, err := conn.client.Do(req)
  96. if err != nil {
  97. // Transfer failed
  98. event = newProgressEvent(TransferFailedEvent, tracker.completedBytes, req.ContentLength)
  99. publishProgress(listener, event)
  100. return nil, err
  101. }
  102. // Transfer completed
  103. event = newProgressEvent(TransferCompletedEvent, tracker.completedBytes, req.ContentLength)
  104. publishProgress(listener, event)
  105. return conn.handleResponse(resp, crc)
  106. }
  107. func (conn Conn) getURLParams(params map[string]interface{}) string {
  108. // Sort
  109. keys := make([]string, 0, len(params))
  110. for k := range params {
  111. keys = append(keys, k)
  112. }
  113. sort.Strings(keys)
  114. // Serialize
  115. var buf bytes.Buffer
  116. for _, k := range keys {
  117. if buf.Len() > 0 {
  118. buf.WriteByte('&')
  119. }
  120. buf.WriteString(url.QueryEscape(k))
  121. if params[k] != nil {
  122. buf.WriteString("=" + url.QueryEscape(params[k].(string)))
  123. }
  124. }
  125. return buf.String()
  126. }
  127. func (conn Conn) getSubResource(params map[string]interface{}) string {
  128. // Sort
  129. keys := make([]string, 0, len(params))
  130. for k := range params {
  131. if conn.isParamSign(k) {
  132. keys = append(keys, k)
  133. }
  134. }
  135. sort.Strings(keys)
  136. // Serialize
  137. var buf bytes.Buffer
  138. for _, k := range keys {
  139. if buf.Len() > 0 {
  140. buf.WriteByte('&')
  141. }
  142. buf.WriteString(k)
  143. if params[k] != nil {
  144. buf.WriteString("=" + params[k].(string))
  145. }
  146. }
  147. return buf.String()
  148. }
  149. func (conn Conn) isParamSign(paramKey string) bool {
  150. for _, k := range signKeyList {
  151. if paramKey == k {
  152. return true
  153. }
  154. }
  155. return false
  156. }
  157. func (conn Conn) doRequest(method string, uri *url.URL, canonicalizedResource string, headers map[string]string,
  158. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  159. method = strings.ToUpper(method)
  160. req := &http.Request{
  161. Method: method,
  162. URL: uri,
  163. Proto: "HTTP/1.1",
  164. ProtoMajor: 1,
  165. ProtoMinor: 1,
  166. Header: make(http.Header),
  167. Host: uri.Host,
  168. }
  169. tracker := &readerTracker{completedBytes: 0}
  170. fd, crc := conn.handleBody(req, data, initCRC, listener, tracker)
  171. if fd != nil {
  172. defer func() {
  173. fd.Close()
  174. os.Remove(fd.Name())
  175. }()
  176. }
  177. if conn.config.IsAuthProxy {
  178. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  179. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  180. req.Header.Set("Proxy-Authorization", basic)
  181. }
  182. date := time.Now().UTC().Format(http.TimeFormat)
  183. req.Header.Set(HTTPHeaderDate, date)
  184. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  185. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  186. if conn.config.SecurityToken != "" {
  187. req.Header.Set(HTTPHeaderOssSecurityToken, conn.config.SecurityToken)
  188. }
  189. if headers != nil {
  190. for k, v := range headers {
  191. req.Header.Set(k, v)
  192. }
  193. }
  194. conn.signHeader(req, canonicalizedResource)
  195. // Transfer started
  196. event := newProgressEvent(TransferStartedEvent, 0, req.ContentLength)
  197. publishProgress(listener, event)
  198. resp, err := conn.client.Do(req)
  199. if err != nil {
  200. // Transfer failed
  201. event = newProgressEvent(TransferFailedEvent, tracker.completedBytes, req.ContentLength)
  202. publishProgress(listener, event)
  203. return nil, err
  204. }
  205. // Transfer completed
  206. event = newProgressEvent(TransferCompletedEvent, tracker.completedBytes, req.ContentLength)
  207. publishProgress(listener, event)
  208. return conn.handleResponse(resp, crc)
  209. }
  210. func (conn Conn) signURL(method HTTPMethod, bucketName, objectName string, expiration int64, params map[string]interface{}, headers map[string]string) string {
  211. if conn.config.SecurityToken != "" {
  212. params[HTTPParamSecurityToken] = conn.config.SecurityToken
  213. }
  214. subResource := conn.getSubResource(params)
  215. canonicalizedResource := conn.url.getResource(bucketName, objectName, subResource)
  216. m := strings.ToUpper(string(method))
  217. req := &http.Request{
  218. Method: m,
  219. Header: make(http.Header),
  220. }
  221. if conn.config.IsAuthProxy {
  222. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  223. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  224. req.Header.Set("Proxy-Authorization", basic)
  225. }
  226. req.Header.Set(HTTPHeaderDate, strconv.FormatInt(expiration, 10))
  227. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  228. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  229. if headers != nil {
  230. for k, v := range headers {
  231. req.Header.Set(k, v)
  232. }
  233. }
  234. signedStr := conn.getSignedStr(req, canonicalizedResource)
  235. params[HTTPParamExpires] = strconv.FormatInt(expiration, 10)
  236. params[HTTPParamAccessKeyID] = conn.config.AccessKeyID
  237. params[HTTPParamSignature] = signedStr
  238. urlParams := conn.getURLParams(params)
  239. return conn.url.getSignURL(bucketName, objectName, urlParams)
  240. }
  241. // handleBody handles request body
  242. func (conn Conn) handleBody(req *http.Request, body io.Reader, initCRC uint64,
  243. listener ProgressListener, tracker *readerTracker) (*os.File, hash.Hash64) {
  244. var file *os.File
  245. var crc hash.Hash64
  246. reader := body
  247. // Length
  248. switch v := body.(type) {
  249. case *bytes.Buffer:
  250. req.ContentLength = int64(v.Len())
  251. case *bytes.Reader:
  252. req.ContentLength = int64(v.Len())
  253. case *strings.Reader:
  254. req.ContentLength = int64(v.Len())
  255. case *os.File:
  256. req.ContentLength = tryGetFileSize(v)
  257. case *io.LimitedReader:
  258. req.ContentLength = int64(v.N)
  259. }
  260. req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
  261. // MD5
  262. if body != nil && conn.config.IsEnableMD5 && req.Header.Get(HTTPHeaderContentMD5) == "" {
  263. md5 := ""
  264. reader, md5, file, _ = calcMD5(body, req.ContentLength, conn.config.MD5Threshold)
  265. req.Header.Set(HTTPHeaderContentMD5, md5)
  266. }
  267. // CRC
  268. if reader != nil && conn.config.IsEnableCRC {
  269. crc = NewCRC(crcTable(), initCRC)
  270. reader = TeeReader(reader, crc, req.ContentLength, listener, tracker)
  271. }
  272. // HTTP body
  273. rc, ok := reader.(io.ReadCloser)
  274. if !ok && reader != nil {
  275. rc = ioutil.NopCloser(reader)
  276. }
  277. req.Body = rc
  278. return file, crc
  279. }
  280. func tryGetFileSize(f *os.File) int64 {
  281. fInfo, _ := f.Stat()
  282. return fInfo.Size()
  283. }
  284. // handleResponse handles response
  285. func (conn Conn) handleResponse(resp *http.Response, crc hash.Hash64) (*Response, error) {
  286. var cliCRC uint64
  287. var srvCRC uint64
  288. statusCode := resp.StatusCode
  289. if statusCode >= 400 && statusCode <= 505 {
  290. // 4xx and 5xx indicate that the operation has error occurred
  291. var respBody []byte
  292. respBody, err := readResponseBody(resp)
  293. if err != nil {
  294. return nil, err
  295. }
  296. if len(respBody) == 0 {
  297. // No error in response body
  298. err = fmt.Errorf("oss: service returned empty response body, status = %s, RequestId = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID))
  299. } else {
  300. // Response contains storage service error object, unmarshal
  301. srvErr, errIn := serviceErrFromXML(respBody, resp.StatusCode,
  302. resp.Header.Get(HTTPHeaderOssRequestID))
  303. if errIn != nil { // error unmarshaling the error response
  304. err = fmt.Errorf("oss: service returned invalid response body, status = %s, RequestId = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID))
  305. } else {
  306. err = srvErr
  307. }
  308. }
  309. return &Response{
  310. StatusCode: resp.StatusCode,
  311. Headers: resp.Header,
  312. Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body
  313. }, err
  314. } else if statusCode >= 300 && statusCode <= 307 {
  315. // OSS use 3xx, but response has no body
  316. err := fmt.Errorf("oss: service returned %d,%s", resp.StatusCode, resp.Status)
  317. return &Response{
  318. StatusCode: resp.StatusCode,
  319. Headers: resp.Header,
  320. Body: resp.Body,
  321. }, err
  322. }
  323. if conn.config.IsEnableCRC && crc != nil {
  324. cliCRC = crc.Sum64()
  325. }
  326. srvCRC, _ = strconv.ParseUint(resp.Header.Get(HTTPHeaderOssCRC64), 10, 64)
  327. // 2xx, successful
  328. return &Response{
  329. StatusCode: resp.StatusCode,
  330. Headers: resp.Header,
  331. Body: resp.Body,
  332. ClientCRC: cliCRC,
  333. ServerCRC: srvCRC,
  334. }, nil
  335. }
  336. func calcMD5(body io.Reader, contentLen, md5Threshold int64) (reader io.Reader, b64 string, tempFile *os.File, err error) {
  337. if contentLen == 0 || contentLen > md5Threshold {
  338. // Huge body, use temporary file
  339. tempFile, err = ioutil.TempFile(os.TempDir(), TempFilePrefix)
  340. if tempFile != nil {
  341. io.Copy(tempFile, body)
  342. tempFile.Seek(0, os.SEEK_SET)
  343. md5 := md5.New()
  344. io.Copy(md5, tempFile)
  345. sum := md5.Sum(nil)
  346. b64 = base64.StdEncoding.EncodeToString(sum[:])
  347. tempFile.Seek(0, os.SEEK_SET)
  348. reader = tempFile
  349. }
  350. } else {
  351. // Small body, use memory
  352. buf, _ := ioutil.ReadAll(body)
  353. sum := md5.Sum(buf)
  354. b64 = base64.StdEncoding.EncodeToString(sum[:])
  355. reader = bytes.NewReader(buf)
  356. }
  357. return
  358. }
  359. func readResponseBody(resp *http.Response) ([]byte, error) {
  360. defer resp.Body.Close()
  361. out, err := ioutil.ReadAll(resp.Body)
  362. if err == io.EOF {
  363. err = nil
  364. }
  365. return out, err
  366. }
  367. func serviceErrFromXML(body []byte, statusCode int, requestID string) (ServiceError, error) {
  368. var storageErr ServiceError
  369. if err := xml.Unmarshal(body, &storageErr); err != nil {
  370. return storageErr, err
  371. }
  372. storageErr.StatusCode = statusCode
  373. storageErr.RequestID = requestID
  374. storageErr.RawMessage = string(body)
  375. return storageErr, nil
  376. }
  377. func xmlUnmarshal(body io.Reader, v interface{}) error {
  378. data, err := ioutil.ReadAll(body)
  379. if err != nil {
  380. return err
  381. }
  382. return xml.Unmarshal(data, v)
  383. }
  384. func jsonUnmarshal(body io.Reader, v interface{}) error {
  385. data, err := ioutil.ReadAll(body)
  386. if err != nil {
  387. return err
  388. }
  389. return json.Unmarshal(data, v)
  390. }
  391. // timeoutConn handles HTTP timeout
  392. type timeoutConn struct {
  393. conn net.Conn
  394. timeout time.Duration
  395. longTimeout time.Duration
  396. }
  397. func newTimeoutConn(conn net.Conn, timeout time.Duration, longTimeout time.Duration) *timeoutConn {
  398. conn.SetReadDeadline(time.Now().Add(longTimeout))
  399. return &timeoutConn{
  400. conn: conn,
  401. timeout: timeout,
  402. longTimeout: longTimeout,
  403. }
  404. }
  405. func (c *timeoutConn) Read(b []byte) (n int, err error) {
  406. c.SetReadDeadline(time.Now().Add(c.timeout))
  407. n, err = c.conn.Read(b)
  408. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  409. return n, err
  410. }
  411. func (c *timeoutConn) Write(b []byte) (n int, err error) {
  412. c.SetWriteDeadline(time.Now().Add(c.timeout))
  413. n, err = c.conn.Write(b)
  414. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  415. return n, err
  416. }
  417. func (c *timeoutConn) Close() error {
  418. return c.conn.Close()
  419. }
  420. func (c *timeoutConn) LocalAddr() net.Addr {
  421. return c.conn.LocalAddr()
  422. }
  423. func (c *timeoutConn) RemoteAddr() net.Addr {
  424. return c.conn.RemoteAddr()
  425. }
  426. func (c *timeoutConn) SetDeadline(t time.Time) error {
  427. return c.conn.SetDeadline(t)
  428. }
  429. func (c *timeoutConn) SetReadDeadline(t time.Time) error {
  430. return c.conn.SetReadDeadline(t)
  431. }
  432. func (c *timeoutConn) SetWriteDeadline(t time.Time) error {
  433. return c.conn.SetWriteDeadline(t)
  434. }
  435. // UrlMaker builds URL and resource
  436. const (
  437. urlTypeCname = 1
  438. urlTypeIP = 2
  439. urlTypeAliyun = 3
  440. )
  441. type urlMaker struct {
  442. Scheme string // HTTP or HTTPS
  443. NetLoc string // Host or IP
  444. Type int // 1 CNAME, 2 IP, 3 ALIYUN
  445. IsProxy bool // Proxy
  446. }
  447. // Init parses endpoint
  448. func (um *urlMaker) Init(endpoint string, isCname bool, isProxy bool) {
  449. if strings.HasPrefix(endpoint, "http://") {
  450. um.Scheme = "http"
  451. um.NetLoc = endpoint[len("http://"):]
  452. } else if strings.HasPrefix(endpoint, "https://") {
  453. um.Scheme = "https"
  454. um.NetLoc = endpoint[len("https://"):]
  455. } else {
  456. um.Scheme = "http"
  457. um.NetLoc = endpoint
  458. }
  459. host, _, err := net.SplitHostPort(um.NetLoc)
  460. if err != nil {
  461. host = um.NetLoc
  462. if host[0] == '[' && host[len(host)-1] == ']' {
  463. host = host[1 : len(host)-1]
  464. }
  465. }
  466. ip := net.ParseIP(host)
  467. if ip != nil {
  468. um.Type = urlTypeIP
  469. } else if isCname {
  470. um.Type = urlTypeCname
  471. } else {
  472. um.Type = urlTypeAliyun
  473. }
  474. um.IsProxy = isProxy
  475. }
  476. // getURL gets URL
  477. func (um urlMaker) getURL(bucket, object, params string) *url.URL {
  478. host, path := um.buildURL(bucket, object)
  479. addr := ""
  480. if params == "" {
  481. addr = fmt.Sprintf("%s://%s%s", um.Scheme, host, path)
  482. } else {
  483. addr = fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  484. }
  485. uri, _ := url.ParseRequestURI(addr)
  486. return uri
  487. }
  488. // getSignURL gets sign URL
  489. func (um urlMaker) getSignURL(bucket, object, params string) string {
  490. host, path := um.buildURL(bucket, object)
  491. return fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  492. }
  493. // buildURL builds URL
  494. func (um urlMaker) buildURL(bucket, object string) (string, string) {
  495. var host = ""
  496. var path = ""
  497. object = url.QueryEscape(object)
  498. object = strings.Replace(object, "+", "%20", -1)
  499. if um.Type == urlTypeCname {
  500. host = um.NetLoc
  501. path = "/" + object
  502. } else if um.Type == urlTypeIP {
  503. if bucket == "" {
  504. host = um.NetLoc
  505. path = "/"
  506. } else {
  507. host = um.NetLoc
  508. path = fmt.Sprintf("/%s/%s", bucket, object)
  509. }
  510. } else {
  511. if bucket == "" {
  512. host = um.NetLoc
  513. path = "/"
  514. } else {
  515. host = bucket + "." + um.NetLoc
  516. path = "/" + object
  517. }
  518. }
  519. return host, path
  520. }
  521. // getResource gets canonicalized resource
  522. func (um urlMaker) getResource(bucketName, objectName, subResource string) string {
  523. if subResource != "" {
  524. subResource = "?" + subResource
  525. }
  526. if bucketName == "" {
  527. return fmt.Sprintf("/%s%s", bucketName, subResource)
  528. }
  529. return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource)
  530. }