http-client.scm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
  4. ;;; Copyright © 2012, 2015 Free Software Foundation, Inc.
  5. ;;; Copyright © 2017 Tobias Geerinckx-Rice <me@tobias.gr>
  6. ;;;
  7. ;;; This file is part of GNU Guix.
  8. ;;;
  9. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  10. ;;; under the terms of the GNU General Public License as published by
  11. ;;; the Free Software Foundation; either version 3 of the License, or (at
  12. ;;; your option) any later version.
  13. ;;;
  14. ;;; GNU Guix is distributed in the hope that it will be useful, but
  15. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;;; GNU General Public License for more details.
  18. ;;;
  19. ;;; You should have received a copy of the GNU General Public License
  20. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  21. (define-module (guix http-client)
  22. #:use-module (web uri)
  23. #:use-module (web http)
  24. #:use-module ((web client) #:hide (open-socket-for-uri))
  25. #:use-module (web request)
  26. #:use-module (web response)
  27. #:use-module (srfi srfi-1)
  28. #:use-module (srfi srfi-11)
  29. #:use-module (srfi srfi-19)
  30. #:use-module (srfi srfi-26)
  31. #:use-module (srfi srfi-34)
  32. #:use-module (srfi srfi-35)
  33. #:use-module (ice-9 match)
  34. #:use-module (ice-9 binary-ports)
  35. #:use-module (rnrs bytevectors)
  36. #:use-module (guix ui)
  37. #:use-module (guix utils)
  38. #:use-module (guix base64)
  39. #:autoload (gcrypt hash) (sha256)
  40. #:autoload (gnutls) (error/invalid-session)
  41. #:use-module ((guix build utils)
  42. #:select (mkdir-p dump-port))
  43. #:use-module ((guix build download)
  44. #:select (open-socket-for-uri
  45. (open-connection-for-uri
  46. . guix:open-connection-for-uri)
  47. resolve-uri-reference))
  48. #:re-export (open-socket-for-uri)
  49. #:export (&http-get-error
  50. http-get-error?
  51. http-get-error-uri
  52. http-get-error-code
  53. http-get-error-reason
  54. http-fetch
  55. http-multiple-get
  56. %http-cache-ttl
  57. http-fetch/cached))
  58. ;;; Commentary:
  59. ;;;
  60. ;;; HTTP client portable among Guile versions, and with proper error condition
  61. ;;; reporting.
  62. ;;;
  63. ;;; Code:
  64. ;; HTTP GET error.
  65. (define-condition-type &http-get-error &error
  66. http-get-error?
  67. (uri http-get-error-uri) ; URI
  68. (code http-get-error-code) ; integer
  69. (reason http-get-error-reason)) ; string
  70. (define* (http-fetch uri #:key port (text? #f) (buffered? #t)
  71. (open-connection guix:open-connection-for-uri)
  72. (keep-alive? #f)
  73. (verify-certificate? #t)
  74. (headers '((user-agent . "GNU Guile")))
  75. (log-port (current-error-port))
  76. timeout)
  77. "Return an input port containing the data at URI, and the expected number of
  78. bytes available or #f. If TEXT? is true, the data at URI is considered to be
  79. textual. Follow any HTTP redirection. When BUFFERED? is #f, return an
  80. unbuffered port, suitable for use in `filtered-port'. HEADERS is an alist of
  81. extra HTTP headers.
  82. When KEEP-ALIVE? is true, the connection is marked as 'keep-alive' and PORT is
  83. not closed upon completion.
  84. When VERIFY-CERTIFICATE? is true, verify HTTPS server certificates.
  85. TIMEOUT specifies the timeout in seconds for connection establishment; when
  86. TIMEOUT is #f, connection establishment never times out.
  87. Write information about redirects to LOG-PORT.
  88. Raise an '&http-get-error' condition if downloading fails."
  89. (let loop ((uri (if (string? uri)
  90. (string->uri uri)
  91. uri)))
  92. (let ((port (or port (open-connection uri
  93. #:verify-certificate?
  94. verify-certificate?
  95. #:timeout timeout)))
  96. (headers (match (uri-userinfo uri)
  97. ((? string? str)
  98. (cons (cons 'Authorization
  99. (string-append "Basic "
  100. (base64-encode
  101. (string->utf8 str))))
  102. headers))
  103. (_ headers))))
  104. (unless (or buffered? (not (file-port? port)))
  105. (setvbuf port 'none))
  106. (let*-values (((resp data)
  107. (http-get uri #:streaming? #t #:port port
  108. #:keep-alive? keep-alive?
  109. #:headers headers))
  110. ((code)
  111. (response-code resp)))
  112. (case code
  113. ((200)
  114. (values data (response-content-length resp)))
  115. ((301 ; moved permanently
  116. 302 ; found (redirection)
  117. 303 ; see other
  118. 307 ; temporary redirection
  119. 308) ; permanent redirection
  120. (let ((uri (resolve-uri-reference (response-location resp) uri)))
  121. (close-port port)
  122. (format log-port (G_ "following redirection to `~a'...~%")
  123. (uri->string uri))
  124. (loop uri)))
  125. (else
  126. (raise (condition (&http-get-error
  127. (uri uri)
  128. (code code)
  129. (reason (response-reason-phrase resp)))
  130. (&message
  131. (message
  132. (format
  133. #f
  134. (G_ "~a: HTTP download failed: ~a (~s)")
  135. (uri->string uri) code
  136. (response-reason-phrase resp))))))))))))
  137. (define-syntax-rule (false-if-networking-error exp)
  138. "Return #f if EXP triggers a network related exception as can occur when
  139. reusing stale cached connections."
  140. ;; FIXME: Duplicated from 'with-cached-connection'.
  141. (catch #t
  142. (lambda ()
  143. exp)
  144. (lambda (key . args)
  145. ;; If PORT was cached and the server closed the connection in the
  146. ;; meantime, we get EPIPE. In that case, open a fresh connection and
  147. ;; retry. We might also get 'bad-response or a similar exception from
  148. ;; (web response) later on, once we've sent the request, or a
  149. ;; ERROR/INVALID-SESSION from GnuTLS.
  150. (if (or (and (eq? key 'system-error)
  151. (= EPIPE (system-error-errno `(,key ,@args))))
  152. (and (eq? key 'gnutls-error)
  153. (eq? (first args) error/invalid-session))
  154. (memq key
  155. '(bad-response bad-header bad-header-component)))
  156. #f
  157. (apply throw key args)))))
  158. (define* (http-multiple-get base-uri proc seed requests
  159. #:key port (verify-certificate? #t)
  160. (open-connection guix:open-connection-for-uri)
  161. (keep-alive? #t)
  162. (batch-size 1000))
  163. "Send all of REQUESTS to the server at BASE-URI. Call PROC for each
  164. response, passing it the request object, the response, a port from which to
  165. read the response body, and the previous result, starting with SEED, à la
  166. 'fold'. Return the final result.
  167. When PORT is specified, use it as the initial connection on which HTTP
  168. requests are sent; otherwise call OPEN-CONNECTION to open a new connection for
  169. a URI. When KEEP-ALIVE? is false, close the connection port before
  170. returning."
  171. (let connect ((port port)
  172. (requests requests)
  173. (result seed))
  174. (define batch
  175. (if (>= batch-size (length requests))
  176. requests
  177. (take requests batch-size)))
  178. ;; (format (current-error-port) "connecting (~a requests left)..."
  179. ;; (length requests))
  180. (let ((p (or port (open-connection base-uri
  181. #:verify-certificate?
  182. verify-certificate?))))
  183. ;; For HTTPS, P is not a file port and does not support 'setvbuf'.
  184. (when (file-port? p)
  185. (setvbuf p 'block (expt 2 16)))
  186. ;; Send BATCH in a row.
  187. ;; XXX: Do our own caching to work around inefficiencies when
  188. ;; communicating over TLS: <http://bugs.gnu.org/22966>.
  189. (let-values (((buffer get) (open-bytevector-output-port)))
  190. ;; Inherit the HTTP proxying property from P.
  191. (set-http-proxy-port?! buffer (http-proxy-port? p))
  192. (unless (false-if-networking-error
  193. (begin
  194. (for-each (cut write-request <> buffer) batch)
  195. (put-bytevector p (get))
  196. (force-output p)
  197. #t))
  198. ;; If PORT becomes unusable, open a fresh connection and retry.
  199. (close-port p) ; close the broken port
  200. (connect #f requests result)))
  201. ;; Now start processing responses.
  202. (let loop ((sent batch)
  203. (processed 0)
  204. (result result))
  205. (match sent
  206. (()
  207. (match (drop requests processed)
  208. (()
  209. (unless keep-alive?
  210. (close-port p))
  211. (reverse result))
  212. (remainder
  213. (connect p remainder result))))
  214. ((head tail ...)
  215. (match (false-if-networking-error (read-response p))
  216. ((? response? resp)
  217. (let* ((body (response-body-port resp))
  218. (result (proc head resp body result)))
  219. ;; The server can choose to stop responding at any time,
  220. ;; in which case we have to try again. Check whether
  221. ;; that is the case. Note that even upon "Connection:
  222. ;; close", we can read from BODY.
  223. (match (assq 'connection (response-headers resp))
  224. (('connection 'close)
  225. (close-port p)
  226. (connect #f ;try again
  227. (drop requests (+ 1 processed))
  228. result))
  229. (_
  230. (loop tail (+ 1 processed) result)))))
  231. (#f
  232. (close-port p)
  233. (connect #f ; try again
  234. (drop requests processed)
  235. result)))))))))
  236. ;;;
  237. ;;; Caching.
  238. ;;;
  239. (define %http-cache-ttl
  240. ;; Time-to-live in seconds of the HTTP cache of in ~/.cache/guix.
  241. (make-parameter
  242. (* 3600 (or (and=> (getenv "GUIX_HTTP_CACHE_TTL")
  243. string->number*)
  244. 36))))
  245. (define (cache-file-for-uri uri)
  246. "Return the name of the file in the cache corresponding to URI."
  247. (let ((digest (sha256 (string->utf8 (uri->string uri)))))
  248. ;; Use the "URL" alphabet because it does not contain "/".
  249. (string-append (cache-directory) "/http/"
  250. (base64-encode digest 0 (bytevector-length digest)
  251. #f #f base64url-alphabet))))
  252. (define* (http-fetch/cached uri #:key (ttl (%http-cache-ttl)) text?
  253. (write-cache dump-port)
  254. (cache-miss (const #t))
  255. (log-port (current-error-port))
  256. (timeout 10))
  257. "Like 'http-fetch', return an input port, but cache its contents in
  258. ~/.cache/guix. The cache remains valid for TTL seconds.
  259. Call WRITE-CACHE with the HTTP input port and the cache output port to write
  260. the data to cache. Call CACHE-MISS with URI just before fetching data from
  261. URI.
  262. TIMEOUT specifies the timeout in seconds for connection establishment.
  263. Write information about redirects to LOG-PORT."
  264. (let ((file (cache-file-for-uri uri)))
  265. (define (update-cache cache-port)
  266. (define cache-time
  267. (and cache-port
  268. (stat:mtime (stat cache-port))))
  269. (define headers
  270. `((user-agent . "GNU Guile")
  271. ,@(if cache-time
  272. `((if-modified-since
  273. . ,(time-utc->date (make-time time-utc 0 cache-time))))
  274. '())))
  275. ;; Update the cache and return an input port.
  276. (guard (c ((http-get-error? c)
  277. (if (= 304 (http-get-error-code c)) ;"Not Modified"
  278. (begin
  279. (utime file) ;update FILE's mtime
  280. cache-port)
  281. (raise c))))
  282. (let ((port (http-fetch uri #:text? text?
  283. #:log-port log-port
  284. #:headers headers #:timeout timeout)))
  285. (cache-miss uri)
  286. (mkdir-p (dirname file))
  287. (when cache-port
  288. (close-port cache-port))
  289. (with-atomic-file-output file
  290. (cut write-cache port <>))
  291. (close-port port)
  292. (open-input-file file))))
  293. (define (old? port)
  294. ;; Return true if PORT has passed TTL.
  295. (let* ((s (stat port))
  296. (now (current-time time-utc)))
  297. (< (+ (stat:mtime s) ttl) (time-second now))))
  298. (catch 'system-error
  299. (lambda ()
  300. (let ((port (open-input-file file)))
  301. (if (old? port)
  302. (update-cache port)
  303. port)))
  304. (lambda args
  305. (if (= ENOENT (system-error-errno args))
  306. (update-cache #f)
  307. (apply throw args))))))
  308. ;;; http-client.scm ends here