conn.go 20 KB

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