conn.go 20 KB

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