conn.go 20 KB

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