conn.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. if conn.config.SecurityToken != "" {
  211. params[HTTPParamSecurityToken] = conn.config.SecurityToken
  212. }
  213. subResource := conn.getSubResource(params)
  214. canonicalizedResource := conn.url.getResource(bucketName, objectName, subResource)
  215. m := strings.ToUpper(string(method))
  216. req := &http.Request{
  217. Method: m,
  218. Header: make(http.Header),
  219. }
  220. if conn.config.IsAuthProxy {
  221. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  222. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  223. req.Header.Set("Proxy-Authorization", basic)
  224. }
  225. req.Header.Set(HTTPHeaderDate, strconv.FormatInt(expiration, 10))
  226. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  227. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  228. if headers != nil {
  229. for k, v := range headers {
  230. req.Header.Set(k, v)
  231. }
  232. }
  233. signedStr := conn.getSignedStr(req, canonicalizedResource)
  234. params[HTTPParamExpires] = strconv.FormatInt(expiration, 10)
  235. params[HTTPParamAccessKeyID] = conn.config.AccessKeyID
  236. params[HTTPParamSignature] = signedStr
  237. urlParams := conn.getURLParams(params)
  238. return conn.url.getSignURL(bucketName, objectName, urlParams)
  239. }
  240. func (conn Conn) signRtmpURL(bucketName, channelName, playlistName string, expiration int64) string {
  241. params := map[string]interface{}{}
  242. if playlistName != "" {
  243. params[HTTPParamPlaylistName] = playlistName
  244. }
  245. expireStr := strconv.FormatInt(expiration, 10)
  246. params[HTTPParamExpires] = expireStr
  247. if conn.config.AccessKeyID != "" {
  248. params[HTTPParamAccessKeyID] = conn.config.AccessKeyID
  249. if conn.config.SecurityToken != "" {
  250. params[HTTPParamSecurityToken] = conn.config.SecurityToken
  251. }
  252. signedStr := conn.getRtmpSignedStr(bucketName, channelName, playlistName, expiration, params)
  253. params[HTTPParamSignature] = signedStr
  254. }
  255. urlParams := conn.getURLParams(params)
  256. return conn.url.getSignRtmpURL(bucketName, channelName, urlParams)
  257. }
  258. // handle request body
  259. func (conn Conn) handleBody(req *http.Request, body io.Reader, initCRC uint64,
  260. listener ProgressListener, tracker *readerTracker) (*os.File, hash.Hash64) {
  261. var file *os.File
  262. var crc hash.Hash64
  263. reader := body
  264. // length
  265. switch v := body.(type) {
  266. case *bytes.Buffer:
  267. req.ContentLength = int64(v.Len())
  268. case *bytes.Reader:
  269. req.ContentLength = int64(v.Len())
  270. case *strings.Reader:
  271. req.ContentLength = int64(v.Len())
  272. case *os.File:
  273. req.ContentLength = tryGetFileSize(v)
  274. case *io.LimitedReader:
  275. req.ContentLength = int64(v.N)
  276. }
  277. req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
  278. // md5
  279. if body != nil && conn.config.IsEnableMD5 && req.Header.Get(HTTPHeaderContentMD5) == "" {
  280. md5 := ""
  281. reader, md5, file, _ = calcMD5(body, req.ContentLength, conn.config.MD5Threshold)
  282. req.Header.Set(HTTPHeaderContentMD5, md5)
  283. }
  284. // crc
  285. if reader != nil && conn.config.IsEnableCRC {
  286. crc = NewCRC(crcTable(), initCRC)
  287. reader = TeeReader(reader, crc, req.ContentLength, listener, tracker)
  288. }
  289. // http body
  290. rc, ok := reader.(io.ReadCloser)
  291. if !ok && reader != nil {
  292. rc = ioutil.NopCloser(reader)
  293. }
  294. req.Body = rc
  295. return file, crc
  296. }
  297. func tryGetFileSize(f *os.File) int64 {
  298. fInfo, _ := f.Stat()
  299. return fInfo.Size()
  300. }
  301. // handle response
  302. func (conn Conn) handleResponse(resp *http.Response, crc hash.Hash64) (*Response, error) {
  303. var cliCRC uint64
  304. var srvCRC uint64
  305. statusCode := resp.StatusCode
  306. if statusCode >= 400 && statusCode <= 505 {
  307. // 4xx and 5xx indicate that the operation has error occurred
  308. var respBody []byte
  309. respBody, err := readResponseBody(resp)
  310. if err != nil {
  311. return nil, err
  312. }
  313. if len(respBody) == 0 {
  314. // no error in response body
  315. err = fmt.Errorf("oss: service returned without a response body (%s)", resp.Status)
  316. } else {
  317. // response contains storage service error object, unmarshal
  318. srvErr, errIn := serviceErrFromXML(respBody, resp.StatusCode,
  319. resp.Header.Get(HTTPHeaderOssRequestID))
  320. if err != nil { // error unmarshaling the error response
  321. err = errIn
  322. }
  323. err = srvErr
  324. }
  325. return &Response{
  326. StatusCode: resp.StatusCode,
  327. Headers: resp.Header,
  328. Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body
  329. }, err
  330. } else if statusCode >= 300 && statusCode <= 307 {
  331. // oss use 3xx, but response has no body
  332. err := fmt.Errorf("oss: service returned %d,%s", resp.StatusCode, resp.Status)
  333. return &Response{
  334. StatusCode: resp.StatusCode,
  335. Headers: resp.Header,
  336. Body: resp.Body,
  337. }, err
  338. }
  339. if conn.config.IsEnableCRC && crc != nil {
  340. cliCRC = crc.Sum64()
  341. }
  342. srvCRC, _ = strconv.ParseUint(resp.Header.Get(HTTPHeaderOssCRC64), 10, 64)
  343. // 2xx, successful
  344. return &Response{
  345. StatusCode: resp.StatusCode,
  346. Headers: resp.Header,
  347. Body: resp.Body,
  348. ClientCRC: cliCRC,
  349. ServerCRC: srvCRC,
  350. }, nil
  351. }
  352. func calcMD5(body io.Reader, contentLen, md5Threshold int64) (reader io.Reader, b64 string, tempFile *os.File, err error) {
  353. if contentLen == 0 || contentLen > md5Threshold {
  354. // huge body, use temporary file
  355. tempFile, err = ioutil.TempFile(os.TempDir(), TempFilePrefix)
  356. if tempFile != nil {
  357. io.Copy(tempFile, body)
  358. tempFile.Seek(0, os.SEEK_SET)
  359. md5 := md5.New()
  360. io.Copy(md5, tempFile)
  361. sum := md5.Sum(nil)
  362. b64 = base64.StdEncoding.EncodeToString(sum[:])
  363. tempFile.Seek(0, os.SEEK_SET)
  364. reader = tempFile
  365. }
  366. } else {
  367. // small body, use memory
  368. buf, _ := ioutil.ReadAll(body)
  369. sum := md5.Sum(buf)
  370. b64 = base64.StdEncoding.EncodeToString(sum[:])
  371. reader = bytes.NewReader(buf)
  372. }
  373. return
  374. }
  375. func readResponseBody(resp *http.Response) ([]byte, error) {
  376. defer resp.Body.Close()
  377. out, err := ioutil.ReadAll(resp.Body)
  378. if err == io.EOF {
  379. err = nil
  380. }
  381. return out, err
  382. }
  383. func serviceErrFromXML(body []byte, statusCode int, requestID string) (ServiceError, error) {
  384. var storageErr ServiceError
  385. if err := xml.Unmarshal(body, &storageErr); err != nil {
  386. return storageErr, err
  387. }
  388. storageErr.StatusCode = statusCode
  389. storageErr.RequestID = requestID
  390. storageErr.RawMessage = string(body)
  391. return storageErr, nil
  392. }
  393. func xmlUnmarshal(body io.Reader, v interface{}) error {
  394. data, err := ioutil.ReadAll(body)
  395. if err != nil {
  396. return err
  397. }
  398. return xml.Unmarshal(data, v)
  399. }
  400. // Handle http timeout
  401. type timeoutConn struct {
  402. conn net.Conn
  403. timeout time.Duration
  404. longTimeout time.Duration
  405. }
  406. func newTimeoutConn(conn net.Conn, timeout time.Duration, longTimeout time.Duration) *timeoutConn {
  407. conn.SetReadDeadline(time.Now().Add(longTimeout))
  408. return &timeoutConn{
  409. conn: conn,
  410. timeout: timeout,
  411. longTimeout: longTimeout,
  412. }
  413. }
  414. func (c *timeoutConn) Read(b []byte) (n int, err error) {
  415. c.SetReadDeadline(time.Now().Add(c.timeout))
  416. n, err = c.conn.Read(b)
  417. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  418. return n, err
  419. }
  420. func (c *timeoutConn) Write(b []byte) (n int, err error) {
  421. c.SetWriteDeadline(time.Now().Add(c.timeout))
  422. n, err = c.conn.Write(b)
  423. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  424. return n, err
  425. }
  426. func (c *timeoutConn) Close() error {
  427. return c.conn.Close()
  428. }
  429. func (c *timeoutConn) LocalAddr() net.Addr {
  430. return c.conn.LocalAddr()
  431. }
  432. func (c *timeoutConn) RemoteAddr() net.Addr {
  433. return c.conn.RemoteAddr()
  434. }
  435. func (c *timeoutConn) SetDeadline(t time.Time) error {
  436. return c.conn.SetDeadline(t)
  437. }
  438. func (c *timeoutConn) SetReadDeadline(t time.Time) error {
  439. return c.conn.SetReadDeadline(t)
  440. }
  441. func (c *timeoutConn) SetWriteDeadline(t time.Time) error {
  442. return c.conn.SetWriteDeadline(t)
  443. }
  444. // UrlMaker - build url and resource
  445. const (
  446. urlTypeCname = 1
  447. urlTypeIP = 2
  448. urlTypeAliyun = 3
  449. )
  450. type urlMaker struct {
  451. Scheme string // http or https
  452. NetLoc string // host or ip
  453. Type int // 1 CNAME 2 IP 3 ALIYUN
  454. IsProxy bool // proxy
  455. }
  456. // Parse endpoint
  457. func (um *urlMaker) Init(endpoint string, isCname bool, isProxy bool) {
  458. if strings.HasPrefix(endpoint, "http://") {
  459. um.Scheme = "http"
  460. um.NetLoc = endpoint[len("http://"):]
  461. } else if strings.HasPrefix(endpoint, "https://") {
  462. um.Scheme = "https"
  463. um.NetLoc = endpoint[len("https://"):]
  464. } else {
  465. um.Scheme = "http"
  466. um.NetLoc = endpoint
  467. }
  468. host, _, err := net.SplitHostPort(um.NetLoc)
  469. if err != nil {
  470. host = um.NetLoc
  471. }
  472. ip := net.ParseIP(host)
  473. if ip != nil {
  474. um.Type = urlTypeIP
  475. } else if isCname {
  476. um.Type = urlTypeCname
  477. } else {
  478. um.Type = urlTypeAliyun
  479. }
  480. um.IsProxy = isProxy
  481. }
  482. // Build URL
  483. func (um urlMaker) getURL(bucket, object, params string) *url.URL {
  484. host, path := um.buildURL(bucket, object)
  485. addr := ""
  486. if params == "" {
  487. addr = fmt.Sprintf("%s://%s%s", um.Scheme, host, path)
  488. } else {
  489. addr = fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  490. }
  491. uri, _ := url.ParseRequestURI(addr)
  492. return uri
  493. }
  494. // Build Sign URL
  495. func (um urlMaker) getSignURL(bucket, object, params string) string {
  496. host, path := um.buildURL(bucket, object)
  497. return fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  498. }
  499. // Build Sign Rtmp URL
  500. func (um urlMaker) getSignRtmpURL(bucket, channelName, params string) string {
  501. host, path := um.buildURL(bucket, "live")
  502. channelName = url.QueryEscape(channelName)
  503. channelName = strings.Replace(channelName, "+", "%20", -1)
  504. return fmt.Sprintf("rtmp://%s%s/%s?%s", host, path, channelName, params)
  505. }
  506. // Build URL
  507. func (um urlMaker) buildURL(bucket, object string) (string, string) {
  508. var host = ""
  509. var path = ""
  510. object = url.QueryEscape(object)
  511. object = strings.Replace(object, "+", "%20", -1)
  512. if um.Type == urlTypeCname {
  513. host = um.NetLoc
  514. path = "/" + object
  515. } else if um.Type == urlTypeIP {
  516. if bucket == "" {
  517. host = um.NetLoc
  518. path = "/"
  519. } else {
  520. host = um.NetLoc
  521. path = fmt.Sprintf("/%s/%s", bucket, object)
  522. }
  523. } else {
  524. if bucket == "" {
  525. host = um.NetLoc
  526. path = "/"
  527. } else {
  528. host = bucket + "." + um.NetLoc
  529. path = "/" + object
  530. }
  531. }
  532. return host, path
  533. }
  534. // Canonicalized Resource
  535. func (um urlMaker) getResource(bucketName, objectName, subResource string) string {
  536. if subResource != "" {
  537. subResource = "?" + subResource
  538. }
  539. if bucketName == "" {
  540. return fmt.Sprintf("/%s%s", bucketName, subResource)
  541. }
  542. return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource)
  543. }