request.go 19 KB

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