conn.go 9.7 KB

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