conn.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. resp, err := conn.client.Do(req)
  102. if err != nil {
  103. // fail transfer
  104. event := newProgressEvent(TransferFailedEvent, tracker.completedBytes, req.ContentLength)
  105. publishProgress(listener, event)
  106. return nil, err
  107. }
  108. return conn.handleResponse(resp, crc)
  109. }
  110. // handle request body
  111. func (conn Conn) handleBody(req *http.Request, body io.Reader, initCRC uint64,
  112. listener ProgressListener, tracker *readerTracker) (*os.File, hash.Hash64) {
  113. var file *os.File
  114. var crc hash.Hash64
  115. reader := body
  116. // length
  117. switch v := body.(type) {
  118. case *bytes.Buffer:
  119. req.ContentLength = int64(v.Len())
  120. case *bytes.Reader:
  121. req.ContentLength = int64(v.Len())
  122. case *strings.Reader:
  123. req.ContentLength = int64(v.Len())
  124. case *os.File:
  125. req.ContentLength = tryGetFileSize(v)
  126. case *io.LimitedReader:
  127. req.ContentLength = int64(v.N)
  128. }
  129. req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
  130. // md5
  131. if body != nil && conn.config.IsEnableMD5 && req.Header.Get(HTTPHeaderContentMD5) == "" {
  132. md5 := ""
  133. reader, md5, file, _ = calcMD5(body, req.ContentLength, conn.config.MD5Threshold)
  134. req.Header.Set(HTTPHeaderContentMD5, md5)
  135. }
  136. // crc
  137. if reader != nil && conn.config.IsEnableCRC {
  138. crc = NewCRC(crcTable(), initCRC)
  139. reader = TeeReader(reader, crc, req.ContentLength, listener, tracker)
  140. }
  141. // http body
  142. rc, ok := reader.(io.ReadCloser)
  143. if !ok && reader != nil {
  144. rc = ioutil.NopCloser(reader)
  145. }
  146. req.Body = rc
  147. return file, crc
  148. }
  149. func tryGetFileSize(f *os.File) int64 {
  150. fInfo, _ := f.Stat()
  151. return fInfo.Size()
  152. }
  153. // handle response
  154. func (conn Conn) handleResponse(resp *http.Response, crc hash.Hash64) (*Response, error) {
  155. var cliCRC uint64
  156. var srvCRC uint64
  157. statusCode := resp.StatusCode
  158. if statusCode >= 400 && statusCode <= 505 {
  159. // 4xx and 5xx indicate that the operation has error occurred
  160. var respBody []byte
  161. respBody, err := readResponseBody(resp)
  162. if err != nil {
  163. return nil, err
  164. }
  165. if len(respBody) == 0 {
  166. // no error in response body
  167. err = fmt.Errorf("oss: service returned without a response body (%s)", resp.Status)
  168. } else {
  169. // response contains storage service error object, unmarshal
  170. srvErr, errIn := serviceErrFromXML(respBody, resp.StatusCode,
  171. resp.Header.Get(HTTPHeaderOssRequestID))
  172. if err != nil { // error unmarshaling the error response
  173. err = errIn
  174. }
  175. err = srvErr
  176. }
  177. return &Response{
  178. StatusCode: resp.StatusCode,
  179. Headers: resp.Header,
  180. Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body
  181. }, err
  182. } else if statusCode >= 300 && statusCode <= 307 {
  183. // oss use 3xx, but response has no body
  184. err := fmt.Errorf("oss: service returned %d,%s", resp.StatusCode, resp.Status)
  185. return &Response{
  186. StatusCode: resp.StatusCode,
  187. Headers: resp.Header,
  188. Body: resp.Body,
  189. }, err
  190. }
  191. if conn.config.IsEnableCRC && crc != nil {
  192. cliCRC = crc.Sum64()
  193. }
  194. srvCRC, _ = strconv.ParseUint(resp.Header.Get(HTTPHeaderOssCRC64), 10, 64)
  195. // 2xx, successful
  196. return &Response{
  197. StatusCode: resp.StatusCode,
  198. Headers: resp.Header,
  199. Body: resp.Body,
  200. ClientCRC: cliCRC,
  201. ServerCRC: srvCRC,
  202. }, nil
  203. }
  204. func calcMD5(body io.Reader, contentLen, md5Threshold int64) (reader io.Reader, b64 string, tempFile *os.File, err error) {
  205. if contentLen == 0 || contentLen > md5Threshold {
  206. // huge body, use temporary file
  207. tempFile, err = ioutil.TempFile(os.TempDir(), TempFilePrefix)
  208. if tempFile != nil {
  209. io.Copy(tempFile, body)
  210. tempFile.Seek(0, os.SEEK_SET)
  211. md5 := md5.New()
  212. io.Copy(md5, tempFile)
  213. sum := md5.Sum(nil)
  214. b64 = base64.StdEncoding.EncodeToString(sum[:])
  215. tempFile.Seek(0, os.SEEK_SET)
  216. reader = tempFile
  217. }
  218. } else {
  219. // small body, use memory
  220. buf, _ := ioutil.ReadAll(body)
  221. sum := md5.Sum(buf)
  222. b64 = base64.StdEncoding.EncodeToString(sum[:])
  223. reader = bytes.NewReader(buf)
  224. }
  225. return
  226. }
  227. func readResponseBody(resp *http.Response) ([]byte, error) {
  228. defer resp.Body.Close()
  229. out, err := ioutil.ReadAll(resp.Body)
  230. if err == io.EOF {
  231. err = nil
  232. }
  233. return out, err
  234. }
  235. func serviceErrFromXML(body []byte, statusCode int, requestID string) (ServiceError, error) {
  236. var storageErr ServiceError
  237. if err := xml.Unmarshal(body, &storageErr); err != nil {
  238. return storageErr, err
  239. }
  240. storageErr.StatusCode = statusCode
  241. storageErr.RequestID = requestID
  242. storageErr.RawMessage = string(body)
  243. return storageErr, nil
  244. }
  245. func xmlUnmarshal(body io.Reader, v interface{}) error {
  246. data, err := ioutil.ReadAll(body)
  247. if err != nil {
  248. return err
  249. }
  250. return xml.Unmarshal(data, v)
  251. }
  252. // Handle http timeout
  253. type timeoutConn struct {
  254. conn net.Conn
  255. timeout time.Duration
  256. longTimeout time.Duration
  257. }
  258. func newTimeoutConn(conn net.Conn, timeout time.Duration, longTimeout time.Duration) *timeoutConn {
  259. conn.SetReadDeadline(time.Now().Add(longTimeout))
  260. return &timeoutConn{
  261. conn: conn,
  262. timeout: timeout,
  263. longTimeout: longTimeout,
  264. }
  265. }
  266. func (c *timeoutConn) Read(b []byte) (n int, err error) {
  267. c.SetReadDeadline(time.Now().Add(c.timeout))
  268. n, err = c.conn.Read(b)
  269. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  270. return n, err
  271. }
  272. func (c *timeoutConn) Write(b []byte) (n int, err error) {
  273. c.SetWriteDeadline(time.Now().Add(c.timeout))
  274. n, err = c.conn.Write(b)
  275. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  276. return n, err
  277. }
  278. func (c *timeoutConn) Close() error {
  279. return c.conn.Close()
  280. }
  281. func (c *timeoutConn) LocalAddr() net.Addr {
  282. return c.conn.LocalAddr()
  283. }
  284. func (c *timeoutConn) RemoteAddr() net.Addr {
  285. return c.conn.RemoteAddr()
  286. }
  287. func (c *timeoutConn) SetDeadline(t time.Time) error {
  288. return c.conn.SetDeadline(t)
  289. }
  290. func (c *timeoutConn) SetReadDeadline(t time.Time) error {
  291. return c.conn.SetReadDeadline(t)
  292. }
  293. func (c *timeoutConn) SetWriteDeadline(t time.Time) error {
  294. return c.conn.SetWriteDeadline(t)
  295. }
  296. // UrlMaker - build url and resource
  297. const (
  298. urlTypeCname = 1
  299. urlTypeIP = 2
  300. urlTypeAliyun = 3
  301. )
  302. type urlMaker struct {
  303. Scheme string // http or https
  304. NetLoc string // host or ip
  305. Type int // 1 CNAME 2 IP 3 ALIYUN
  306. IsProxy bool // proxy
  307. }
  308. // Parse endpoint
  309. func (um *urlMaker) Init(endpoint string, isCname bool, isProxy bool) {
  310. if strings.HasPrefix(endpoint, "http://") {
  311. um.Scheme = "http"
  312. um.NetLoc = endpoint[len("http://"):]
  313. } else if strings.HasPrefix(endpoint, "https://") {
  314. um.Scheme = "https"
  315. um.NetLoc = endpoint[len("https://"):]
  316. } else {
  317. um.Scheme = "http"
  318. um.NetLoc = endpoint
  319. }
  320. host, _, err := net.SplitHostPort(um.NetLoc)
  321. if err != nil {
  322. host = um.NetLoc
  323. }
  324. ip := net.ParseIP(host)
  325. if ip != nil {
  326. um.Type = urlTypeIP
  327. } else if isCname {
  328. um.Type = urlTypeCname
  329. } else {
  330. um.Type = urlTypeAliyun
  331. }
  332. um.IsProxy = isProxy
  333. }
  334. // Build URL
  335. func (um urlMaker) getURL(bucket, object, params string) *url.URL {
  336. var host = ""
  337. var path = ""
  338. if !um.IsProxy {
  339. object = url.QueryEscape(object)
  340. }
  341. if um.Type == urlTypeCname {
  342. host = um.NetLoc
  343. path = "/" + object
  344. } else if um.Type == urlTypeIP {
  345. if bucket == "" {
  346. host = um.NetLoc
  347. path = "/"
  348. } else {
  349. host = um.NetLoc
  350. path = fmt.Sprintf("/%s/%s", bucket, object)
  351. }
  352. } else {
  353. if bucket == "" {
  354. host = um.NetLoc
  355. path = "/"
  356. } else {
  357. host = bucket + "." + um.NetLoc
  358. path = "/" + object
  359. }
  360. }
  361. uri := &url.URL{
  362. Scheme: um.Scheme,
  363. Host: host,
  364. Path: path,
  365. RawQuery: params,
  366. }
  367. return uri
  368. }
  369. // Canonicalized Resource
  370. func (um urlMaker) getResource(bucketName, objectName, subResource string) string {
  371. if subResource != "" {
  372. subResource = "?" + subResource
  373. }
  374. if bucketName == "" {
  375. return fmt.Sprintf("/%s%s", bucketName, subResource)
  376. }
  377. return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource)
  378. }