conn.go 16 KB

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