conn.go 15 KB

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