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.

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