conn.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. // Conn oss conn
  20. type Conn struct {
  21. config *Config
  22. url *urlMaker
  23. client *http.Client
  24. }
  25. // init 初始化Conn
  26. func (conn *Conn) init(config *Config, urlMaker *urlMaker) error {
  27. httpTimeOut := conn.config.HTTPTimeout
  28. // new Transport
  29. transport := &http.Transport{
  30. Dial: func(netw, addr string) (net.Conn, error) {
  31. conn, err := net.DialTimeout(netw, addr, httpTimeOut.ConnectTimeout)
  32. if err != nil {
  33. return nil, err
  34. }
  35. return newTimeoutConn(conn, httpTimeOut.ReadWriteTimeout, httpTimeOut.LongTimeout), nil
  36. },
  37. ResponseHeaderTimeout: httpTimeOut.HeaderTimeout,
  38. MaxIdleConnsPerHost: 2000,
  39. }
  40. // Proxy
  41. if conn.config.IsUseProxy {
  42. proxyURL, err := url.Parse(config.ProxyHost)
  43. if err != nil {
  44. return err
  45. }
  46. transport.Proxy = http.ProxyURL(proxyURL)
  47. }
  48. conn.config = config
  49. conn.url = urlMaker
  50. conn.client = &http.Client{Transport: transport}
  51. return nil
  52. }
  53. // Do 处理请求,返回响应结果。
  54. func (conn Conn) Do(method, bucketName, objectName, urlParams, subResource string, headers map[string]string,
  55. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  56. uri := conn.url.getURL(bucketName, objectName, urlParams)
  57. resource := conn.url.getResource(bucketName, objectName, subResource)
  58. return conn.doRequest(method, uri, resource, headers, data, initCRC, listener)
  59. }
  60. func (conn Conn) doRequest(method string, uri *url.URL, canonicalizedResource string, headers map[string]string,
  61. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  62. method = strings.ToUpper(method)
  63. if !conn.config.IsUseProxy {
  64. uri.Opaque = uri.Path
  65. }
  66. req := &http.Request{
  67. Method: method,
  68. URL: uri,
  69. Proto: "HTTP/1.1",
  70. ProtoMajor: 1,
  71. ProtoMinor: 1,
  72. Header: make(http.Header),
  73. Host: uri.Host,
  74. }
  75. tracker := &readerTracker{completedBytes: 0}
  76. fd, crc := conn.handleBody(req, data, initCRC, listener, tracker)
  77. if fd != nil {
  78. defer func() {
  79. fd.Close()
  80. os.Remove(fd.Name())
  81. }()
  82. }
  83. if conn.config.IsAuthProxy {
  84. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  85. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  86. req.Header.Set("Proxy-Authorization", basic)
  87. }
  88. date := time.Now().UTC().Format(http.TimeFormat)
  89. req.Header.Set(HTTPHeaderDate, date)
  90. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  91. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  92. if conn.config.SecurityToken != "" {
  93. req.Header.Set(HTTPHeaderOssSecurityToken, conn.config.SecurityToken)
  94. }
  95. if headers != nil {
  96. for k, v := range headers {
  97. req.Header.Set(k, v)
  98. }
  99. }
  100. conn.signHeader(req, canonicalizedResource)
  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. // handle request body
  117. func (conn Conn) handleBody(req *http.Request, body io.Reader, initCRC uint64,
  118. listener ProgressListener, tracker *readerTracker) (*os.File, hash.Hash64) {
  119. var file *os.File
  120. var crc hash.Hash64
  121. reader := body
  122. // length
  123. switch v := body.(type) {
  124. case *bytes.Buffer:
  125. req.ContentLength = int64(v.Len())
  126. case *bytes.Reader:
  127. req.ContentLength = int64(v.Len())
  128. case *strings.Reader:
  129. req.ContentLength = int64(v.Len())
  130. case *os.File:
  131. req.ContentLength = tryGetFileSize(v)
  132. case *io.LimitedReader:
  133. req.ContentLength = int64(v.N)
  134. }
  135. req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
  136. // md5
  137. if body != nil && conn.config.IsEnableMD5 && req.Header.Get(HTTPHeaderContentMD5) == "" {
  138. md5 := ""
  139. reader, md5, file, _ = calcMD5(body, req.ContentLength, conn.config.MD5Threshold)
  140. req.Header.Set(HTTPHeaderContentMD5, md5)
  141. }
  142. // crc
  143. if reader != nil && conn.config.IsEnableCRC {
  144. crc = NewCRC(crcTable(), initCRC)
  145. reader = TeeReader(reader, crc, req.ContentLength, listener, tracker)
  146. }
  147. // http body
  148. rc, ok := reader.(io.ReadCloser)
  149. if !ok && reader != nil {
  150. rc = ioutil.NopCloser(reader)
  151. }
  152. req.Body = rc
  153. return file, crc
  154. }
  155. func tryGetFileSize(f *os.File) int64 {
  156. fInfo, _ := f.Stat()
  157. return fInfo.Size()
  158. }
  159. // handle response
  160. func (conn Conn) handleResponse(resp *http.Response, crc hash.Hash64) (*Response, error) {
  161. var cliCRC uint64
  162. var srvCRC uint64
  163. statusCode := resp.StatusCode
  164. if statusCode >= 400 && statusCode <= 505 {
  165. // 4xx and 5xx indicate that the operation has error occurred
  166. var respBody []byte
  167. respBody, err := readResponseBody(resp)
  168. if err != nil {
  169. return nil, err
  170. }
  171. if len(respBody) == 0 {
  172. // no error in response body
  173. err = fmt.Errorf("oss: service returned without a response body (%s)", resp.Status)
  174. } else {
  175. // response contains storage service error object, unmarshal
  176. srvErr, errIn := serviceErrFromXML(respBody, resp.StatusCode,
  177. resp.Header.Get(HTTPHeaderOssRequestID))
  178. if err != nil { // error unmarshaling the error response
  179. err = errIn
  180. }
  181. err = srvErr
  182. }
  183. return &Response{
  184. StatusCode: resp.StatusCode,
  185. Headers: resp.Header,
  186. Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body
  187. }, err
  188. } else if statusCode >= 300 && statusCode <= 307 {
  189. // oss use 3xx, but response has no body
  190. err := fmt.Errorf("oss: service returned %d,%s", resp.StatusCode, resp.Status)
  191. return &Response{
  192. StatusCode: resp.StatusCode,
  193. Headers: resp.Header,
  194. Body: resp.Body,
  195. }, err
  196. }
  197. if conn.config.IsEnableCRC && crc != nil {
  198. cliCRC = crc.Sum64()
  199. }
  200. srvCRC, _ = strconv.ParseUint(resp.Header.Get(HTTPHeaderOssCRC64), 10, 64)
  201. // 2xx, successful
  202. return &Response{
  203. StatusCode: resp.StatusCode,
  204. Headers: resp.Header,
  205. Body: resp.Body,
  206. ClientCRC: cliCRC,
  207. ServerCRC: srvCRC,
  208. }, nil
  209. }
  210. func calcMD5(body io.Reader, contentLen, md5Threshold int64) (reader io.Reader, b64 string, tempFile *os.File, err error) {
  211. if contentLen == 0 || contentLen > md5Threshold {
  212. // huge body, use temporary file
  213. tempFile, err = ioutil.TempFile(os.TempDir(), TempFilePrefix)
  214. if tempFile != nil {
  215. io.Copy(tempFile, body)
  216. tempFile.Seek(0, os.SEEK_SET)
  217. md5 := md5.New()
  218. io.Copy(md5, tempFile)
  219. sum := md5.Sum(nil)
  220. b64 = base64.StdEncoding.EncodeToString(sum[:])
  221. tempFile.Seek(0, os.SEEK_SET)
  222. reader = tempFile
  223. }
  224. } else {
  225. // small body, use memory
  226. buf, _ := ioutil.ReadAll(body)
  227. sum := md5.Sum(buf)
  228. b64 = base64.StdEncoding.EncodeToString(sum[:])
  229. reader = bytes.NewReader(buf)
  230. }
  231. return
  232. }
  233. func readResponseBody(resp *http.Response) ([]byte, error) {
  234. defer resp.Body.Close()
  235. out, err := ioutil.ReadAll(resp.Body)
  236. if err == io.EOF {
  237. err = nil
  238. }
  239. return out, err
  240. }
  241. func serviceErrFromXML(body []byte, statusCode int, requestID string) (ServiceError, error) {
  242. var storageErr ServiceError
  243. if err := xml.Unmarshal(body, &storageErr); err != nil {
  244. return storageErr, err
  245. }
  246. storageErr.StatusCode = statusCode
  247. storageErr.RequestID = requestID
  248. storageErr.RawMessage = string(body)
  249. return storageErr, nil
  250. }
  251. func xmlUnmarshal(body io.Reader, v interface{}) error {
  252. data, err := ioutil.ReadAll(body)
  253. if err != nil {
  254. return err
  255. }
  256. return xml.Unmarshal(data, v)
  257. }
  258. // Handle http timeout
  259. type timeoutConn struct {
  260. conn net.Conn
  261. timeout time.Duration
  262. longTimeout time.Duration
  263. }
  264. func newTimeoutConn(conn net.Conn, timeout time.Duration, longTimeout time.Duration) *timeoutConn {
  265. conn.SetReadDeadline(time.Now().Add(longTimeout))
  266. return &timeoutConn{
  267. conn: conn,
  268. timeout: timeout,
  269. longTimeout: longTimeout,
  270. }
  271. }
  272. func (c *timeoutConn) Read(b []byte) (n int, err error) {
  273. c.SetReadDeadline(time.Now().Add(c.timeout))
  274. n, err = c.conn.Read(b)
  275. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  276. return n, err
  277. }
  278. func (c *timeoutConn) Write(b []byte) (n int, err error) {
  279. c.SetWriteDeadline(time.Now().Add(c.timeout))
  280. n, err = c.conn.Write(b)
  281. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  282. return n, err
  283. }
  284. func (c *timeoutConn) Close() error {
  285. return c.conn.Close()
  286. }
  287. func (c *timeoutConn) LocalAddr() net.Addr {
  288. return c.conn.LocalAddr()
  289. }
  290. func (c *timeoutConn) RemoteAddr() net.Addr {
  291. return c.conn.RemoteAddr()
  292. }
  293. func (c *timeoutConn) SetDeadline(t time.Time) error {
  294. return c.conn.SetDeadline(t)
  295. }
  296. func (c *timeoutConn) SetReadDeadline(t time.Time) error {
  297. return c.conn.SetReadDeadline(t)
  298. }
  299. func (c *timeoutConn) SetWriteDeadline(t time.Time) error {
  300. return c.conn.SetWriteDeadline(t)
  301. }
  302. // UrlMaker - build url and resource
  303. const (
  304. urlTypeCname = 1
  305. urlTypeIP = 2
  306. urlTypeAliyun = 3
  307. )
  308. type urlMaker struct {
  309. Scheme string // http or https
  310. NetLoc string // host or ip
  311. Type int // 1 CNAME 2 IP 3 ALIYUN
  312. IsProxy bool // proxy
  313. }
  314. // Parse endpoint
  315. func (um *urlMaker) Init(endpoint string, isCname bool, isProxy bool) {
  316. if strings.HasPrefix(endpoint, "http://") {
  317. um.Scheme = "http"
  318. um.NetLoc = endpoint[len("http://"):]
  319. } else if strings.HasPrefix(endpoint, "https://") {
  320. um.Scheme = "https"
  321. um.NetLoc = endpoint[len("https://"):]
  322. } else {
  323. um.Scheme = "http"
  324. um.NetLoc = endpoint
  325. }
  326. host, _, err := net.SplitHostPort(um.NetLoc)
  327. if err != nil {
  328. host = um.NetLoc
  329. }
  330. ip := net.ParseIP(host)
  331. if ip != nil {
  332. um.Type = urlTypeIP
  333. } else if isCname {
  334. um.Type = urlTypeCname
  335. } else {
  336. um.Type = urlTypeAliyun
  337. }
  338. um.IsProxy = isProxy
  339. }
  340. // Build URL
  341. func (um urlMaker) getURL(bucket, object, params string) *url.URL {
  342. var host = ""
  343. var path = ""
  344. if !um.IsProxy {
  345. object = url.QueryEscape(object)
  346. }
  347. if um.Type == urlTypeCname {
  348. host = um.NetLoc
  349. path = "/" + object
  350. } else if um.Type == urlTypeIP {
  351. if bucket == "" {
  352. host = um.NetLoc
  353. path = "/"
  354. } else {
  355. host = um.NetLoc
  356. path = fmt.Sprintf("/%s/%s", bucket, object)
  357. }
  358. } else {
  359. if bucket == "" {
  360. host = um.NetLoc
  361. path = "/"
  362. } else {
  363. host = bucket + "." + um.NetLoc
  364. path = "/" + object
  365. }
  366. }
  367. uri := &url.URL{
  368. Scheme: um.Scheme,
  369. Host: host,
  370. Path: path,
  371. RawQuery: params,
  372. }
  373. return uri
  374. }
  375. // Canonicalized Resource
  376. func (um urlMaker) getResource(bucketName, objectName, subResource string) string {
  377. if subResource != "" {
  378. subResource = "?" + subResource
  379. }
  380. if bucketName == "" {
  381. return fmt.Sprintf("/%s%s", bucketName, subResource)
  382. }
  383. return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource)
  384. }