conn.go 10 KB

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