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

api.go 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /*
  2. * MinIO Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2015-2018 MinIO, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package minio
  18. import (
  19. "bytes"
  20. "context"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "math/rand"
  26. "net"
  27. "net/http"
  28. "net/http/cookiejar"
  29. "net/http/httputil"
  30. "net/url"
  31. "os"
  32. "runtime"
  33. "strings"
  34. "sync"
  35. "time"
  36. md5simd "github.com/minio/md5-simd"
  37. "github.com/minio/minio-go/v7/pkg/credentials"
  38. "github.com/minio/minio-go/v7/pkg/s3utils"
  39. "github.com/minio/minio-go/v7/pkg/signer"
  40. "golang.org/x/net/publicsuffix"
  41. )
  42. // Client implements Amazon S3 compatible methods.
  43. type Client struct {
  44. /// Standard options.
  45. // Parsed endpoint url provided by the user.
  46. endpointURL *url.URL
  47. // Holds various credential providers.
  48. credsProvider *credentials.Credentials
  49. // Custom signerType value overrides all credentials.
  50. overrideSignerType credentials.SignatureType
  51. // User supplied.
  52. appInfo struct {
  53. appName string
  54. appVersion string
  55. }
  56. // Indicate whether we are using https or not
  57. secure bool
  58. // Needs allocation.
  59. httpClient *http.Client
  60. bucketLocCache *bucketLocationCache
  61. // Advanced functionality.
  62. isTraceEnabled bool
  63. traceErrorsOnly bool
  64. traceOutput io.Writer
  65. // S3 specific accelerated endpoint.
  66. s3AccelerateEndpoint string
  67. // Region endpoint
  68. region string
  69. // Random seed.
  70. random *rand.Rand
  71. // lookup indicates type of url lookup supported by server. If not specified,
  72. // default to Auto.
  73. lookup BucketLookupType
  74. // Factory for MD5 hash functions.
  75. md5Hasher func() md5simd.Hasher
  76. sha256Hasher func() md5simd.Hasher
  77. }
  78. // Options for New method
  79. type Options struct {
  80. Creds *credentials.Credentials
  81. Secure bool
  82. Transport http.RoundTripper
  83. Region string
  84. BucketLookup BucketLookupType
  85. // Custom hash routines. Leave nil to use standard.
  86. CustomMD5 func() md5simd.Hasher
  87. CustomSHA256 func() md5simd.Hasher
  88. }
  89. // Global constants.
  90. const (
  91. libraryName = "minio-go"
  92. libraryVersion = "v7.0.6"
  93. )
  94. // User Agent should always following the below style.
  95. // Please open an issue to discuss any new changes here.
  96. //
  97. // MinIO (OS; ARCH) LIB/VER APP/VER
  98. const (
  99. libraryUserAgentPrefix = "MinIO (" + runtime.GOOS + "; " + runtime.GOARCH + ") "
  100. libraryUserAgent = libraryUserAgentPrefix + libraryName + "/" + libraryVersion
  101. )
  102. // BucketLookupType is type of url lookup supported by server.
  103. type BucketLookupType int
  104. // Different types of url lookup supported by the server.Initialized to BucketLookupAuto
  105. const (
  106. BucketLookupAuto BucketLookupType = iota
  107. BucketLookupDNS
  108. BucketLookupPath
  109. )
  110. // New - instantiate minio client with options
  111. func New(endpoint string, opts *Options) (*Client, error) {
  112. if opts == nil {
  113. return nil, errors.New("no options provided")
  114. }
  115. clnt, err := privateNew(endpoint, opts)
  116. if err != nil {
  117. return nil, err
  118. }
  119. // Google cloud storage should be set to signature V2, force it if not.
  120. if s3utils.IsGoogleEndpoint(*clnt.endpointURL) {
  121. clnt.overrideSignerType = credentials.SignatureV2
  122. }
  123. // If Amazon S3 set to signature v4.
  124. if s3utils.IsAmazonEndpoint(*clnt.endpointURL) {
  125. clnt.overrideSignerType = credentials.SignatureV4
  126. }
  127. return clnt, nil
  128. }
  129. // EndpointURL returns the URL of the S3 endpoint.
  130. func (c *Client) EndpointURL() *url.URL {
  131. endpoint := *c.endpointURL // copy to prevent callers from modifying internal state
  132. return &endpoint
  133. }
  134. // lockedRandSource provides protected rand source, implements rand.Source interface.
  135. type lockedRandSource struct {
  136. lk sync.Mutex
  137. src rand.Source
  138. }
  139. // Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
  140. func (r *lockedRandSource) Int63() (n int64) {
  141. r.lk.Lock()
  142. n = r.src.Int63()
  143. r.lk.Unlock()
  144. return
  145. }
  146. // Seed uses the provided seed value to initialize the generator to a
  147. // deterministic state.
  148. func (r *lockedRandSource) Seed(seed int64) {
  149. r.lk.Lock()
  150. r.src.Seed(seed)
  151. r.lk.Unlock()
  152. }
  153. // Redirect requests by re signing the request.
  154. func (c *Client) redirectHeaders(req *http.Request, via []*http.Request) error {
  155. if len(via) >= 5 {
  156. return errors.New("stopped after 5 redirects")
  157. }
  158. if len(via) == 0 {
  159. return nil
  160. }
  161. lastRequest := via[len(via)-1]
  162. var reAuth bool
  163. for attr, val := range lastRequest.Header {
  164. // if hosts do not match do not copy Authorization header
  165. if attr == "Authorization" && req.Host != lastRequest.Host {
  166. reAuth = true
  167. continue
  168. }
  169. if _, ok := req.Header[attr]; !ok {
  170. req.Header[attr] = val
  171. }
  172. }
  173. *c.endpointURL = *req.URL
  174. value, err := c.credsProvider.Get()
  175. if err != nil {
  176. return err
  177. }
  178. var (
  179. signerType = value.SignerType
  180. accessKeyID = value.AccessKeyID
  181. secretAccessKey = value.SecretAccessKey
  182. sessionToken = value.SessionToken
  183. region = c.region
  184. )
  185. // Custom signer set then override the behavior.
  186. if c.overrideSignerType != credentials.SignatureDefault {
  187. signerType = c.overrideSignerType
  188. }
  189. // If signerType returned by credentials helper is anonymous,
  190. // then do not sign regardless of signerType override.
  191. if value.SignerType == credentials.SignatureAnonymous {
  192. signerType = credentials.SignatureAnonymous
  193. }
  194. if reAuth {
  195. // Check if there is no region override, if not get it from the URL if possible.
  196. if region == "" {
  197. region = s3utils.GetRegionFromURL(*c.endpointURL)
  198. }
  199. switch {
  200. case signerType.IsV2():
  201. return errors.New("signature V2 cannot support redirection")
  202. case signerType.IsV4():
  203. signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, getDefaultLocation(*c.endpointURL, region))
  204. }
  205. }
  206. return nil
  207. }
  208. func privateNew(endpoint string, opts *Options) (*Client, error) {
  209. // construct endpoint.
  210. endpointURL, err := getEndpointURL(endpoint, opts.Secure)
  211. if err != nil {
  212. return nil, err
  213. }
  214. // Initialize cookies to preserve server sent cookies if any and replay
  215. // them upon each request.
  216. jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
  217. if err != nil {
  218. return nil, err
  219. }
  220. // instantiate new Client.
  221. clnt := new(Client)
  222. // Save the credentials.
  223. clnt.credsProvider = opts.Creds
  224. // Remember whether we are using https or not
  225. clnt.secure = opts.Secure
  226. // Save endpoint URL, user agent for future uses.
  227. clnt.endpointURL = endpointURL
  228. transport := opts.Transport
  229. if transport == nil {
  230. transport, err = DefaultTransport(opts.Secure)
  231. if err != nil {
  232. return nil, err
  233. }
  234. }
  235. // Instantiate http client and bucket location cache.
  236. clnt.httpClient = &http.Client{
  237. Jar: jar,
  238. Transport: transport,
  239. CheckRedirect: clnt.redirectHeaders,
  240. }
  241. // Sets custom region, if region is empty bucket location cache is used automatically.
  242. if opts.Region == "" {
  243. opts.Region = s3utils.GetRegionFromURL(*clnt.endpointURL)
  244. }
  245. clnt.region = opts.Region
  246. // Instantiate bucket location cache.
  247. clnt.bucketLocCache = newBucketLocationCache()
  248. // Introduce a new locked random seed.
  249. clnt.random = rand.New(&lockedRandSource{src: rand.NewSource(time.Now().UTC().UnixNano())})
  250. // Add default md5 hasher.
  251. clnt.md5Hasher = opts.CustomMD5
  252. clnt.sha256Hasher = opts.CustomSHA256
  253. if clnt.md5Hasher == nil {
  254. clnt.md5Hasher = newMd5Hasher
  255. }
  256. if clnt.sha256Hasher == nil {
  257. clnt.sha256Hasher = newSHA256Hasher
  258. }
  259. // Sets bucket lookup style, whether server accepts DNS or Path lookup. Default is Auto - determined
  260. // by the SDK. When Auto is specified, DNS lookup is used for Amazon/Google cloud endpoints and Path for all other endpoints.
  261. clnt.lookup = opts.BucketLookup
  262. // Return.
  263. return clnt, nil
  264. }
  265. // SetAppInfo - add application details to user agent.
  266. func (c *Client) SetAppInfo(appName string, appVersion string) {
  267. // if app name and version not set, we do not set a new user agent.
  268. if appName != "" && appVersion != "" {
  269. c.appInfo.appName = appName
  270. c.appInfo.appVersion = appVersion
  271. }
  272. }
  273. // TraceOn - enable HTTP tracing.
  274. func (c *Client) TraceOn(outputStream io.Writer) {
  275. // if outputStream is nil then default to os.Stdout.
  276. if outputStream == nil {
  277. outputStream = os.Stdout
  278. }
  279. // Sets a new output stream.
  280. c.traceOutput = outputStream
  281. // Enable tracing.
  282. c.isTraceEnabled = true
  283. }
  284. // TraceErrorsOnlyOn - same as TraceOn, but only errors will be traced.
  285. func (c *Client) TraceErrorsOnlyOn(outputStream io.Writer) {
  286. c.TraceOn(outputStream)
  287. c.traceErrorsOnly = true
  288. }
  289. // TraceErrorsOnlyOff - Turns off the errors only tracing and everything will be traced after this call.
  290. // If all tracing needs to be turned off, call TraceOff().
  291. func (c *Client) TraceErrorsOnlyOff() {
  292. c.traceErrorsOnly = false
  293. }
  294. // TraceOff - disable HTTP tracing.
  295. func (c *Client) TraceOff() {
  296. // Disable tracing.
  297. c.isTraceEnabled = false
  298. c.traceErrorsOnly = false
  299. }
  300. // SetS3TransferAccelerate - turns s3 accelerated endpoint on or off for all your
  301. // requests. This feature is only specific to S3 for all other endpoints this
  302. // function does nothing. To read further details on s3 transfer acceleration
  303. // please vist -
  304. // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html
  305. func (c *Client) SetS3TransferAccelerate(accelerateEndpoint string) {
  306. if s3utils.IsAmazonEndpoint(*c.endpointURL) {
  307. c.s3AccelerateEndpoint = accelerateEndpoint
  308. }
  309. }
  310. // Hash materials provides relevant initialized hash algo writers
  311. // based on the expected signature type.
  312. //
  313. // - For signature v4 request if the connection is insecure compute only sha256.
  314. // - For signature v4 request if the connection is secure compute only md5.
  315. // - For anonymous request compute md5.
  316. func (c *Client) hashMaterials(isMd5Requested bool) (hashAlgos map[string]md5simd.Hasher, hashSums map[string][]byte) {
  317. hashSums = make(map[string][]byte)
  318. hashAlgos = make(map[string]md5simd.Hasher)
  319. if c.overrideSignerType.IsV4() {
  320. if c.secure {
  321. hashAlgos["md5"] = c.md5Hasher()
  322. } else {
  323. hashAlgos["sha256"] = c.sha256Hasher()
  324. }
  325. } else {
  326. if c.overrideSignerType.IsAnonymous() {
  327. hashAlgos["md5"] = c.md5Hasher()
  328. }
  329. }
  330. if isMd5Requested {
  331. hashAlgos["md5"] = c.md5Hasher()
  332. }
  333. return hashAlgos, hashSums
  334. }
  335. // requestMetadata - is container for all the values to make a request.
  336. type requestMetadata struct {
  337. // If set newRequest presigns the URL.
  338. presignURL bool
  339. // User supplied.
  340. bucketName string
  341. objectName string
  342. queryValues url.Values
  343. customHeader http.Header
  344. expires int64
  345. // Generated by our internal code.
  346. bucketLocation string
  347. contentBody io.Reader
  348. contentLength int64
  349. contentMD5Base64 string // carries base64 encoded md5sum
  350. contentSHA256Hex string // carries hex encoded sha256sum
  351. }
  352. // dumpHTTP - dump HTTP request and response.
  353. func (c Client) dumpHTTP(req *http.Request, resp *http.Response) error {
  354. // Starts http dump.
  355. _, err := fmt.Fprintln(c.traceOutput, "---------START-HTTP---------")
  356. if err != nil {
  357. return err
  358. }
  359. // Filter out Signature field from Authorization header.
  360. origAuth := req.Header.Get("Authorization")
  361. if origAuth != "" {
  362. req.Header.Set("Authorization", redactSignature(origAuth))
  363. }
  364. // Only display request header.
  365. reqTrace, err := httputil.DumpRequestOut(req, false)
  366. if err != nil {
  367. return err
  368. }
  369. // Write request to trace output.
  370. _, err = fmt.Fprint(c.traceOutput, string(reqTrace))
  371. if err != nil {
  372. return err
  373. }
  374. // Only display response header.
  375. var respTrace []byte
  376. // For errors we make sure to dump response body as well.
  377. if resp.StatusCode != http.StatusOK &&
  378. resp.StatusCode != http.StatusPartialContent &&
  379. resp.StatusCode != http.StatusNoContent {
  380. respTrace, err = httputil.DumpResponse(resp, true)
  381. if err != nil {
  382. return err
  383. }
  384. } else {
  385. respTrace, err = httputil.DumpResponse(resp, false)
  386. if err != nil {
  387. return err
  388. }
  389. }
  390. // Write response to trace output.
  391. _, err = fmt.Fprint(c.traceOutput, strings.TrimSuffix(string(respTrace), "\r\n"))
  392. if err != nil {
  393. return err
  394. }
  395. // Ends the http dump.
  396. _, err = fmt.Fprintln(c.traceOutput, "---------END-HTTP---------")
  397. if err != nil {
  398. return err
  399. }
  400. // Returns success.
  401. return nil
  402. }
  403. // do - execute http request.
  404. func (c Client) do(req *http.Request) (*http.Response, error) {
  405. resp, err := c.httpClient.Do(req)
  406. if err != nil {
  407. // Handle this specifically for now until future Golang versions fix this issue properly.
  408. if urlErr, ok := err.(*url.Error); ok {
  409. if strings.Contains(urlErr.Err.Error(), "EOF") {
  410. return nil, &url.Error{
  411. Op: urlErr.Op,
  412. URL: urlErr.URL,
  413. Err: errors.New("Connection closed by foreign host " + urlErr.URL + ". Retry again."),
  414. }
  415. }
  416. }
  417. return nil, err
  418. }
  419. // Response cannot be non-nil, report error if thats the case.
  420. if resp == nil {
  421. msg := "Response is empty. " + reportIssue
  422. return nil, errInvalidArgument(msg)
  423. }
  424. // If trace is enabled, dump http request and response,
  425. // except when the traceErrorsOnly enabled and the response's status code is ok
  426. if c.isTraceEnabled && !(c.traceErrorsOnly && resp.StatusCode == http.StatusOK) {
  427. err = c.dumpHTTP(req, resp)
  428. if err != nil {
  429. return nil, err
  430. }
  431. }
  432. return resp, nil
  433. }
  434. // List of success status.
  435. var successStatus = []int{
  436. http.StatusOK,
  437. http.StatusNoContent,
  438. http.StatusPartialContent,
  439. }
  440. // executeMethod - instantiates a given method, and retries the
  441. // request upon any error up to maxRetries attempts in a binomially
  442. // delayed manner using a standard back off algorithm.
  443. func (c Client) executeMethod(ctx context.Context, method string, metadata requestMetadata) (res *http.Response, err error) {
  444. var retryable bool // Indicates if request can be retried.
  445. var bodySeeker io.Seeker // Extracted seeker from io.Reader.
  446. var reqRetry = MaxRetry // Indicates how many times we can retry the request
  447. if metadata.contentBody != nil {
  448. // Check if body is seekable then it is retryable.
  449. bodySeeker, retryable = metadata.contentBody.(io.Seeker)
  450. switch bodySeeker {
  451. case os.Stdin, os.Stdout, os.Stderr:
  452. retryable = false
  453. }
  454. // Retry only when reader is seekable
  455. if !retryable {
  456. reqRetry = 1
  457. }
  458. // Figure out if the body can be closed - if yes
  459. // we will definitely close it upon the function
  460. // return.
  461. bodyCloser, ok := metadata.contentBody.(io.Closer)
  462. if ok {
  463. defer bodyCloser.Close()
  464. }
  465. }
  466. // Create cancel context to control 'newRetryTimer' go routine.
  467. retryCtx, cancel := context.WithCancel(ctx)
  468. // Indicate to our routine to exit cleanly upon return.
  469. defer cancel()
  470. // Blank indentifier is kept here on purpose since 'range' without
  471. // blank identifiers is only supported since go1.4
  472. // https://golang.org/doc/go1.4#forrange.
  473. for range c.newRetryTimer(retryCtx, reqRetry, DefaultRetryUnit, DefaultRetryCap, MaxJitter) {
  474. // Retry executes the following function body if request has an
  475. // error until maxRetries have been exhausted, retry attempts are
  476. // performed after waiting for a given period of time in a
  477. // binomial fashion.
  478. if retryable {
  479. // Seek back to beginning for each attempt.
  480. if _, err = bodySeeker.Seek(0, 0); err != nil {
  481. // If seek failed, no need to retry.
  482. return nil, err
  483. }
  484. }
  485. // Instantiate a new request.
  486. var req *http.Request
  487. req, err = c.newRequest(ctx, method, metadata)
  488. if err != nil {
  489. errResponse := ToErrorResponse(err)
  490. if isS3CodeRetryable(errResponse.Code) {
  491. continue // Retry.
  492. }
  493. return nil, err
  494. }
  495. // Initiate the request.
  496. res, err = c.do(req)
  497. if err != nil {
  498. if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
  499. return nil, err
  500. }
  501. // Retry the request
  502. continue
  503. }
  504. // For any known successful http status, return quickly.
  505. for _, httpStatus := range successStatus {
  506. if httpStatus == res.StatusCode {
  507. return res, nil
  508. }
  509. }
  510. // Read the body to be saved later.
  511. errBodyBytes, err := ioutil.ReadAll(res.Body)
  512. // res.Body should be closed
  513. closeResponse(res)
  514. if err != nil {
  515. return nil, err
  516. }
  517. // Save the body.
  518. errBodySeeker := bytes.NewReader(errBodyBytes)
  519. res.Body = ioutil.NopCloser(errBodySeeker)
  520. // For errors verify if its retryable otherwise fail quickly.
  521. errResponse := ToErrorResponse(httpRespToErrorResponse(res, metadata.bucketName, metadata.objectName))
  522. // Save the body back again.
  523. errBodySeeker.Seek(0, 0) // Seek back to starting point.
  524. res.Body = ioutil.NopCloser(errBodySeeker)
  525. // Bucket region if set in error response and the error
  526. // code dictates invalid region, we can retry the request
  527. // with the new region.
  528. //
  529. // Additionally we should only retry if bucketLocation and custom
  530. // region is empty.
  531. if c.region == "" {
  532. switch errResponse.Code {
  533. case "AuthorizationHeaderMalformed":
  534. fallthrough
  535. case "InvalidRegion":
  536. fallthrough
  537. case "AccessDenied":
  538. if errResponse.Region == "" {
  539. // Region is empty we simply return the error.
  540. return res, err
  541. }
  542. // Region is not empty figure out a way to
  543. // handle this appropriately.
  544. if metadata.bucketName != "" {
  545. // Gather Cached location only if bucketName is present.
  546. if location, cachedOk := c.bucketLocCache.Get(metadata.bucketName); cachedOk && location != errResponse.Region {
  547. c.bucketLocCache.Set(metadata.bucketName, errResponse.Region)
  548. continue // Retry.
  549. }
  550. } else {
  551. // This is for ListBuckets() fallback.
  552. if errResponse.Region != metadata.bucketLocation {
  553. // Retry if the error response has a different region
  554. // than the request we just made.
  555. metadata.bucketLocation = errResponse.Region
  556. continue // Retry
  557. }
  558. }
  559. }
  560. }
  561. // Verify if error response code is retryable.
  562. if isS3CodeRetryable(errResponse.Code) {
  563. continue // Retry.
  564. }
  565. // Verify if http status code is retryable.
  566. if isHTTPStatusRetryable(res.StatusCode) {
  567. continue // Retry.
  568. }
  569. // For all other cases break out of the retry loop.
  570. break
  571. }
  572. // Return an error when retry is canceled or deadlined
  573. if e := retryCtx.Err(); e != nil {
  574. return nil, e
  575. }
  576. return res, err
  577. }
  578. // newRequest - instantiate a new HTTP request for a given method.
  579. func (c Client) newRequest(ctx context.Context, method string, metadata requestMetadata) (req *http.Request, err error) {
  580. // If no method is supplied default to 'POST'.
  581. if method == "" {
  582. method = http.MethodPost
  583. }
  584. location := metadata.bucketLocation
  585. if location == "" {
  586. if metadata.bucketName != "" {
  587. // Gather location only if bucketName is present.
  588. location, err = c.getBucketLocation(ctx, metadata.bucketName)
  589. if err != nil {
  590. return nil, err
  591. }
  592. }
  593. if location == "" {
  594. location = getDefaultLocation(*c.endpointURL, c.region)
  595. }
  596. }
  597. // Look if target url supports virtual host.
  598. // We explicitly disallow MakeBucket calls to not use virtual DNS style,
  599. // since the resolution may fail.
  600. isMakeBucket := (metadata.objectName == "" && method == http.MethodPut && len(metadata.queryValues) == 0)
  601. isVirtualHost := c.isVirtualHostStyleRequest(*c.endpointURL, metadata.bucketName) && !isMakeBucket
  602. // Construct a new target URL.
  603. targetURL, err := c.makeTargetURL(metadata.bucketName, metadata.objectName, location,
  604. isVirtualHost, metadata.queryValues)
  605. if err != nil {
  606. return nil, err
  607. }
  608. // Initialize a new HTTP request for the method.
  609. req, err = http.NewRequestWithContext(ctx, method, targetURL.String(), nil)
  610. if err != nil {
  611. return nil, err
  612. }
  613. // Get credentials from the configured credentials provider.
  614. value, err := c.credsProvider.Get()
  615. if err != nil {
  616. return nil, err
  617. }
  618. var (
  619. signerType = value.SignerType
  620. accessKeyID = value.AccessKeyID
  621. secretAccessKey = value.SecretAccessKey
  622. sessionToken = value.SessionToken
  623. )
  624. // Custom signer set then override the behavior.
  625. if c.overrideSignerType != credentials.SignatureDefault {
  626. signerType = c.overrideSignerType
  627. }
  628. // If signerType returned by credentials helper is anonymous,
  629. // then do not sign regardless of signerType override.
  630. if value.SignerType == credentials.SignatureAnonymous {
  631. signerType = credentials.SignatureAnonymous
  632. }
  633. // Generate presign url if needed, return right here.
  634. if metadata.expires != 0 && metadata.presignURL {
  635. if signerType.IsAnonymous() {
  636. return nil, errInvalidArgument("Presigned URLs cannot be generated with anonymous credentials.")
  637. }
  638. if signerType.IsV2() {
  639. // Presign URL with signature v2.
  640. req = signer.PreSignV2(*req, accessKeyID, secretAccessKey, metadata.expires, isVirtualHost)
  641. } else if signerType.IsV4() {
  642. // Presign URL with signature v4.
  643. req = signer.PreSignV4(*req, accessKeyID, secretAccessKey, sessionToken, location, metadata.expires)
  644. }
  645. return req, nil
  646. }
  647. // Set 'User-Agent' header for the request.
  648. c.setUserAgent(req)
  649. // Set all headers.
  650. for k, v := range metadata.customHeader {
  651. req.Header.Set(k, v[0])
  652. }
  653. // Go net/http notoriously closes the request body.
  654. // - The request Body, if non-nil, will be closed by the underlying Transport, even on errors.
  655. // This can cause underlying *os.File seekers to fail, avoid that
  656. // by making sure to wrap the closer as a nop.
  657. if metadata.contentLength == 0 {
  658. req.Body = nil
  659. } else {
  660. req.Body = ioutil.NopCloser(metadata.contentBody)
  661. }
  662. // Set incoming content-length.
  663. req.ContentLength = metadata.contentLength
  664. if req.ContentLength <= -1 {
  665. // For unknown content length, we upload using transfer-encoding: chunked.
  666. req.TransferEncoding = []string{"chunked"}
  667. }
  668. // set md5Sum for content protection.
  669. if len(metadata.contentMD5Base64) > 0 {
  670. req.Header.Set("Content-Md5", metadata.contentMD5Base64)
  671. }
  672. // For anonymous requests just return.
  673. if signerType.IsAnonymous() {
  674. return req, nil
  675. }
  676. switch {
  677. case signerType.IsV2():
  678. // Add signature version '2' authorization header.
  679. req = signer.SignV2(*req, accessKeyID, secretAccessKey, isVirtualHost)
  680. case metadata.objectName != "" && metadata.queryValues == nil && method == http.MethodPut && metadata.customHeader.Get("X-Amz-Copy-Source") == "" && !c.secure:
  681. // Streaming signature is used by default for a PUT object request. Additionally we also
  682. // look if the initialized client is secure, if yes then we don't need to perform
  683. // streaming signature.
  684. req = signer.StreamingSignV4(req, accessKeyID,
  685. secretAccessKey, sessionToken, location, metadata.contentLength, time.Now().UTC())
  686. default:
  687. // Set sha256 sum for signature calculation only with signature version '4'.
  688. shaHeader := unsignedPayload
  689. if metadata.contentSHA256Hex != "" {
  690. shaHeader = metadata.contentSHA256Hex
  691. }
  692. req.Header.Set("X-Amz-Content-Sha256", shaHeader)
  693. // Add signature version '4' authorization header.
  694. req = signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, location)
  695. }
  696. // Return request.
  697. return req, nil
  698. }
  699. // set User agent.
  700. func (c Client) setUserAgent(req *http.Request) {
  701. req.Header.Set("User-Agent", libraryUserAgent)
  702. if c.appInfo.appName != "" && c.appInfo.appVersion != "" {
  703. req.Header.Set("User-Agent", libraryUserAgent+" "+c.appInfo.appName+"/"+c.appInfo.appVersion)
  704. }
  705. }
  706. // makeTargetURL make a new target url.
  707. func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, isVirtualHostStyle bool, queryValues url.Values) (*url.URL, error) {
  708. host := c.endpointURL.Host
  709. // For Amazon S3 endpoint, try to fetch location based endpoint.
  710. if s3utils.IsAmazonEndpoint(*c.endpointURL) {
  711. if c.s3AccelerateEndpoint != "" && bucketName != "" {
  712. // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html
  713. // Disable transfer acceleration for non-compliant bucket names.
  714. if strings.Contains(bucketName, ".") {
  715. return nil, errTransferAccelerationBucket(bucketName)
  716. }
  717. // If transfer acceleration is requested set new host.
  718. // For more details about enabling transfer acceleration read here.
  719. // http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html
  720. host = c.s3AccelerateEndpoint
  721. } else {
  722. // Do not change the host if the endpoint URL is a FIPS S3 endpoint.
  723. if !s3utils.IsAmazonFIPSEndpoint(*c.endpointURL) {
  724. // Fetch new host based on the bucket location.
  725. host = getS3Endpoint(bucketLocation)
  726. }
  727. }
  728. }
  729. // Save scheme.
  730. scheme := c.endpointURL.Scheme
  731. // Strip port 80 and 443 so we won't send these ports in Host header.
  732. // The reason is that browsers and curl automatically remove :80 and :443
  733. // with the generated presigned urls, then a signature mismatch error.
  734. if h, p, err := net.SplitHostPort(host); err == nil {
  735. if scheme == "http" && p == "80" || scheme == "https" && p == "443" {
  736. host = h
  737. }
  738. }
  739. urlStr := scheme + "://" + host + "/"
  740. // Make URL only if bucketName is available, otherwise use the
  741. // endpoint URL.
  742. if bucketName != "" {
  743. // If endpoint supports virtual host style use that always.
  744. // Currently only S3 and Google Cloud Storage would support
  745. // virtual host style.
  746. if isVirtualHostStyle {
  747. urlStr = scheme + "://" + bucketName + "." + host + "/"
  748. if objectName != "" {
  749. urlStr = urlStr + s3utils.EncodePath(objectName)
  750. }
  751. } else {
  752. // If not fall back to using path style.
  753. urlStr = urlStr + bucketName + "/"
  754. if objectName != "" {
  755. urlStr = urlStr + s3utils.EncodePath(objectName)
  756. }
  757. }
  758. }
  759. // If there are any query values, add them to the end.
  760. if len(queryValues) > 0 {
  761. urlStr = urlStr + "?" + s3utils.QueryEncode(queryValues)
  762. }
  763. return url.Parse(urlStr)
  764. }
  765. // returns true if virtual hosted style requests are to be used.
  766. func (c *Client) isVirtualHostStyleRequest(url url.URL, bucketName string) bool {
  767. if bucketName == "" {
  768. return false
  769. }
  770. if c.lookup == BucketLookupDNS {
  771. return true
  772. }
  773. if c.lookup == BucketLookupPath {
  774. return false
  775. }
  776. // default to virtual only for Amazon/Google storage. In all other cases use
  777. // path style requests
  778. return s3utils.IsVirtualHostSupported(url, bucketName)
  779. }