conn.go 19 KB

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