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. 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. readerLen, err := GetReaderLen(reader)
  310. if err == nil {
  311. req.ContentLength = readerLen
  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. }