conn.go 10 KB

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