conn.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. package oss
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/base64"
  6. "encoding/json"
  7. "encoding/xml"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "net/http"
  14. "net/url"
  15. "os"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. // Conn defines OSS Conn
  22. type Conn struct {
  23. config *Config
  24. url *urlMaker
  25. client *http.Client
  26. }
  27. var signKeyList = []string{"acl", "uploads", "location", "cors",
  28. "logging", "website", "referer", "lifecycle",
  29. "delete", "append", "tagging", "objectMeta",
  30. "uploadId", "partNumber", "security-token",
  31. "position", "img", "style", "styleName",
  32. "replication", "replicationProgress",
  33. "replicationLocation", "cname", "bucketInfo",
  34. "comp", "qos", "live", "status", "vod",
  35. "startTime", "endTime", "symlink",
  36. "x-oss-process", "response-content-type", "x-oss-traffic-limit",
  37. "response-content-language", "response-expires",
  38. "response-cache-control", "response-content-disposition",
  39. "response-content-encoding", "udf", "udfName", "udfImage",
  40. "udfId", "udfImageDesc", "udfApplication", "comp",
  41. "udfApplicationLog", "restore", "callback", "callback-var", "qosInfo",
  42. "policy", "stat", "encryption", "versions", "versioning", "versionId", "requestPayment"}
  43. // init initializes Conn
  44. func (conn *Conn) init(config *Config, urlMaker *urlMaker, client *http.Client) error {
  45. if client == nil {
  46. // New transport
  47. transport := newTransport(conn, config)
  48. // Proxy
  49. if conn.config.IsUseProxy {
  50. proxyURL, err := url.Parse(config.ProxyHost)
  51. if err != nil {
  52. return err
  53. }
  54. if config.IsAuthProxy {
  55. if config.ProxyPassword != "" {
  56. proxyURL.User = url.UserPassword(config.ProxyUser, config.ProxyPassword)
  57. } else {
  58. proxyURL.User = url.User(config.ProxyUser)
  59. }
  60. }
  61. transport.Proxy = http.ProxyURL(proxyURL)
  62. }
  63. client = &http.Client{Transport: transport}
  64. }
  65. conn.config = config
  66. conn.url = urlMaker
  67. conn.client = client
  68. return nil
  69. }
  70. // Do sends request and returns the response
  71. func (conn Conn) Do(method, bucketName, objectName string, params map[string]interface{}, headers map[string]string,
  72. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  73. err := CheckBucketName(bucketName)
  74. if len(bucketName) > 0 && err != nil {
  75. return nil, err
  76. }
  77. urlParams := conn.getURLParams(params)
  78. subResource := conn.getSubResource(params)
  79. uri := conn.url.getURL(bucketName, objectName, urlParams)
  80. resource := conn.url.getResource(bucketName, objectName, subResource)
  81. return conn.doRequest(method, uri, resource, headers, data, initCRC, listener)
  82. }
  83. // DoURL sends the request with signed URL and returns the response result.
  84. func (conn Conn) DoURL(method HTTPMethod, signedURL string, headers map[string]string,
  85. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  86. // Get URI from signedURL
  87. uri, err := url.ParseRequestURI(signedURL)
  88. if err != nil {
  89. return nil, err
  90. }
  91. m := strings.ToUpper(string(method))
  92. req := &http.Request{
  93. Method: m,
  94. URL: uri,
  95. Proto: "HTTP/1.1",
  96. ProtoMajor: 1,
  97. ProtoMinor: 1,
  98. Header: make(http.Header),
  99. Host: uri.Host,
  100. }
  101. tracker := &readerTracker{completedBytes: 0}
  102. fd, crc := conn.handleBody(req, data, initCRC, listener, tracker)
  103. if fd != nil {
  104. defer func() {
  105. fd.Close()
  106. os.Remove(fd.Name())
  107. }()
  108. }
  109. if conn.config.IsAuthProxy {
  110. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  111. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  112. req.Header.Set("Proxy-Authorization", basic)
  113. }
  114. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  115. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  116. if headers != nil {
  117. for k, v := range headers {
  118. req.Header.Set(k, v)
  119. }
  120. }
  121. // Transfer started
  122. event := newProgressEvent(TransferStartedEvent, 0, req.ContentLength, 0)
  123. publishProgress(listener, event)
  124. if conn.config.LogLevel >= Debug {
  125. conn.LoggerHTTPReq(req)
  126. }
  127. resp, err := conn.client.Do(req)
  128. if err != nil {
  129. // Transfer failed
  130. event = newProgressEvent(TransferFailedEvent, tracker.completedBytes, req.ContentLength, 0)
  131. publishProgress(listener, event)
  132. conn.config.WriteLog(Debug, "[Resp:%p]http error:%s\n", req, err.Error())
  133. return nil, err
  134. }
  135. if conn.config.LogLevel >= Debug {
  136. //print out http resp
  137. conn.LoggerHTTPResp(req, resp)
  138. }
  139. // Transfer completed
  140. event = newProgressEvent(TransferCompletedEvent, tracker.completedBytes, req.ContentLength, 0)
  141. publishProgress(listener, event)
  142. return conn.handleResponse(resp, crc)
  143. }
  144. func (conn Conn) getURLParams(params map[string]interface{}) string {
  145. // Sort
  146. keys := make([]string, 0, len(params))
  147. for k := range params {
  148. keys = append(keys, k)
  149. }
  150. sort.Strings(keys)
  151. // Serialize
  152. var buf bytes.Buffer
  153. for _, k := range keys {
  154. if buf.Len() > 0 {
  155. buf.WriteByte('&')
  156. }
  157. buf.WriteString(url.QueryEscape(k))
  158. if params[k] != nil {
  159. buf.WriteString("=" + url.QueryEscape(params[k].(string)))
  160. }
  161. }
  162. return buf.String()
  163. }
  164. func (conn Conn) getSubResource(params map[string]interface{}) string {
  165. // Sort
  166. keys := make([]string, 0, len(params))
  167. for k := range params {
  168. if conn.isParamSign(k) {
  169. keys = append(keys, k)
  170. }
  171. }
  172. sort.Strings(keys)
  173. // Serialize
  174. var buf bytes.Buffer
  175. for _, k := range keys {
  176. if buf.Len() > 0 {
  177. buf.WriteByte('&')
  178. }
  179. buf.WriteString(k)
  180. if params[k] != nil {
  181. buf.WriteString("=" + params[k].(string))
  182. }
  183. }
  184. return buf.String()
  185. }
  186. func (conn Conn) isParamSign(paramKey string) bool {
  187. for _, k := range signKeyList {
  188. if paramKey == k {
  189. return true
  190. }
  191. }
  192. return false
  193. }
  194. func (conn Conn) doRequest(method string, uri *url.URL, canonicalizedResource string, headers map[string]string,
  195. data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) {
  196. method = strings.ToUpper(method)
  197. req := &http.Request{
  198. Method: method,
  199. URL: uri,
  200. Proto: "HTTP/1.1",
  201. ProtoMajor: 1,
  202. ProtoMinor: 1,
  203. Header: make(http.Header),
  204. Host: uri.Host,
  205. }
  206. tracker := &readerTracker{completedBytes: 0}
  207. fd, crc := conn.handleBody(req, data, initCRC, listener, tracker)
  208. if fd != nil {
  209. defer func() {
  210. fd.Close()
  211. os.Remove(fd.Name())
  212. }()
  213. }
  214. if conn.config.IsAuthProxy {
  215. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  216. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  217. req.Header.Set("Proxy-Authorization", basic)
  218. }
  219. date := time.Now().UTC().Format(http.TimeFormat)
  220. req.Header.Set(HTTPHeaderDate, date)
  221. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  222. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  223. akIf := conn.config.GetCredentials()
  224. if akIf.GetSecurityToken() != "" {
  225. req.Header.Set(HTTPHeaderOssSecurityToken, akIf.GetSecurityToken())
  226. }
  227. if headers != nil {
  228. for k, v := range headers {
  229. req.Header.Set(k, v)
  230. }
  231. }
  232. conn.signHeader(req, canonicalizedResource)
  233. // Transfer started
  234. event := newProgressEvent(TransferStartedEvent, 0, req.ContentLength, 0)
  235. publishProgress(listener, event)
  236. if conn.config.LogLevel >= Debug {
  237. conn.LoggerHTTPReq(req)
  238. }
  239. resp, err := conn.client.Do(req)
  240. if err != nil {
  241. // Transfer failed
  242. event = newProgressEvent(TransferFailedEvent, tracker.completedBytes, req.ContentLength, 0)
  243. publishProgress(listener, event)
  244. conn.config.WriteLog(Debug, "[Resp:%p]http error:%s\n", req, err.Error())
  245. return nil, err
  246. }
  247. if conn.config.LogLevel >= Debug {
  248. //print out http resp
  249. conn.LoggerHTTPResp(req, resp)
  250. }
  251. // Transfer completed
  252. event = newProgressEvent(TransferCompletedEvent, tracker.completedBytes, req.ContentLength, 0)
  253. publishProgress(listener, event)
  254. return conn.handleResponse(resp, crc)
  255. }
  256. func (conn Conn) signURL(method HTTPMethod, bucketName, objectName string, expiration int64, params map[string]interface{}, headers map[string]string) string {
  257. akIf := conn.config.GetCredentials()
  258. if akIf.GetSecurityToken() != "" {
  259. params[HTTPParamSecurityToken] = akIf.GetSecurityToken()
  260. }
  261. subResource := conn.getSubResource(params)
  262. canonicalizedResource := conn.url.getResource(bucketName, objectName, subResource)
  263. m := strings.ToUpper(string(method))
  264. req := &http.Request{
  265. Method: m,
  266. Header: make(http.Header),
  267. }
  268. if conn.config.IsAuthProxy {
  269. auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword
  270. basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  271. req.Header.Set("Proxy-Authorization", basic)
  272. }
  273. req.Header.Set(HTTPHeaderDate, strconv.FormatInt(expiration, 10))
  274. req.Header.Set(HTTPHeaderHost, conn.config.Endpoint)
  275. req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent)
  276. if headers != nil {
  277. for k, v := range headers {
  278. req.Header.Set(k, v)
  279. }
  280. }
  281. signedStr := conn.getSignedStr(req, canonicalizedResource, akIf.GetAccessKeySecret())
  282. params[HTTPParamExpires] = strconv.FormatInt(expiration, 10)
  283. params[HTTPParamAccessKeyID] = akIf.GetAccessKeyID()
  284. params[HTTPParamSignature] = signedStr
  285. urlParams := conn.getURLParams(params)
  286. return conn.url.getSignURL(bucketName, objectName, urlParams)
  287. }
  288. func (conn Conn) signRtmpURL(bucketName, channelName, playlistName string, expiration int64) string {
  289. params := map[string]interface{}{}
  290. if playlistName != "" {
  291. params[HTTPParamPlaylistName] = playlistName
  292. }
  293. expireStr := strconv.FormatInt(expiration, 10)
  294. params[HTTPParamExpires] = expireStr
  295. akIf := conn.config.GetCredentials()
  296. if akIf.GetAccessKeyID() != "" {
  297. params[HTTPParamAccessKeyID] = akIf.GetAccessKeyID()
  298. if akIf.GetSecurityToken() != "" {
  299. params[HTTPParamSecurityToken] = akIf.GetSecurityToken()
  300. }
  301. signedStr := conn.getRtmpSignedStr(bucketName, channelName, playlistName, expiration, akIf.GetAccessKeySecret(), params)
  302. params[HTTPParamSignature] = signedStr
  303. }
  304. urlParams := conn.getURLParams(params)
  305. return conn.url.getSignRtmpURL(bucketName, channelName, urlParams)
  306. }
  307. // handleBody handles request body
  308. func (conn Conn) handleBody(req *http.Request, body io.Reader, initCRC uint64,
  309. listener ProgressListener, tracker *readerTracker) (*os.File, hash.Hash64) {
  310. var file *os.File
  311. var crc hash.Hash64
  312. reader := body
  313. // Length
  314. switch v := body.(type) {
  315. case *bytes.Buffer:
  316. req.ContentLength = int64(v.Len())
  317. case *bytes.Reader:
  318. req.ContentLength = int64(v.Len())
  319. case *strings.Reader:
  320. req.ContentLength = int64(v.Len())
  321. case *os.File:
  322. req.ContentLength = tryGetFileSize(v)
  323. case *io.LimitedReader:
  324. req.ContentLength = int64(v.N)
  325. }
  326. req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
  327. // MD5
  328. if body != nil && conn.config.IsEnableMD5 && req.Header.Get(HTTPHeaderContentMD5) == "" {
  329. md5 := ""
  330. reader, md5, file, _ = calcMD5(body, req.ContentLength, conn.config.MD5Threshold)
  331. req.Header.Set(HTTPHeaderContentMD5, md5)
  332. }
  333. // CRC
  334. if reader != nil && conn.config.IsEnableCRC {
  335. crc = NewCRC(crcTable(), initCRC)
  336. reader = TeeReader(reader, crc, req.ContentLength, listener, tracker)
  337. }
  338. // HTTP body
  339. rc, ok := reader.(io.ReadCloser)
  340. if !ok && reader != nil {
  341. rc = ioutil.NopCloser(reader)
  342. }
  343. if conn.isUploadLimitReq(req) {
  344. limitReader := &LimitSpeedReader{
  345. reader: rc,
  346. ossLimiter: conn.config.UploadLimiter,
  347. }
  348. req.Body = limitReader
  349. } else {
  350. req.Body = rc
  351. }
  352. return file, crc
  353. }
  354. // isUploadLimitReq: judge limit upload speed or not
  355. func (conn Conn) isUploadLimitReq(req *http.Request) bool {
  356. if conn.config.UploadLimitSpeed == 0 || conn.config.UploadLimiter == nil {
  357. return false
  358. }
  359. if req.Method != "GET" && req.Method != "DELETE" && req.Method != "HEAD" {
  360. if req.ContentLength > 0 {
  361. return true
  362. }
  363. }
  364. return false
  365. }
  366. func tryGetFileSize(f *os.File) int64 {
  367. fInfo, _ := f.Stat()
  368. return fInfo.Size()
  369. }
  370. // handleResponse handles response
  371. func (conn Conn) handleResponse(resp *http.Response, crc hash.Hash64) (*Response, error) {
  372. var cliCRC uint64
  373. var srvCRC uint64
  374. statusCode := resp.StatusCode
  375. if statusCode >= 400 && statusCode <= 505 {
  376. // 4xx and 5xx indicate that the operation has error occurred
  377. var respBody []byte
  378. respBody, err := readResponseBody(resp)
  379. if err != nil {
  380. return nil, err
  381. }
  382. if len(respBody) == 0 {
  383. err = ServiceError{
  384. StatusCode: statusCode,
  385. RequestID: resp.Header.Get(HTTPHeaderOssRequestID),
  386. }
  387. } else {
  388. // Response contains storage service error object, unmarshal
  389. srvErr, errIn := serviceErrFromXML(respBody, resp.StatusCode,
  390. resp.Header.Get(HTTPHeaderOssRequestID))
  391. if errIn != nil { // error unmarshaling the error response
  392. err = fmt.Errorf("oss: service returned invalid response body, status = %s, RequestId = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID))
  393. } else {
  394. err = srvErr
  395. }
  396. }
  397. return &Response{
  398. StatusCode: resp.StatusCode,
  399. Headers: resp.Header,
  400. Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body
  401. }, err
  402. } else if statusCode >= 300 && statusCode <= 307 {
  403. // OSS use 3xx, but response has no body
  404. err := fmt.Errorf("oss: service returned %d,%s", resp.StatusCode, resp.Status)
  405. return &Response{
  406. StatusCode: resp.StatusCode,
  407. Headers: resp.Header,
  408. Body: resp.Body,
  409. }, err
  410. }
  411. if conn.config.IsEnableCRC && crc != nil {
  412. cliCRC = crc.Sum64()
  413. }
  414. srvCRC, _ = strconv.ParseUint(resp.Header.Get(HTTPHeaderOssCRC64), 10, 64)
  415. // 2xx, successful
  416. return &Response{
  417. StatusCode: resp.StatusCode,
  418. Headers: resp.Header,
  419. Body: resp.Body,
  420. ClientCRC: cliCRC,
  421. ServerCRC: srvCRC,
  422. }, nil
  423. }
  424. // LoggerHTTPReq Print the header information of the http request
  425. func (conn Conn) LoggerHTTPReq(req *http.Request) {
  426. var logBuffer bytes.Buffer
  427. logBuffer.WriteString(fmt.Sprintf("[Req:%p]Method:%s\t", req, req.Method))
  428. logBuffer.WriteString(fmt.Sprintf("Host:%s\t", req.URL.Host))
  429. logBuffer.WriteString(fmt.Sprintf("Path:%s\t", req.URL.Path))
  430. logBuffer.WriteString(fmt.Sprintf("Query:%s\t", req.URL.RawQuery))
  431. logBuffer.WriteString(fmt.Sprintf("Header info:"))
  432. for k, v := range req.Header {
  433. var valueBuffer bytes.Buffer
  434. for j := 0; j < len(v); j++ {
  435. if j > 0 {
  436. valueBuffer.WriteString(" ")
  437. }
  438. valueBuffer.WriteString(v[j])
  439. }
  440. logBuffer.WriteString(fmt.Sprintf("\t%s:%s", k, valueBuffer.String()))
  441. }
  442. conn.config.WriteLog(Debug, "%s\n", logBuffer.String())
  443. }
  444. // LoggerHTTPResp Print Response to http request
  445. func (conn Conn) LoggerHTTPResp(req *http.Request, resp *http.Response) {
  446. var logBuffer bytes.Buffer
  447. logBuffer.WriteString(fmt.Sprintf("[Resp:%p]StatusCode:%d\t", req, resp.StatusCode))
  448. logBuffer.WriteString(fmt.Sprintf("Header info:"))
  449. for k, v := range resp.Header {
  450. var valueBuffer bytes.Buffer
  451. for j := 0; j < len(v); j++ {
  452. if j > 0 {
  453. valueBuffer.WriteString(" ")
  454. }
  455. valueBuffer.WriteString(v[j])
  456. }
  457. logBuffer.WriteString(fmt.Sprintf("\t%s:%s", k, valueBuffer.String()))
  458. }
  459. conn.config.WriteLog(Debug, "%s\n", logBuffer.String())
  460. }
  461. func calcMD5(body io.Reader, contentLen, md5Threshold int64) (reader io.Reader, b64 string, tempFile *os.File, err error) {
  462. if contentLen == 0 || contentLen > md5Threshold {
  463. // Huge body, use temporary file
  464. tempFile, err = ioutil.TempFile(os.TempDir(), TempFilePrefix)
  465. if tempFile != nil {
  466. io.Copy(tempFile, body)
  467. tempFile.Seek(0, os.SEEK_SET)
  468. md5 := md5.New()
  469. io.Copy(md5, tempFile)
  470. sum := md5.Sum(nil)
  471. b64 = base64.StdEncoding.EncodeToString(sum[:])
  472. tempFile.Seek(0, os.SEEK_SET)
  473. reader = tempFile
  474. }
  475. } else {
  476. // Small body, use memory
  477. buf, _ := ioutil.ReadAll(body)
  478. sum := md5.Sum(buf)
  479. b64 = base64.StdEncoding.EncodeToString(sum[:])
  480. reader = bytes.NewReader(buf)
  481. }
  482. return
  483. }
  484. func readResponseBody(resp *http.Response) ([]byte, error) {
  485. defer resp.Body.Close()
  486. out, err := ioutil.ReadAll(resp.Body)
  487. if err == io.EOF {
  488. err = nil
  489. }
  490. return out, err
  491. }
  492. func serviceErrFromXML(body []byte, statusCode int, requestID string) (ServiceError, error) {
  493. var storageErr ServiceError
  494. if err := xml.Unmarshal(body, &storageErr); err != nil {
  495. return storageErr, err
  496. }
  497. storageErr.StatusCode = statusCode
  498. storageErr.RequestID = requestID
  499. storageErr.RawMessage = string(body)
  500. return storageErr, nil
  501. }
  502. func xmlUnmarshal(body io.Reader, v interface{}) error {
  503. data, err := ioutil.ReadAll(body)
  504. if err != nil {
  505. return err
  506. }
  507. return xml.Unmarshal(data, v)
  508. }
  509. func jsonUnmarshal(body io.Reader, v interface{}) error {
  510. data, err := ioutil.ReadAll(body)
  511. if err != nil {
  512. return err
  513. }
  514. return json.Unmarshal(data, v)
  515. }
  516. // timeoutConn handles HTTP timeout
  517. type timeoutConn struct {
  518. conn net.Conn
  519. timeout time.Duration
  520. longTimeout time.Duration
  521. }
  522. func newTimeoutConn(conn net.Conn, timeout time.Duration, longTimeout time.Duration) *timeoutConn {
  523. conn.SetReadDeadline(time.Now().Add(longTimeout))
  524. return &timeoutConn{
  525. conn: conn,
  526. timeout: timeout,
  527. longTimeout: longTimeout,
  528. }
  529. }
  530. func (c *timeoutConn) Read(b []byte) (n int, err error) {
  531. c.SetReadDeadline(time.Now().Add(c.timeout))
  532. n, err = c.conn.Read(b)
  533. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  534. return n, err
  535. }
  536. func (c *timeoutConn) Write(b []byte) (n int, err error) {
  537. c.SetWriteDeadline(time.Now().Add(c.timeout))
  538. n, err = c.conn.Write(b)
  539. c.SetReadDeadline(time.Now().Add(c.longTimeout))
  540. return n, err
  541. }
  542. func (c *timeoutConn) Close() error {
  543. return c.conn.Close()
  544. }
  545. func (c *timeoutConn) LocalAddr() net.Addr {
  546. return c.conn.LocalAddr()
  547. }
  548. func (c *timeoutConn) RemoteAddr() net.Addr {
  549. return c.conn.RemoteAddr()
  550. }
  551. func (c *timeoutConn) SetDeadline(t time.Time) error {
  552. return c.conn.SetDeadline(t)
  553. }
  554. func (c *timeoutConn) SetReadDeadline(t time.Time) error {
  555. return c.conn.SetReadDeadline(t)
  556. }
  557. func (c *timeoutConn) SetWriteDeadline(t time.Time) error {
  558. return c.conn.SetWriteDeadline(t)
  559. }
  560. // UrlMaker builds URL and resource
  561. const (
  562. urlTypeCname = 1
  563. urlTypeIP = 2
  564. urlTypeAliyun = 3
  565. )
  566. type urlMaker struct {
  567. Scheme string // HTTP or HTTPS
  568. NetLoc string // Host or IP
  569. Type int // 1 CNAME, 2 IP, 3 ALIYUN
  570. IsProxy bool // Proxy
  571. }
  572. // Init parses endpoint
  573. func (um *urlMaker) Init(endpoint string, isCname bool, isProxy bool) error {
  574. if strings.HasPrefix(endpoint, "http://") {
  575. um.Scheme = "http"
  576. um.NetLoc = endpoint[len("http://"):]
  577. } else if strings.HasPrefix(endpoint, "https://") {
  578. um.Scheme = "https"
  579. um.NetLoc = endpoint[len("https://"):]
  580. } else {
  581. um.Scheme = "http"
  582. um.NetLoc = endpoint
  583. }
  584. //use url.Parse() to get real host
  585. strUrl := um.Scheme + "://" + um.NetLoc
  586. url, err := url.Parse(strUrl)
  587. if err != nil {
  588. return err
  589. }
  590. um.NetLoc = url.Host
  591. host, _, err := net.SplitHostPort(um.NetLoc)
  592. if err != nil {
  593. host = um.NetLoc
  594. if host[0] == '[' && host[len(host)-1] == ']' {
  595. host = host[1 : len(host)-1]
  596. }
  597. }
  598. ip := net.ParseIP(host)
  599. if ip != nil {
  600. um.Type = urlTypeIP
  601. } else if isCname {
  602. um.Type = urlTypeCname
  603. } else {
  604. um.Type = urlTypeAliyun
  605. }
  606. um.IsProxy = isProxy
  607. return nil
  608. }
  609. // getURL gets URL
  610. func (um urlMaker) getURL(bucket, object, params string) *url.URL {
  611. host, path := um.buildURL(bucket, object)
  612. addr := ""
  613. if params == "" {
  614. addr = fmt.Sprintf("%s://%s%s", um.Scheme, host, path)
  615. } else {
  616. addr = fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  617. }
  618. uri, _ := url.ParseRequestURI(addr)
  619. return uri
  620. }
  621. // getSignURL gets sign URL
  622. func (um urlMaker) getSignURL(bucket, object, params string) string {
  623. host, path := um.buildURL(bucket, object)
  624. return fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params)
  625. }
  626. // getSignRtmpURL Build Sign Rtmp URL
  627. func (um urlMaker) getSignRtmpURL(bucket, channelName, params string) string {
  628. host, path := um.buildURL(bucket, "live")
  629. channelName = url.QueryEscape(channelName)
  630. channelName = strings.Replace(channelName, "+", "%20", -1)
  631. return fmt.Sprintf("rtmp://%s%s/%s?%s", host, path, channelName, params)
  632. }
  633. // buildURL builds URL
  634. func (um urlMaker) buildURL(bucket, object string) (string, string) {
  635. var host = ""
  636. var path = ""
  637. object = url.QueryEscape(object)
  638. object = strings.Replace(object, "+", "%20", -1)
  639. if um.Type == urlTypeCname {
  640. host = um.NetLoc
  641. path = "/" + object
  642. } else if um.Type == urlTypeIP {
  643. if bucket == "" {
  644. host = um.NetLoc
  645. path = "/"
  646. } else {
  647. host = um.NetLoc
  648. path = fmt.Sprintf("/%s/%s", bucket, object)
  649. }
  650. } else {
  651. if bucket == "" {
  652. host = um.NetLoc
  653. path = "/"
  654. } else {
  655. host = bucket + "." + um.NetLoc
  656. path = "/" + object
  657. }
  658. }
  659. return host, path
  660. }
  661. // getResource gets canonicalized resource
  662. func (um urlMaker) getResource(bucketName, objectName, subResource string) string {
  663. if subResource != "" {
  664. subResource = "?" + subResource
  665. }
  666. if bucketName == "" {
  667. return fmt.Sprintf("/%s%s", bucketName, subResource)
  668. }
  669. return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource)
  670. }