request.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package request
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "reflect"
  10. "strings"
  11. "time"
  12. "github.com/aws/aws-sdk-go/aws"
  13. "github.com/aws/aws-sdk-go/aws/awserr"
  14. "github.com/aws/aws-sdk-go/aws/client/metadata"
  15. "github.com/aws/aws-sdk-go/internal/sdkio"
  16. )
  17. const (
  18. // ErrCodeSerialization is the serialization error code that is received
  19. // during protocol unmarshaling.
  20. ErrCodeSerialization = "SerializationError"
  21. // ErrCodeRead is an error that is returned during HTTP reads.
  22. ErrCodeRead = "ReadError"
  23. // ErrCodeResponseTimeout is the connection timeout error that is received
  24. // during body reads.
  25. ErrCodeResponseTimeout = "ResponseTimeout"
  26. // ErrCodeInvalidPresignExpire is returned when the expire time provided to
  27. // presign is invalid
  28. ErrCodeInvalidPresignExpire = "InvalidPresignExpireError"
  29. // CanceledErrorCode is the error code that will be returned by an
  30. // API request that was canceled. Requests given a aws.Context may
  31. // return this error when canceled.
  32. CanceledErrorCode = "RequestCanceled"
  33. )
  34. // A Request is the service request to be made.
  35. type Request struct {
  36. Config aws.Config
  37. ClientInfo metadata.ClientInfo
  38. Handlers Handlers
  39. Retryer
  40. AttemptTime time.Time
  41. Time time.Time
  42. Operation *Operation
  43. HTTPRequest *http.Request
  44. HTTPResponse *http.Response
  45. Body io.ReadSeeker
  46. BodyStart int64 // offset from beginning of Body that the request body starts
  47. Params interface{}
  48. Error error
  49. Data interface{}
  50. RequestID string
  51. RetryCount int
  52. Retryable *bool
  53. RetryDelay time.Duration
  54. NotHoist bool
  55. SignedHeaderVals http.Header
  56. LastSignedAt time.Time
  57. DisableFollowRedirects bool
  58. // A value greater than 0 instructs the request to be signed as Presigned URL
  59. // You should not set this field directly. Instead use Request's
  60. // Presign or PresignRequest methods.
  61. ExpireTime time.Duration
  62. context aws.Context
  63. built bool
  64. // Need to persist an intermediate body between the input Body and HTTP
  65. // request body because the HTTP Client's transport can maintain a reference
  66. // to the HTTP request's body after the client has returned. This value is
  67. // safe to use concurrently and wrap the input Body for each HTTP request.
  68. safeBody *offsetReader
  69. }
  70. // An Operation is the service API operation to be made.
  71. type Operation struct {
  72. Name string
  73. HTTPMethod string
  74. HTTPPath string
  75. *Paginator
  76. BeforePresignFn func(r *Request) error
  77. }
  78. // New returns a new Request pointer for the service API
  79. // operation and parameters.
  80. //
  81. // Params is any value of input parameters to be the request payload.
  82. // Data is pointer value to an object which the request's response
  83. // payload will be deserialized to.
  84. func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers,
  85. retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request {
  86. method := operation.HTTPMethod
  87. if method == "" {
  88. method = "POST"
  89. }
  90. httpReq, _ := http.NewRequest(method, "", nil)
  91. var err error
  92. httpReq.URL, err = url.Parse(clientInfo.Endpoint + operation.HTTPPath)
  93. if err != nil {
  94. httpReq.URL = &url.URL{}
  95. err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err)
  96. }
  97. SanitizeHostForHeader(httpReq)
  98. r := &Request{
  99. Config: cfg,
  100. ClientInfo: clientInfo,
  101. Handlers: handlers.Copy(),
  102. Retryer: retryer,
  103. AttemptTime: time.Now(),
  104. Time: time.Now(),
  105. ExpireTime: 0,
  106. Operation: operation,
  107. HTTPRequest: httpReq,
  108. Body: nil,
  109. Params: params,
  110. Error: err,
  111. Data: data,
  112. }
  113. r.SetBufferBody([]byte{})
  114. return r
  115. }
  116. // A Option is a functional option that can augment or modify a request when
  117. // using a WithContext API operation method.
  118. type Option func(*Request)
  119. // WithGetResponseHeader builds a request Option which will retrieve a single
  120. // header value from the HTTP Response. If there are multiple values for the
  121. // header key use WithGetResponseHeaders instead to access the http.Header
  122. // map directly. The passed in val pointer must be non-nil.
  123. //
  124. // This Option can be used multiple times with a single API operation.
  125. //
  126. // var id2, versionID string
  127. // svc.PutObjectWithContext(ctx, params,
  128. // request.WithGetResponseHeader("x-amz-id-2", &id2),
  129. // request.WithGetResponseHeader("x-amz-version-id", &versionID),
  130. // )
  131. func WithGetResponseHeader(key string, val *string) Option {
  132. return func(r *Request) {
  133. r.Handlers.Complete.PushBack(func(req *Request) {
  134. *val = req.HTTPResponse.Header.Get(key)
  135. })
  136. }
  137. }
  138. // WithGetResponseHeaders builds a request Option which will retrieve the
  139. // headers from the HTTP response and assign them to the passed in headers
  140. // variable. The passed in headers pointer must be non-nil.
  141. //
  142. // var headers http.Header
  143. // svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers))
  144. func WithGetResponseHeaders(headers *http.Header) Option {
  145. return func(r *Request) {
  146. r.Handlers.Complete.PushBack(func(req *Request) {
  147. *headers = req.HTTPResponse.Header
  148. })
  149. }
  150. }
  151. // WithLogLevel is a request option that will set the request to use a specific
  152. // log level when the request is made.
  153. //
  154. // svc.PutObjectWithContext(ctx, params, request.WithLogLevel(aws.LogDebugWithHTTPBody)
  155. func WithLogLevel(l aws.LogLevelType) Option {
  156. return func(r *Request) {
  157. r.Config.LogLevel = aws.LogLevel(l)
  158. }
  159. }
  160. // ApplyOptions will apply each option to the request calling them in the order
  161. // the were provided.
  162. func (r *Request) ApplyOptions(opts ...Option) {
  163. for _, opt := range opts {
  164. opt(r)
  165. }
  166. }
  167. // Context will always returns a non-nil context. If Request does not have a
  168. // context aws.BackgroundContext will be returned.
  169. func (r *Request) Context() aws.Context {
  170. if r.context != nil {
  171. return r.context
  172. }
  173. return aws.BackgroundContext()
  174. }
  175. // SetContext adds a Context to the current request that can be used to cancel
  176. // a in-flight request. The Context value must not be nil, or this method will
  177. // panic.
  178. //
  179. // Unlike http.Request.WithContext, SetContext does not return a copy of the
  180. // Request. It is not safe to use use a single Request value for multiple
  181. // requests. A new Request should be created for each API operation request.
  182. //
  183. // Go 1.6 and below:
  184. // The http.Request's Cancel field will be set to the Done() value of
  185. // the context. This will overwrite the Cancel field's value.
  186. //
  187. // Go 1.7 and above:
  188. // The http.Request.WithContext will be used to set the context on the underlying
  189. // http.Request. This will create a shallow copy of the http.Request. The SDK
  190. // may create sub contexts in the future for nested requests such as retries.
  191. func (r *Request) SetContext(ctx aws.Context) {
  192. if ctx == nil {
  193. panic("context cannot be nil")
  194. }
  195. setRequestContext(r, ctx)
  196. }
  197. // WillRetry returns if the request's can be retried.
  198. func (r *Request) WillRetry() bool {
  199. if !aws.IsReaderSeekable(r.Body) && r.HTTPRequest.Body != NoBody {
  200. return false
  201. }
  202. return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries()
  203. }
  204. // ParamsFilled returns if the request's parameters have been populated
  205. // and the parameters are valid. False is returned if no parameters are
  206. // provided or invalid.
  207. func (r *Request) ParamsFilled() bool {
  208. return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid()
  209. }
  210. // DataFilled returns true if the request's data for response deserialization
  211. // target has been set and is a valid. False is returned if data is not
  212. // set, or is invalid.
  213. func (r *Request) DataFilled() bool {
  214. return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid()
  215. }
  216. // SetBufferBody will set the request's body bytes that will be sent to
  217. // the service API.
  218. func (r *Request) SetBufferBody(buf []byte) {
  219. r.SetReaderBody(bytes.NewReader(buf))
  220. }
  221. // SetStringBody sets the body of the request to be backed by a string.
  222. func (r *Request) SetStringBody(s string) {
  223. r.SetReaderBody(strings.NewReader(s))
  224. }
  225. // SetReaderBody will set the request's body reader.
  226. func (r *Request) SetReaderBody(reader io.ReadSeeker) {
  227. r.Body = reader
  228. r.BodyStart, _ = reader.Seek(0, sdkio.SeekCurrent) // Get the Bodies current offset.
  229. r.ResetBody()
  230. }
  231. // Presign returns the request's signed URL. Error will be returned
  232. // if the signing fails.
  233. //
  234. // It is invalid to create a presigned URL with a expire duration 0 or less. An
  235. // error is returned if expire duration is 0 or less.
  236. func (r *Request) Presign(expire time.Duration) (string, error) {
  237. r = r.copy()
  238. // Presign requires all headers be hoisted. There is no way to retrieve
  239. // the signed headers not hoisted without this. Making the presigned URL
  240. // useless.
  241. r.NotHoist = false
  242. u, _, err := getPresignedURL(r, expire)
  243. return u, err
  244. }
  245. // PresignRequest behaves just like presign, with the addition of returning a
  246. // set of headers that were signed.
  247. //
  248. // It is invalid to create a presigned URL with a expire duration 0 or less. An
  249. // error is returned if expire duration is 0 or less.
  250. //
  251. // Returns the URL string for the API operation with signature in the query string,
  252. // and the HTTP headers that were included in the signature. These headers must
  253. // be included in any HTTP request made with the presigned URL.
  254. //
  255. // To prevent hoisting any headers to the query string set NotHoist to true on
  256. // this Request value prior to calling PresignRequest.
  257. func (r *Request) PresignRequest(expire time.Duration) (string, http.Header, error) {
  258. r = r.copy()
  259. return getPresignedURL(r, expire)
  260. }
  261. // IsPresigned returns true if the request represents a presigned API url.
  262. func (r *Request) IsPresigned() bool {
  263. return r.ExpireTime != 0
  264. }
  265. func getPresignedURL(r *Request, expire time.Duration) (string, http.Header, error) {
  266. if expire <= 0 {
  267. return "", nil, awserr.New(
  268. ErrCodeInvalidPresignExpire,
  269. "presigned URL requires an expire duration greater than 0",
  270. nil,
  271. )
  272. }
  273. r.ExpireTime = expire
  274. if r.Operation.BeforePresignFn != nil {
  275. if err := r.Operation.BeforePresignFn(r); err != nil {
  276. return "", nil, err
  277. }
  278. }
  279. if err := r.Sign(); err != nil {
  280. return "", nil, err
  281. }
  282. return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil
  283. }
  284. func debugLogReqError(r *Request, stage string, retrying bool, err error) {
  285. if !r.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) {
  286. return
  287. }
  288. retryStr := "not retrying"
  289. if retrying {
  290. retryStr = "will retry"
  291. }
  292. r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v",
  293. stage, r.ClientInfo.ServiceName, r.Operation.Name, retryStr, err))
  294. }
  295. // Build will build the request's object so it can be signed and sent
  296. // to the service. Build will also validate all the request's parameters.
  297. // Any additional build Handlers set on this request will be run
  298. // in the order they were set.
  299. //
  300. // The request will only be built once. Multiple calls to build will have
  301. // no effect.
  302. //
  303. // If any Validate or Build errors occur the build will stop and the error
  304. // which occurred will be returned.
  305. func (r *Request) Build() error {
  306. if !r.built {
  307. r.Handlers.Validate.Run(r)
  308. if r.Error != nil {
  309. debugLogReqError(r, "Validate Request", false, r.Error)
  310. return r.Error
  311. }
  312. r.Handlers.Build.Run(r)
  313. if r.Error != nil {
  314. debugLogReqError(r, "Build Request", false, r.Error)
  315. return r.Error
  316. }
  317. r.built = true
  318. }
  319. return r.Error
  320. }
  321. // Sign will sign the request, returning error if errors are encountered.
  322. //
  323. // Sign will build the request prior to signing. All Sign Handlers will
  324. // be executed in the order they were set.
  325. func (r *Request) Sign() error {
  326. r.Build()
  327. if r.Error != nil {
  328. debugLogReqError(r, "Build Request", false, r.Error)
  329. return r.Error
  330. }
  331. r.Handlers.Sign.Run(r)
  332. return r.Error
  333. }
  334. func (r *Request) getNextRequestBody() (io.ReadCloser, error) {
  335. if r.safeBody != nil {
  336. r.safeBody.Close()
  337. }
  338. r.safeBody = newOffsetReader(r.Body, r.BodyStart)
  339. // Go 1.8 tightened and clarified the rules code needs to use when building
  340. // requests with the http package. Go 1.8 removed the automatic detection
  341. // of if the Request.Body was empty, or actually had bytes in it. The SDK
  342. // always sets the Request.Body even if it is empty and should not actually
  343. // be sent. This is incorrect.
  344. //
  345. // Go 1.8 did add a http.NoBody value that the SDK can use to tell the http
  346. // client that the request really should be sent without a body. The
  347. // Request.Body cannot be set to nil, which is preferable, because the
  348. // field is exported and could introduce nil pointer dereferences for users
  349. // of the SDK if they used that field.
  350. //
  351. // Related golang/go#18257
  352. l, err := aws.SeekerLen(r.Body)
  353. if err != nil {
  354. return nil, awserr.New(ErrCodeSerialization, "failed to compute request body size", err)
  355. }
  356. var body io.ReadCloser
  357. if l == 0 {
  358. body = NoBody
  359. } else if l > 0 {
  360. body = r.safeBody
  361. } else {
  362. // Hack to prevent sending bodies for methods where the body
  363. // should be ignored by the server. Sending bodies on these
  364. // methods without an associated ContentLength will cause the
  365. // request to socket timeout because the server does not handle
  366. // Transfer-Encoding: chunked bodies for these methods.
  367. //
  368. // This would only happen if a aws.ReaderSeekerCloser was used with
  369. // a io.Reader that was not also an io.Seeker, or did not implement
  370. // Len() method.
  371. switch r.Operation.HTTPMethod {
  372. case "GET", "HEAD", "DELETE":
  373. body = NoBody
  374. default:
  375. body = r.safeBody
  376. }
  377. }
  378. return body, nil
  379. }
  380. // GetBody will return an io.ReadSeeker of the Request's underlying
  381. // input body with a concurrency safe wrapper.
  382. func (r *Request) GetBody() io.ReadSeeker {
  383. return r.safeBody
  384. }
  385. // Send will send the request, returning error if errors are encountered.
  386. //
  387. // Send will sign the request prior to sending. All Send Handlers will
  388. // be executed in the order they were set.
  389. //
  390. // Canceling a request is non-deterministic. If a request has been canceled,
  391. // then the transport will choose, randomly, one of the state channels during
  392. // reads or getting the connection.
  393. //
  394. // readLoop() and getConn(req *Request, cm connectMethod)
  395. // https://github.com/golang/go/blob/master/src/net/http/transport.go
  396. //
  397. // Send will not close the request.Request's body.
  398. func (r *Request) Send() error {
  399. defer func() {
  400. // Regardless of success or failure of the request trigger the Complete
  401. // request handlers.
  402. r.Handlers.Complete.Run(r)
  403. }()
  404. for {
  405. r.AttemptTime = time.Now()
  406. if aws.BoolValue(r.Retryable) {
  407. if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) {
  408. r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d",
  409. r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount))
  410. }
  411. // The previous http.Request will have a reference to the r.Body
  412. // and the HTTP Client's Transport may still be reading from
  413. // the request's body even though the Client's Do returned.
  414. r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil)
  415. r.ResetBody()
  416. // Closing response body to ensure that no response body is leaked
  417. // between retry attempts.
  418. if r.HTTPResponse != nil && r.HTTPResponse.Body != nil {
  419. r.HTTPResponse.Body.Close()
  420. }
  421. }
  422. r.Sign()
  423. if r.Error != nil {
  424. return r.Error
  425. }
  426. r.Retryable = nil
  427. r.Handlers.Send.Run(r)
  428. if r.Error != nil {
  429. if !shouldRetryCancel(r) {
  430. return r.Error
  431. }
  432. err := r.Error
  433. r.Handlers.Retry.Run(r)
  434. r.Handlers.AfterRetry.Run(r)
  435. if r.Error != nil {
  436. debugLogReqError(r, "Send Request", false, err)
  437. return r.Error
  438. }
  439. debugLogReqError(r, "Send Request", true, err)
  440. continue
  441. }
  442. r.Handlers.UnmarshalMeta.Run(r)
  443. r.Handlers.ValidateResponse.Run(r)
  444. if r.Error != nil {
  445. r.Handlers.UnmarshalError.Run(r)
  446. err := r.Error
  447. r.Handlers.Retry.Run(r)
  448. r.Handlers.AfterRetry.Run(r)
  449. if r.Error != nil {
  450. debugLogReqError(r, "Validate Response", false, err)
  451. return r.Error
  452. }
  453. debugLogReqError(r, "Validate Response", true, err)
  454. continue
  455. }
  456. r.Handlers.Unmarshal.Run(r)
  457. if r.Error != nil {
  458. err := r.Error
  459. r.Handlers.Retry.Run(r)
  460. r.Handlers.AfterRetry.Run(r)
  461. if r.Error != nil {
  462. debugLogReqError(r, "Unmarshal Response", false, err)
  463. return r.Error
  464. }
  465. debugLogReqError(r, "Unmarshal Response", true, err)
  466. continue
  467. }
  468. break
  469. }
  470. return nil
  471. }
  472. // copy will copy a request which will allow for local manipulation of the
  473. // request.
  474. func (r *Request) copy() *Request {
  475. req := &Request{}
  476. *req = *r
  477. req.Handlers = r.Handlers.Copy()
  478. op := *r.Operation
  479. req.Operation = &op
  480. return req
  481. }
  482. // AddToUserAgent adds the string to the end of the request's current user agent.
  483. func AddToUserAgent(r *Request, s string) {
  484. curUA := r.HTTPRequest.Header.Get("User-Agent")
  485. if len(curUA) > 0 {
  486. s = curUA + " " + s
  487. }
  488. r.HTTPRequest.Header.Set("User-Agent", s)
  489. }
  490. func shouldRetryCancel(r *Request) bool {
  491. awsErr, ok := r.Error.(awserr.Error)
  492. timeoutErr := false
  493. errStr := r.Error.Error()
  494. if ok {
  495. if awsErr.Code() == CanceledErrorCode {
  496. return false
  497. }
  498. err := awsErr.OrigErr()
  499. netErr, netOK := err.(net.Error)
  500. timeoutErr = netOK && netErr.Temporary()
  501. if urlErr, ok := err.(*url.Error); !timeoutErr && ok {
  502. errStr = urlErr.Err.Error()
  503. }
  504. }
  505. // There can be two types of canceled errors here.
  506. // The first being a net.Error and the other being an error.
  507. // If the request was timed out, we want to continue the retry
  508. // process. Otherwise, return the canceled error.
  509. return timeoutErr ||
  510. (errStr != "net/http: request canceled" &&
  511. errStr != "net/http: request canceled while waiting for connection")
  512. }
  513. // SanitizeHostForHeader removes default port from host and updates request.Host
  514. func SanitizeHostForHeader(r *http.Request) {
  515. host := getHost(r)
  516. port := portOnly(host)
  517. if port != "" && isDefaultPort(r.URL.Scheme, port) {
  518. r.Host = stripPort(host)
  519. }
  520. }
  521. // Returns host from request
  522. func getHost(r *http.Request) string {
  523. if r.Host != "" {
  524. return r.Host
  525. }
  526. return r.URL.Host
  527. }
  528. // Hostname returns u.Host, without any port number.
  529. //
  530. // If Host is an IPv6 literal with a port number, Hostname returns the
  531. // IPv6 literal without the square brackets. IPv6 literals may include
  532. // a zone identifier.
  533. //
  534. // Copied from the Go 1.8 standard library (net/url)
  535. func stripPort(hostport string) string {
  536. colon := strings.IndexByte(hostport, ':')
  537. if colon == -1 {
  538. return hostport
  539. }
  540. if i := strings.IndexByte(hostport, ']'); i != -1 {
  541. return strings.TrimPrefix(hostport[:i], "[")
  542. }
  543. return hostport[:colon]
  544. }
  545. // Port returns the port part of u.Host, without the leading colon.
  546. // If u.Host doesn't contain a port, Port returns an empty string.
  547. //
  548. // Copied from the Go 1.8 standard library (net/url)
  549. func portOnly(hostport string) string {
  550. colon := strings.IndexByte(hostport, ':')
  551. if colon == -1 {
  552. return ""
  553. }
  554. if i := strings.Index(hostport, "]:"); i != -1 {
  555. return hostport[i+len("]:"):]
  556. }
  557. if strings.Contains(hostport, "]") {
  558. return ""
  559. }
  560. return hostport[colon+len(":"):]
  561. }
  562. // Returns true if the specified URI is using the standard port
  563. // (i.e. port 80 for HTTP URIs or 443 for HTTPS URIs)
  564. func isDefaultPort(scheme, port string) bool {
  565. if port == "" {
  566. return true
  567. }
  568. lowerCaseScheme := strings.ToLower(scheme)
  569. if (lowerCaseScheme == "http" && port == "80") || (lowerCaseScheme == "https" && port == "443") {
  570. return true
  571. }
  572. return false
  573. }