http.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package acme
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto"
  9. "crypto/rand"
  10. "encoding/json"
  11. "fmt"
  12. "io/ioutil"
  13. "math/big"
  14. "net/http"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. // retryTimer encapsulates common logic for retrying unsuccessful requests.
  20. // It is not safe for concurrent use.
  21. type retryTimer struct {
  22. // backoffFn provides backoff delay sequence for retries.
  23. // See Client.RetryBackoff doc comment.
  24. backoffFn func(n int, r *http.Request, res *http.Response) time.Duration
  25. // n is the current retry attempt.
  26. n int
  27. }
  28. func (t *retryTimer) inc() {
  29. t.n++
  30. }
  31. // backoff pauses the current goroutine as described in Client.RetryBackoff.
  32. func (t *retryTimer) backoff(ctx context.Context, r *http.Request, res *http.Response) error {
  33. d := t.backoffFn(t.n, r, res)
  34. if d <= 0 {
  35. return fmt.Errorf("acme: no more retries for %s; tried %d time(s)", r.URL, t.n)
  36. }
  37. wakeup := time.NewTimer(d)
  38. defer wakeup.Stop()
  39. select {
  40. case <-ctx.Done():
  41. return ctx.Err()
  42. case <-wakeup.C:
  43. return nil
  44. }
  45. }
  46. func (c *Client) retryTimer() *retryTimer {
  47. f := c.RetryBackoff
  48. if f == nil {
  49. f = defaultBackoff
  50. }
  51. return &retryTimer{backoffFn: f}
  52. }
  53. // defaultBackoff provides default Client.RetryBackoff implementation
  54. // using a truncated exponential backoff algorithm,
  55. // as described in Client.RetryBackoff.
  56. //
  57. // The n argument is always bounded between 1 and 30.
  58. // The returned value is always greater than 0.
  59. func defaultBackoff(n int, r *http.Request, res *http.Response) time.Duration {
  60. const max = 10 * time.Second
  61. var jitter time.Duration
  62. if x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil {
  63. // Set the minimum to 1ms to avoid a case where
  64. // an invalid Retry-After value is parsed into 0 below,
  65. // resulting in the 0 returned value which would unintentionally
  66. // stop the retries.
  67. jitter = (1 + time.Duration(x.Int64())) * time.Millisecond
  68. }
  69. if v, ok := res.Header["Retry-After"]; ok {
  70. return retryAfter(v[0]) + jitter
  71. }
  72. if n < 1 {
  73. n = 1
  74. }
  75. if n > 30 {
  76. n = 30
  77. }
  78. d := time.Duration(1<<uint(n-1))*time.Second + jitter
  79. if d > max {
  80. return max
  81. }
  82. return d
  83. }
  84. // retryAfter parses a Retry-After HTTP header value,
  85. // trying to convert v into an int (seconds) or use http.ParseTime otherwise.
  86. // It returns zero value if v cannot be parsed.
  87. func retryAfter(v string) time.Duration {
  88. if i, err := strconv.Atoi(v); err == nil {
  89. return time.Duration(i) * time.Second
  90. }
  91. t, err := http.ParseTime(v)
  92. if err != nil {
  93. return 0
  94. }
  95. return t.Sub(timeNow())
  96. }
  97. // resOkay is a function that reports whether the provided response is okay.
  98. // It is expected to keep the response body unread.
  99. type resOkay func(*http.Response) bool
  100. // wantStatus returns a function which reports whether the code
  101. // matches the status code of a response.
  102. func wantStatus(codes ...int) resOkay {
  103. return func(res *http.Response) bool {
  104. for _, code := range codes {
  105. if code == res.StatusCode {
  106. return true
  107. }
  108. }
  109. return false
  110. }
  111. }
  112. // get issues an unsigned GET request to the specified URL.
  113. // It returns a non-error value only when ok reports true.
  114. //
  115. // get retries unsuccessful attempts according to c.RetryBackoff
  116. // until the context is done or a non-retriable error is received.
  117. func (c *Client) get(ctx context.Context, url string, ok resOkay) (*http.Response, error) {
  118. retry := c.retryTimer()
  119. for {
  120. req, err := http.NewRequest("GET", url, nil)
  121. if err != nil {
  122. return nil, err
  123. }
  124. res, err := c.doNoRetry(ctx, req)
  125. switch {
  126. case err != nil:
  127. return nil, err
  128. case ok(res):
  129. return res, nil
  130. case isRetriable(res.StatusCode):
  131. res.Body.Close()
  132. retry.inc()
  133. if err := retry.backoff(ctx, req, res); err != nil {
  134. return nil, err
  135. }
  136. default:
  137. defer res.Body.Close()
  138. return nil, responseError(res)
  139. }
  140. }
  141. }
  142. // post issues a signed POST request in JWS format using the provided key
  143. // to the specified URL.
  144. // It returns a non-error value only when ok reports true.
  145. //
  146. // post retries unsuccessful attempts according to c.RetryBackoff
  147. // until the context is done or a non-retriable error is received.
  148. // It uses postNoRetry to make individual requests.
  149. func (c *Client) post(ctx context.Context, key crypto.Signer, url string, body interface{}, ok resOkay) (*http.Response, error) {
  150. retry := c.retryTimer()
  151. for {
  152. res, req, err := c.postNoRetry(ctx, key, url, body)
  153. if err != nil {
  154. return nil, err
  155. }
  156. if ok(res) {
  157. return res, nil
  158. }
  159. err = responseError(res)
  160. res.Body.Close()
  161. switch {
  162. // Check for bad nonce before isRetriable because it may have been returned
  163. // with an unretriable response code such as 400 Bad Request.
  164. case isBadNonce(err):
  165. // Consider any previously stored nonce values to be invalid.
  166. c.clearNonces()
  167. case !isRetriable(res.StatusCode):
  168. return nil, err
  169. }
  170. retry.inc()
  171. if err := retry.backoff(ctx, req, res); err != nil {
  172. return nil, err
  173. }
  174. }
  175. }
  176. // postNoRetry signs the body with the given key and POSTs it to the provided url.
  177. // The body argument must be JSON-serializable.
  178. // It is used by c.post to retry unsuccessful attempts.
  179. func (c *Client) postNoRetry(ctx context.Context, key crypto.Signer, url string, body interface{}) (*http.Response, *http.Request, error) {
  180. nonce, err := c.popNonce(ctx, url)
  181. if err != nil {
  182. return nil, nil, err
  183. }
  184. b, err := jwsEncodeJSON(body, key, nonce)
  185. if err != nil {
  186. return nil, nil, err
  187. }
  188. req, err := http.NewRequest("POST", url, bytes.NewReader(b))
  189. if err != nil {
  190. return nil, nil, err
  191. }
  192. req.Header.Set("Content-Type", "application/jose+json")
  193. res, err := c.doNoRetry(ctx, req)
  194. if err != nil {
  195. return nil, nil, err
  196. }
  197. c.addNonce(res.Header)
  198. return res, req, nil
  199. }
  200. // doNoRetry issues a request req, replacing its context (if any) with ctx.
  201. func (c *Client) doNoRetry(ctx context.Context, req *http.Request) (*http.Response, error) {
  202. res, err := c.httpClient().Do(req.WithContext(ctx))
  203. if err != nil {
  204. select {
  205. case <-ctx.Done():
  206. // Prefer the unadorned context error.
  207. // (The acme package had tests assuming this, previously from ctxhttp's
  208. // behavior, predating net/http supporting contexts natively)
  209. // TODO(bradfitz): reconsider this in the future. But for now this
  210. // requires no test updates.
  211. return nil, ctx.Err()
  212. default:
  213. return nil, err
  214. }
  215. }
  216. return res, nil
  217. }
  218. func (c *Client) httpClient() *http.Client {
  219. if c.HTTPClient != nil {
  220. return c.HTTPClient
  221. }
  222. return http.DefaultClient
  223. }
  224. // isBadNonce reports whether err is an ACME "badnonce" error.
  225. func isBadNonce(err error) bool {
  226. // According to the spec badNonce is urn:ietf:params:acme:error:badNonce.
  227. // However, ACME servers in the wild return their versions of the error.
  228. // See https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-5.4
  229. // and https://github.com/letsencrypt/boulder/blob/0e07eacb/docs/acme-divergences.md#section-66.
  230. ae, ok := err.(*Error)
  231. return ok && strings.HasSuffix(strings.ToLower(ae.ProblemType), ":badnonce")
  232. }
  233. // isRetriable reports whether a request can be retried
  234. // based on the response status code.
  235. //
  236. // Note that a "bad nonce" error is returned with a non-retriable 400 Bad Request code.
  237. // Callers should parse the response and check with isBadNonce.
  238. func isRetriable(code int) bool {
  239. return code <= 399 || code >= 500 || code == http.StatusTooManyRequests
  240. }
  241. // responseError creates an error of Error type from resp.
  242. func responseError(resp *http.Response) error {
  243. // don't care if ReadAll returns an error:
  244. // json.Unmarshal will fail in that case anyway
  245. b, _ := ioutil.ReadAll(resp.Body)
  246. e := &wireError{Status: resp.StatusCode}
  247. if err := json.Unmarshal(b, e); err != nil {
  248. // this is not a regular error response:
  249. // populate detail with anything we received,
  250. // e.Status will already contain HTTP response code value
  251. e.Detail = string(b)
  252. if e.Detail == "" {
  253. e.Detail = resp.Status
  254. }
  255. }
  256. return e.error(resp.Header)
  257. }