conn.go 11 KB

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