You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.go 33 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. package minio_ext
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "math/rand"
  9. "net"
  10. "net/http"
  11. "net/http/cookiejar"
  12. "net/http/httputil"
  13. "net/url"
  14. "path"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/minio/minio-go/pkg/s3signer"
  21. "github.com/minio/minio-go/pkg/s3utils"
  22. "github.com/minio/minio-go/v6/pkg/credentials"
  23. "golang.org/x/net/publicsuffix"
  24. )
  25. // MaxRetry is the maximum number of retries before stopping.
  26. var MaxRetry = 10
  27. // MaxJitter will randomize over the full exponential backoff time
  28. const MaxJitter = 1.0
  29. // NoJitter disables the use of jitter for randomizing the exponential backoff time
  30. const NoJitter = 0.0
  31. // DefaultRetryUnit - default unit multiplicative per retry.
  32. // defaults to 1 second.
  33. const DefaultRetryUnit = time.Second
  34. // DefaultRetryCap - Each retry attempt never waits no longer than
  35. // this maximum time duration.
  36. const DefaultRetryCap = time.Second * 30
  37. // Global constants.
  38. const (
  39. libraryName = "minio-go"
  40. libraryVersion = "v6.0.44"
  41. )
  42. // User Agent should always following the below style.
  43. // Please open an issue to discuss any new changes here.
  44. //
  45. // MinIO (OS; ARCH) LIB/VER APP/VER
  46. const (
  47. libraryUserAgentPrefix = "MinIO (" + runtime.GOOS + "; " + runtime.GOARCH + ") "
  48. libraryUserAgent = libraryUserAgentPrefix + libraryName + "/" + libraryVersion
  49. )
  50. // requestMetadata - is container for all the values to make a request.
  51. type requestMetadata struct {
  52. // If set newRequest presigns the URL.
  53. presignURL bool
  54. // User supplied.
  55. bucketName string
  56. objectName string
  57. queryValues url.Values
  58. customHeader http.Header
  59. expires int64
  60. // Generated by our internal code.
  61. bucketLocation string
  62. contentBody io.Reader
  63. contentLength int64
  64. contentMD5Base64 string // carries base64 encoded md5sum
  65. contentSHA256Hex string // carries hex encoded sha256sum
  66. }
  67. type BucketLookupType int
  68. // bucketLocationCache - Provides simple mechanism to hold bucket
  69. // locations in memory.
  70. type bucketLocationCache struct {
  71. // mutex is used for handling the concurrent
  72. // read/write requests for cache.
  73. sync.RWMutex
  74. // items holds the cached bucket locations.
  75. items map[string]string
  76. }
  77. // Client implements Amazon S3 compatible methods.
  78. type Client struct {
  79. /// Standard options.
  80. // Parsed endpoint url provided by the user.
  81. endpointURL *url.URL
  82. // Holds various credential providers.
  83. credsProvider *credentials.Credentials
  84. // Custom signerType value overrides all credentials.
  85. overrideSignerType credentials.SignatureType
  86. // User supplied.
  87. appInfo struct {
  88. appName string
  89. appVersion string
  90. }
  91. // Indicate whether we are using https or not
  92. secure bool
  93. // Needs allocation.
  94. httpClient *http.Client
  95. bucketLocCache *bucketLocationCache
  96. // Advanced functionality.
  97. isTraceEnabled bool
  98. traceErrorsOnly bool
  99. traceOutput io.Writer
  100. // S3 specific accelerated endpoint.
  101. s3AccelerateEndpoint string
  102. // Region endpoint
  103. region string
  104. // Random seed.
  105. random *rand.Rand
  106. // lookup indicates type of url lookup supported by server. If not specified,
  107. // default to Auto.
  108. lookup BucketLookupType
  109. }
  110. // lockedRandSource provides protected rand source, implements rand.Source interface.
  111. type lockedRandSource struct {
  112. lk sync.Mutex
  113. src rand.Source
  114. }
  115. // Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
  116. func (r *lockedRandSource) Int63() (n int64) {
  117. r.lk.Lock()
  118. n = r.src.Int63()
  119. r.lk.Unlock()
  120. return
  121. }
  122. // Seed uses the provided seed value to initialize the generator to a
  123. // deterministic state.
  124. func (r *lockedRandSource) Seed(seed int64) {
  125. r.lk.Lock()
  126. r.src.Seed(seed)
  127. r.lk.Unlock()
  128. }
  129. // Different types of url lookup supported by the server.Initialized to BucketLookupAuto
  130. const (
  131. BucketLookupAuto BucketLookupType = iota
  132. BucketLookupDNS
  133. BucketLookupPath
  134. )
  135. // List of AWS S3 error codes which are retryable.
  136. var retryableS3Codes = map[string]struct{}{
  137. "RequestError": {},
  138. "RequestTimeout": {},
  139. "Throttling": {},
  140. "ThrottlingException": {},
  141. "RequestLimitExceeded": {},
  142. "RequestThrottled": {},
  143. "InternalError": {},
  144. "ExpiredToken": {},
  145. "ExpiredTokenException": {},
  146. "SlowDown": {},
  147. // Add more AWS S3 codes here.
  148. }
  149. // awsS3EndpointMap Amazon S3 endpoint map.
  150. var awsS3EndpointMap = map[string]string{
  151. "us-east-1": "s3.dualstack.us-east-1.amazonaws.com",
  152. "us-east-2": "s3.dualstack.us-east-2.amazonaws.com",
  153. "us-west-2": "s3.dualstack.us-west-2.amazonaws.com",
  154. "us-west-1": "s3.dualstack.us-west-1.amazonaws.com",
  155. "ca-central-1": "s3.dualstack.ca-central-1.amazonaws.com",
  156. "eu-west-1": "s3.dualstack.eu-west-1.amazonaws.com",
  157. "eu-west-2": "s3.dualstack.eu-west-2.amazonaws.com",
  158. "eu-west-3": "s3.dualstack.eu-west-3.amazonaws.com",
  159. "eu-central-1": "s3.dualstack.eu-central-1.amazonaws.com",
  160. "eu-north-1": "s3.dualstack.eu-north-1.amazonaws.com",
  161. "ap-east-1": "s3.dualstack.ap-east-1.amazonaws.com",
  162. "ap-south-1": "s3.dualstack.ap-south-1.amazonaws.com",
  163. "ap-southeast-1": "s3.dualstack.ap-southeast-1.amazonaws.com",
  164. "ap-southeast-2": "s3.dualstack.ap-southeast-2.amazonaws.com",
  165. "ap-northeast-1": "s3.dualstack.ap-northeast-1.amazonaws.com",
  166. "ap-northeast-2": "s3.dualstack.ap-northeast-2.amazonaws.com",
  167. "sa-east-1": "s3.dualstack.sa-east-1.amazonaws.com",
  168. "us-gov-west-1": "s3.dualstack.us-gov-west-1.amazonaws.com",
  169. "us-gov-east-1": "s3.dualstack.us-gov-east-1.amazonaws.com",
  170. "cn-north-1": "s3.cn-north-1.amazonaws.com.cn",
  171. "cn-northwest-1": "s3.cn-northwest-1.amazonaws.com.cn",
  172. }
  173. // Non exhaustive list of AWS S3 standard error responses -
  174. // http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
  175. var s3ErrorResponseMap = map[string]string{
  176. "AccessDenied": "Access Denied.",
  177. "BadDigest": "The Content-Md5 you specified did not match what we received.",
  178. "EntityTooSmall": "Your proposed upload is smaller than the minimum allowed object size.",
  179. "EntityTooLarge": "Your proposed upload exceeds the maximum allowed object size.",
  180. "IncompleteBody": "You did not provide the number of bytes specified by the Content-Length HTTP header.",
  181. "InternalError": "We encountered an internal error, please try again.",
  182. "InvalidAccessKeyId": "The access key ID you provided does not exist in our records.",
  183. "InvalidBucketName": "The specified bucket is not valid.",
  184. "InvalidDigest": "The Content-Md5 you specified is not valid.",
  185. "InvalidRange": "The requested range is not satisfiable",
  186. "MalformedXML": "The XML you provided was not well-formed or did not validate against our published schema.",
  187. "MissingContentLength": "You must provide the Content-Length HTTP header.",
  188. "MissingContentMD5": "Missing required header for this request: Content-Md5.",
  189. "MissingRequestBodyError": "Request body is empty.",
  190. "NoSuchBucket": "The specified bucket does not exist.",
  191. "NoSuchBucketPolicy": "The bucket policy does not exist",
  192. "NoSuchKey": "The specified key does not exist.",
  193. "NoSuchUpload": "The specified multipart upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed.",
  194. "NotImplemented": "A header you provided implies functionality that is not implemented",
  195. "PreconditionFailed": "At least one of the pre-conditions you specified did not hold",
  196. "RequestTimeTooSkewed": "The difference between the request time and the server's time is too large.",
  197. "SignatureDoesNotMatch": "The request signature we calculated does not match the signature you provided. Check your key and signing method.",
  198. "MethodNotAllowed": "The specified method is not allowed against this resource.",
  199. "InvalidPart": "One or more of the specified parts could not be found.",
  200. "InvalidPartOrder": "The list of parts was not in ascending order. The parts list must be specified in order by part number.",
  201. "InvalidObjectState": "The operation is not valid for the current state of the object.",
  202. "AuthorizationHeaderMalformed": "The authorization header is malformed; the region is wrong.",
  203. "MalformedPOSTRequest": "The body of your POST request is not well-formed multipart/form-data.",
  204. "BucketNotEmpty": "The bucket you tried to delete is not empty",
  205. "AllAccessDisabled": "All access to this bucket has been disabled.",
  206. "MalformedPolicy": "Policy has invalid resource.",
  207. "MissingFields": "Missing fields in request.",
  208. "AuthorizationQueryParametersError": "Error parsing the X-Amz-Credential parameter; the Credential is mal-formed; expecting \"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".",
  209. "MalformedDate": "Invalid date format header, expected to be in ISO8601, RFC1123 or RFC1123Z time format.",
  210. "BucketAlreadyOwnedByYou": "Your previous request to create the named bucket succeeded and you already own it.",
  211. "InvalidDuration": "Duration provided in the request is invalid.",
  212. "XAmzContentSHA256Mismatch": "The provided 'x-amz-content-sha256' header does not match what was computed.",
  213. // Add new API errors here.
  214. }
  215. // List of success status.
  216. var successStatus = []int{
  217. http.StatusOK,
  218. http.StatusNoContent,
  219. http.StatusPartialContent,
  220. }
  221. // List of HTTP status codes which are retryable.
  222. var retryableHTTPStatusCodes = map[int]struct{}{
  223. 429: {}, // http.StatusTooManyRequests is not part of the Go 1.5 library, yet
  224. http.StatusInternalServerError: {},
  225. http.StatusBadGateway: {},
  226. http.StatusServiceUnavailable: {},
  227. http.StatusGatewayTimeout: {},
  228. // Add more HTTP status codes here.
  229. }
  230. // newBucketLocationCache - Provides a new bucket location cache to be
  231. // used internally with the client object.
  232. func newBucketLocationCache() *bucketLocationCache {
  233. return &bucketLocationCache{
  234. items: make(map[string]string),
  235. }
  236. }
  237. // Redirect requests by re signing the request.
  238. func (c *Client) redirectHeaders(req *http.Request, via []*http.Request) error {
  239. if len(via) >= 5 {
  240. return errors.New("stopped after 5 redirects")
  241. }
  242. if len(via) == 0 {
  243. return nil
  244. }
  245. lastRequest := via[len(via)-1]
  246. var reAuth bool
  247. for attr, val := range lastRequest.Header {
  248. // if hosts do not match do not copy Authorization header
  249. if attr == "Authorization" && req.Host != lastRequest.Host {
  250. reAuth = true
  251. continue
  252. }
  253. if _, ok := req.Header[attr]; !ok {
  254. req.Header[attr] = val
  255. }
  256. }
  257. *c.endpointURL = *req.URL
  258. value, err := c.credsProvider.Get()
  259. if err != nil {
  260. return err
  261. }
  262. var (
  263. signerType = value.SignerType
  264. accessKeyID = value.AccessKeyID
  265. secretAccessKey = value.SecretAccessKey
  266. sessionToken = value.SessionToken
  267. region = c.region
  268. )
  269. // Custom signer set then override the behavior.
  270. if c.overrideSignerType != credentials.SignatureDefault {
  271. signerType = c.overrideSignerType
  272. }
  273. // If signerType returned by credentials helper is anonymous,
  274. // then do not sign regardless of signerType override.
  275. if value.SignerType == credentials.SignatureAnonymous {
  276. signerType = credentials.SignatureAnonymous
  277. }
  278. if reAuth {
  279. // Check if there is no region override, if not get it from the URL if possible.
  280. if region == "" {
  281. region = s3utils.GetRegionFromURL(*c.endpointURL)
  282. }
  283. switch {
  284. case signerType.IsV2():
  285. return errors.New("signature V2 cannot support redirection")
  286. case signerType.IsV4():
  287. s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, getDefaultLocation(*c.endpointURL, region))
  288. }
  289. }
  290. return nil
  291. }
  292. func privateNew(endpoint string, creds *credentials.Credentials, secure bool, region string, lookup BucketLookupType) (*Client, error) {
  293. // construct endpoint.
  294. endpointURL, err := getEndpointURL(endpoint, secure)
  295. if err != nil {
  296. return nil, err
  297. }
  298. // Initialize cookies to preserve server sent cookies if any and replay
  299. // them upon each request.
  300. jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
  301. if err != nil {
  302. return nil, err
  303. }
  304. // instantiate new Client.
  305. clnt := new(Client)
  306. // Save the credentials.
  307. clnt.credsProvider = creds
  308. // Remember whether we are using https or not
  309. clnt.secure = secure
  310. // Save endpoint URL, user agent for future uses.
  311. clnt.endpointURL = endpointURL
  312. transport, err := DefaultTransport(secure)
  313. if err != nil {
  314. return nil, err
  315. }
  316. // Instantiate http client and bucket location cache.
  317. clnt.httpClient = &http.Client{
  318. Jar: jar,
  319. Transport: transport,
  320. CheckRedirect: clnt.redirectHeaders,
  321. }
  322. // Sets custom region, if region is empty bucket location cache is used automatically.
  323. if region == "" {
  324. region = s3utils.GetRegionFromURL(*clnt.endpointURL)
  325. }
  326. clnt.region = region
  327. // Instantiate bucket location cache.
  328. clnt.bucketLocCache = newBucketLocationCache()
  329. // Introduce a new locked random seed.
  330. clnt.random = rand.New(&lockedRandSource{src: rand.NewSource(time.Now().UTC().UnixNano())})
  331. // Sets bucket lookup style, whether server accepts DNS or Path lookup. Default is Auto - determined
  332. // by the SDK. When Auto is specified, DNS lookup is used for Amazon/Google cloud endpoints and Path for all other endpoints.
  333. clnt.lookup = lookup
  334. // Return.
  335. return clnt, nil
  336. }
  337. // New - instantiate minio client, adds automatic verification of signature.
  338. func New(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
  339. creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
  340. clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
  341. if err != nil {
  342. return nil, err
  343. }
  344. // Google cloud storage should be set to signature V2, force it if not.
  345. if s3utils.IsGoogleEndpoint(*clnt.endpointURL) {
  346. clnt.overrideSignerType = credentials.SignatureV2
  347. }
  348. // If Amazon S3 set to signature v4.
  349. if s3utils.IsAmazonEndpoint(*clnt.endpointURL) {
  350. clnt.overrideSignerType = credentials.SignatureV4
  351. }
  352. return clnt, nil
  353. }
  354. // isHTTPStatusRetryable - is HTTP error code retryable.
  355. func isHTTPStatusRetryable(httpStatusCode int) (ok bool) {
  356. _, ok = retryableHTTPStatusCodes[httpStatusCode]
  357. return ok
  358. }
  359. // newRetryTimer creates a timer with exponentially increasing
  360. // delays until the maximum retry attempts are reached.
  361. func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
  362. attemptCh := make(chan int)
  363. // computes the exponential backoff duration according to
  364. // https://www.awsarchitectureblog.com/2015/03/backoff.html
  365. exponentialBackoffWait := func(attempt int) time.Duration {
  366. // normalize jitter to the range [0, 1.0]
  367. if jitter < NoJitter {
  368. jitter = NoJitter
  369. }
  370. if jitter > MaxJitter {
  371. jitter = MaxJitter
  372. }
  373. //sleep = random_between(0, min(cap, base * 2 ** attempt))
  374. sleep := unit * time.Duration(1<<uint(attempt))
  375. if sleep > cap {
  376. sleep = cap
  377. }
  378. if jitter != NoJitter {
  379. sleep -= time.Duration(c.random.Float64() * float64(sleep) * jitter)
  380. }
  381. return sleep
  382. }
  383. go func() {
  384. defer close(attemptCh)
  385. for i := 0; i < maxRetry; i++ {
  386. select {
  387. // Attempts start from 1.
  388. case attemptCh <- i + 1:
  389. case <-doneCh:
  390. // Stop the routine.
  391. return
  392. }
  393. time.Sleep(exponentialBackoffWait(i))
  394. }
  395. }()
  396. return attemptCh
  397. }
  398. // Get - Returns a value of a given key if it exists.
  399. func (r *bucketLocationCache) Get(bucketName string) (location string, ok bool) {
  400. r.RLock()
  401. defer r.RUnlock()
  402. location, ok = r.items[bucketName]
  403. return
  404. }
  405. // set User agent.
  406. func (c Client) setUserAgent(req *http.Request) {
  407. req.Header.Set("User-Agent", libraryUserAgent)
  408. if c.appInfo.appName != "" && c.appInfo.appVersion != "" {
  409. req.Header.Set("User-Agent", libraryUserAgent+" "+c.appInfo.appName+"/"+c.appInfo.appVersion)
  410. }
  411. }
  412. // getBucketLocationRequest - Wrapper creates a new getBucketLocation request.
  413. func (c Client) getBucketLocationRequest(bucketName string) (*http.Request, error) {
  414. // Set location query.
  415. urlValues := make(url.Values)
  416. urlValues.Set("location", "")
  417. // Set get bucket location always as path style.
  418. targetURL := *c.endpointURL
  419. // as it works in makeTargetURL method from api.go file
  420. if h, p, err := net.SplitHostPort(targetURL.Host); err == nil {
  421. if targetURL.Scheme == "http" && p == "80" || targetURL.Scheme == "https" && p == "443" {
  422. targetURL.Host = h
  423. }
  424. }
  425. targetURL.Path = path.Join(bucketName, "") + "/"
  426. targetURL.RawQuery = urlValues.Encode()
  427. // Get a new HTTP request for the method.
  428. req, err := http.NewRequest("GET", targetURL.String(), nil)
  429. if err != nil {
  430. return nil, err
  431. }
  432. // Set UserAgent for the request.
  433. c.setUserAgent(req)
  434. // Get credentials from the configured credentials provider.
  435. value, err := c.credsProvider.Get()
  436. if err != nil {
  437. return nil, err
  438. }
  439. var (
  440. signerType = value.SignerType
  441. accessKeyID = value.AccessKeyID
  442. secretAccessKey = value.SecretAccessKey
  443. sessionToken = value.SessionToken
  444. )
  445. // Custom signer set then override the behavior.
  446. if c.overrideSignerType != credentials.SignatureDefault {
  447. signerType = c.overrideSignerType
  448. }
  449. // If signerType returned by credentials helper is anonymous,
  450. // then do not sign regardless of signerType override.
  451. if value.SignerType == credentials.SignatureAnonymous {
  452. signerType = credentials.SignatureAnonymous
  453. }
  454. if signerType.IsAnonymous() {
  455. return req, nil
  456. }
  457. if signerType.IsV2() {
  458. // Get Bucket Location calls should be always path style
  459. isVirtualHost := false
  460. req = s3signer.SignV2(*req, accessKeyID, secretAccessKey, isVirtualHost)
  461. return req, nil
  462. }
  463. // Set sha256 sum for signature calculation only with signature version '4'.
  464. contentSha256 := emptySHA256Hex
  465. if c.secure {
  466. contentSha256 = unsignedPayload
  467. }
  468. req.Header.Set("X-Amz-Content-Sha256", contentSha256)
  469. req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, "us-east-1")
  470. return req, nil
  471. }
  472. // dumpHTTP - dump HTTP request and response.
  473. func (c Client) dumpHTTP(req *http.Request, resp *http.Response) error {
  474. // Starts http dump.
  475. _, err := fmt.Fprintln(c.traceOutput, "---------START-HTTP---------")
  476. if err != nil {
  477. return err
  478. }
  479. // Filter out Signature field from Authorization header.
  480. origAuth := req.Header.Get("Authorization")
  481. if origAuth != "" {
  482. req.Header.Set("Authorization", redactSignature(origAuth))
  483. }
  484. // Only display request header.
  485. reqTrace, err := httputil.DumpRequestOut(req, false)
  486. if err != nil {
  487. return err
  488. }
  489. // Write request to trace output.
  490. _, err = fmt.Fprint(c.traceOutput, string(reqTrace))
  491. if err != nil {
  492. return err
  493. }
  494. // Only display response header.
  495. var respTrace []byte
  496. // For errors we make sure to dump response body as well.
  497. if resp.StatusCode != http.StatusOK &&
  498. resp.StatusCode != http.StatusPartialContent &&
  499. resp.StatusCode != http.StatusNoContent {
  500. respTrace, err = httputil.DumpResponse(resp, true)
  501. if err != nil {
  502. return err
  503. }
  504. } else {
  505. respTrace, err = httputil.DumpResponse(resp, false)
  506. if err != nil {
  507. return err
  508. }
  509. }
  510. // Write response to trace output.
  511. _, err = fmt.Fprint(c.traceOutput, strings.TrimSuffix(string(respTrace), "\r\n"))
  512. if err != nil {
  513. return err
  514. }
  515. // Ends the http dump.
  516. _, err = fmt.Fprintln(c.traceOutput, "---------END-HTTP---------")
  517. if err != nil {
  518. return err
  519. }
  520. // Returns success.
  521. return nil
  522. }
  523. // do - execute http request.
  524. func (c Client) do(req *http.Request) (*http.Response, error) {
  525. resp, err := c.httpClient.Do(req)
  526. if err != nil {
  527. // Handle this specifically for now until future Golang versions fix this issue properly.
  528. if urlErr, ok := err.(*url.Error); ok {
  529. if strings.Contains(urlErr.Err.Error(), "EOF") {
  530. return nil, &url.Error{
  531. Op: urlErr.Op,
  532. URL: urlErr.URL,
  533. Err: errors.New("Connection closed by foreign host " + urlErr.URL + ". Retry again."),
  534. }
  535. }
  536. }
  537. return nil, err
  538. }
  539. // Response cannot be non-nil, report error if thats the case.
  540. if resp == nil {
  541. msg := "Response is empty. " + reportIssue
  542. return nil, ErrInvalidArgument(msg)
  543. }
  544. // If trace is enabled, dump http request and response,
  545. // except when the traceErrorsOnly enabled and the response's status code is ok
  546. if c.isTraceEnabled && !(c.traceErrorsOnly && resp.StatusCode == http.StatusOK) {
  547. err = c.dumpHTTP(req, resp)
  548. if err != nil {
  549. return nil, err
  550. }
  551. }
  552. return resp, nil
  553. }
  554. // getBucketLocation - Get location for the bucketName from location map cache, if not
  555. // fetch freshly by making a new request.
  556. func (c Client) getBucketLocation(bucketName string) (string, error) {
  557. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  558. return "", err
  559. }
  560. // Region set then no need to fetch bucket location.
  561. if c.region != "" {
  562. return c.region, nil
  563. }
  564. if location, ok := c.bucketLocCache.Get(bucketName); ok {
  565. return location, nil
  566. }
  567. // Initialize a new request.
  568. req, err := c.getBucketLocationRequest(bucketName)
  569. if err != nil {
  570. return "", err
  571. }
  572. // Initiate the request.
  573. resp, err := c.do(req)
  574. defer closeResponse(resp)
  575. if err != nil {
  576. return "", err
  577. }
  578. location, err := processBucketLocationResponse(resp, bucketName)
  579. if err != nil {
  580. return "", err
  581. }
  582. c.bucketLocCache.Set(bucketName, location)
  583. return location, nil
  584. }
  585. // Set - Will persist a value into cache.
  586. func (r *bucketLocationCache) Set(bucketName string, location string) {
  587. r.Lock()
  588. defer r.Unlock()
  589. r.items[bucketName] = location
  590. }
  591. // processes the getBucketLocation http response from the server.
  592. func processBucketLocationResponse(resp *http.Response, bucketName string) (bucketLocation string, err error) {
  593. if resp != nil {
  594. if resp.StatusCode != http.StatusOK {
  595. err = httpRespToErrorResponse(resp, bucketName, "")
  596. errResp := ToErrorResponse(err)
  597. // For access denied error, it could be an anonymous
  598. // request. Move forward and let the top level callers
  599. // succeed if possible based on their policy.
  600. switch errResp.Code {
  601. case "AuthorizationHeaderMalformed":
  602. fallthrough
  603. case "InvalidRegion":
  604. fallthrough
  605. case "AccessDenied":
  606. if errResp.Region == "" {
  607. return "us-east-1", nil
  608. }
  609. return errResp.Region, nil
  610. }
  611. return "", err
  612. }
  613. }
  614. // Extract location.
  615. var locationConstraint string
  616. err = xmlDecoder(resp.Body, &locationConstraint)
  617. if err != nil {
  618. return "", err
  619. }
  620. location := locationConstraint
  621. // Location is empty will be 'us-east-1'.
  622. if location == "" {
  623. location = "us-east-1"
  624. }
  625. // Location can be 'EU' convert it to meaningful 'eu-west-1'.
  626. if location == "EU" {
  627. location = "eu-west-1"
  628. }
  629. // Save the location into cache.
  630. // Return.
  631. return location, nil
  632. }
  633. // Get default location returns the location based on the input
  634. // URL `u`, if region override is provided then all location
  635. // defaults to regionOverride.
  636. //
  637. // If no other cases match then the location is set to `us-east-1`
  638. // as a last resort.
  639. func getDefaultLocation(u url.URL, regionOverride string) (location string) {
  640. if regionOverride != "" {
  641. return regionOverride
  642. }
  643. region := s3utils.GetRegionFromURL(u)
  644. if region == "" {
  645. region = "us-east-1"
  646. }
  647. return region
  648. }
  649. // returns true if virtual hosted style requests are to be used.
  650. func (c *Client) isVirtualHostStyleRequest(url url.URL, bucketName string) bool {
  651. if bucketName == "" {
  652. return false
  653. }
  654. if c.lookup == BucketLookupDNS {
  655. return true
  656. }
  657. if c.lookup == BucketLookupPath {
  658. return false
  659. }
  660. // default to virtual only for Amazon/Google storage. In all other cases use
  661. // path style requests
  662. return s3utils.IsVirtualHostSupported(url, bucketName)
  663. }
  664. // ErrTransferAccelerationBucket - bucket name is invalid to be used with transfer acceleration.
  665. func ErrTransferAccelerationBucket(bucketName string) error {
  666. return ErrorResponse{
  667. StatusCode: http.StatusBadRequest,
  668. Code: "InvalidArgument",
  669. Message: "The name of the bucket used for Transfer Acceleration must be DNS-compliant and must not contain periods ‘.’.",
  670. BucketName: bucketName,
  671. }
  672. }
  673. // getS3Endpoint get Amazon S3 endpoint based on the bucket location.
  674. func getS3Endpoint(bucketLocation string) (s3Endpoint string) {
  675. s3Endpoint, ok := awsS3EndpointMap[bucketLocation]
  676. if !ok {
  677. // Default to 's3.dualstack.us-east-1.amazonaws.com' endpoint.
  678. s3Endpoint = "s3.dualstack.us-east-1.amazonaws.com"
  679. }
  680. return s3Endpoint
  681. }
  682. // makeTargetURL make a new target url.
  683. func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, isVirtualHostStyle bool, queryValues url.Values) (*url.URL, error) {
  684. host := c.endpointURL.Host
  685. // For Amazon S3 endpoint, try to fetch location based endpoint.
  686. if s3utils.IsAmazonEndpoint(*c.endpointURL) {
  687. if c.s3AccelerateEndpoint != "" && bucketName != "" {
  688. // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html
  689. // Disable transfer acceleration for non-compliant bucket names.
  690. if strings.Contains(bucketName, ".") {
  691. return nil, ErrTransferAccelerationBucket(bucketName)
  692. }
  693. // If transfer acceleration is requested set new host.
  694. // For more details about enabling transfer acceleration read here.
  695. // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html
  696. host = c.s3AccelerateEndpoint
  697. } else {
  698. // Do not change the host if the endpoint URL is a FIPS S3 endpoint.
  699. if !s3utils.IsAmazonFIPSEndpoint(*c.endpointURL) {
  700. // Fetch new host based on the bucket location.
  701. host = getS3Endpoint(bucketLocation)
  702. }
  703. }
  704. }
  705. // Save scheme.
  706. scheme := c.endpointURL.Scheme
  707. // Strip port 80 and 443 so we won't send these ports in Host header.
  708. // The reason is that browsers and curl automatically remove :80 and :443
  709. // with the generated presigned urls, then a signature mismatch error.
  710. if h, p, err := net.SplitHostPort(host); err == nil {
  711. if scheme == "http" && p == "80" || scheme == "https" && p == "443" {
  712. host = h
  713. }
  714. }
  715. urlStr := scheme + "://" + host + "/"
  716. // Make URL only if bucketName is available, otherwise use the
  717. // endpoint URL.
  718. if bucketName != "" {
  719. // If endpoint supports virtual host style use that always.
  720. // Currently only S3 and Google Cloud Storage would support
  721. // virtual host style.
  722. if isVirtualHostStyle {
  723. urlStr = scheme + "://" + bucketName + "." + host + "/"
  724. if objectName != "" {
  725. urlStr = urlStr + s3utils.EncodePath(objectName)
  726. }
  727. } else {
  728. // If not fall back to using path style.
  729. urlStr = urlStr + bucketName + "/"
  730. if objectName != "" {
  731. urlStr = urlStr + s3utils.EncodePath(objectName)
  732. }
  733. }
  734. }
  735. // If there are any query values, add them to the end.
  736. if len(queryValues) > 0 {
  737. urlStr = urlStr + "?" + s3utils.QueryEncode(queryValues)
  738. }
  739. return url.Parse(urlStr)
  740. }
  741. // newRequest - instantiate a new HTTP request for a given method.
  742. func (c Client) newRequest(method string, metadata requestMetadata) (req *http.Request, err error) {
  743. // If no method is supplied default to 'POST'.
  744. if method == "" {
  745. method = "POST"
  746. }
  747. location := metadata.bucketLocation
  748. if location == "" {
  749. if metadata.bucketName != "" {
  750. // Gather location only if bucketName is present.
  751. location, err = c.getBucketLocation(metadata.bucketName)
  752. if err != nil {
  753. return nil, err
  754. }
  755. }
  756. if location == "" {
  757. location = getDefaultLocation(*c.endpointURL, c.region)
  758. }
  759. }
  760. // Look if target url supports virtual host.
  761. // We explicitly disallow MakeBucket calls to not use virtual DNS style,
  762. // since the resolution may fail.
  763. isMakeBucket := (metadata.objectName == "" && method == "PUT" && len(metadata.queryValues) == 0)
  764. isVirtualHost := c.isVirtualHostStyleRequest(*c.endpointURL, metadata.bucketName) && !isMakeBucket
  765. // Construct a new target URL.
  766. targetURL, err := c.makeTargetURL(metadata.bucketName, metadata.objectName, location,
  767. isVirtualHost, metadata.queryValues)
  768. if err != nil {
  769. return nil, err
  770. }
  771. // Initialize a new HTTP request for the method.
  772. req, err = http.NewRequest(method, targetURL.String(), nil)
  773. if err != nil {
  774. return nil, err
  775. }
  776. // Get credentials from the configured credentials provider.
  777. value, err := c.credsProvider.Get()
  778. if err != nil {
  779. return nil, err
  780. }
  781. var (
  782. signerType = value.SignerType
  783. accessKeyID = value.AccessKeyID
  784. secretAccessKey = value.SecretAccessKey
  785. sessionToken = value.SessionToken
  786. )
  787. // Custom signer set then override the behavior.
  788. if c.overrideSignerType != credentials.SignatureDefault {
  789. signerType = c.overrideSignerType
  790. }
  791. // If signerType returned by credentials helper is anonymous,
  792. // then do not sign regardless of signerType override.
  793. if value.SignerType == credentials.SignatureAnonymous {
  794. signerType = credentials.SignatureAnonymous
  795. }
  796. // Generate presign url if needed, return right here.
  797. if metadata.expires != 0 && metadata.presignURL {
  798. if signerType.IsAnonymous() {
  799. return nil, ErrInvalidArgument("Presigned URLs cannot be generated with anonymous credentials.")
  800. }
  801. if signerType.IsV2() {
  802. // Presign URL with signature v2.
  803. req = s3signer.PreSignV2(*req, accessKeyID, secretAccessKey, metadata.expires, isVirtualHost)
  804. } else if signerType.IsV4() {
  805. // Presign URL with signature v4.
  806. req = s3signer.PreSignV4(*req, accessKeyID, secretAccessKey, sessionToken, location, metadata.expires)
  807. }
  808. return req, nil
  809. }
  810. // Set 'User-Agent' header for the request.
  811. c.setUserAgent(req)
  812. // Set all headers.
  813. for k, v := range metadata.customHeader {
  814. req.Header.Set(k, v[0])
  815. }
  816. // Go net/http notoriously closes the request body.
  817. // - The request Body, if non-nil, will be closed by the underlying Transport, even on errors.
  818. // This can cause underlying *os.File seekers to fail, avoid that
  819. // by making sure to wrap the closer as a nop.
  820. if metadata.contentLength == 0 {
  821. req.Body = nil
  822. } else {
  823. req.Body = ioutil.NopCloser(metadata.contentBody)
  824. }
  825. // Set incoming content-length.
  826. req.ContentLength = metadata.contentLength
  827. if req.ContentLength <= -1 {
  828. // For unknown content length, we upload using transfer-encoding: chunked.
  829. req.TransferEncoding = []string{"chunked"}
  830. }
  831. // set md5Sum for content protection.
  832. if len(metadata.contentMD5Base64) > 0 {
  833. req.Header.Set("Content-Md5", metadata.contentMD5Base64)
  834. }
  835. // For anonymous requests just return.
  836. if signerType.IsAnonymous() {
  837. return req, nil
  838. }
  839. switch {
  840. case signerType.IsV2():
  841. // Add signature version '2' authorization header.
  842. req = s3signer.SignV2(*req, accessKeyID, secretAccessKey, isVirtualHost)
  843. case metadata.objectName != "" && method == "PUT" && metadata.customHeader.Get("X-Amz-Copy-Source") == "" && !c.secure:
  844. // Streaming signature is used by default for a PUT object request. Additionally we also
  845. // look if the initialized client is secure, if yes then we don't need to perform
  846. // streaming signature.
  847. req = s3signer.StreamingSignV4(req, accessKeyID,
  848. secretAccessKey, sessionToken, location, metadata.contentLength, time.Now().UTC())
  849. default:
  850. // Set sha256 sum for signature calculation only with signature version '4'.
  851. shaHeader := unsignedPayload
  852. if metadata.contentSHA256Hex != "" {
  853. shaHeader = metadata.contentSHA256Hex
  854. }
  855. req.Header.Set("X-Amz-Content-Sha256", shaHeader)
  856. // Add signature version '4' authorization header.
  857. req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, location)
  858. }
  859. // Return request.
  860. return req, nil
  861. }
  862. func (c Client) GenUploadPartSignedUrl(uploadID string, bucketName string, objectName string, partNumber int, size int64, expires time.Duration, bucketLocation string) (string, error) {
  863. signedUrl := ""
  864. // Input validation.
  865. if err := s3utils.CheckValidBucketName(bucketName); err != nil {
  866. return signedUrl, err
  867. }
  868. if err := s3utils.CheckValidObjectName(objectName); err != nil {
  869. return signedUrl, err
  870. }
  871. if size > maxPartSize {
  872. return signedUrl, errors.New("size is illegal")
  873. }
  874. if size <= -1 {
  875. return signedUrl, errors.New("size is illegal")
  876. }
  877. if partNumber <= 0 {
  878. return signedUrl, errors.New("partNumber is illegal")
  879. }
  880. if uploadID == "" {
  881. return signedUrl, errors.New("uploadID is illegal")
  882. }
  883. // Get resources properly escaped and lined up before using them in http request.
  884. urlValues := make(url.Values)
  885. // Set part number.
  886. urlValues.Set("partNumber", strconv.Itoa(partNumber))
  887. // Set upload id.
  888. urlValues.Set("uploadId", uploadID)
  889. // Set encryption headers, if any.
  890. customHeader := make(http.Header)
  891. reqMetadata := requestMetadata{
  892. presignURL: true,
  893. bucketName: bucketName,
  894. objectName: objectName,
  895. queryValues: urlValues,
  896. customHeader: customHeader,
  897. //contentBody: reader,
  898. contentLength: size,
  899. //contentMD5Base64: md5Base64,
  900. //contentSHA256Hex: sha256Hex,
  901. expires: int64(expires / time.Second),
  902. bucketLocation: bucketLocation,
  903. }
  904. req, err := c.newRequest("PUT", reqMetadata)
  905. if err != nil {
  906. log.Println("newRequest failed:", err.Error())
  907. return signedUrl, err
  908. }
  909. signedUrl = req.URL.String()
  910. return signedUrl, nil
  911. }