conn.go 16 KB

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