http-client.scm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 error/again error/interrupted)
  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. (memq (first args)
  154. (list error/invalid-session
  155. ;; XXX: These two are not properly handled in
  156. ;; GnuTLS < 3.7.2, in
  157. ;; 'write_to_session_record_port'; see
  158. ;; <https://bugs.gnu.org/47867>.
  159. error/again error/interrupted)))
  160. (memq key
  161. '(bad-response bad-header bad-header-component)))
  162. #f
  163. (apply throw key args)))))
  164. (define* (http-multiple-get base-uri proc seed requests
  165. #:key port (verify-certificate? #t)
  166. (open-connection guix:open-connection-for-uri)
  167. (keep-alive? #t)
  168. (batch-size 1000))
  169. "Send all of REQUESTS to the server at BASE-URI. Call PROC for each
  170. response, passing it the request object, the response, a port from which to
  171. read the response body, and the previous result, starting with SEED, à la
  172. 'fold'. Return the final result.
  173. When PORT is specified, use it as the initial connection on which HTTP
  174. requests are sent; otherwise call OPEN-CONNECTION to open a new connection for
  175. a URI. When KEEP-ALIVE? is false, close the connection port before
  176. returning."
  177. (let connect ((port port)
  178. (requests requests)
  179. (result seed))
  180. (define batch
  181. (if (>= batch-size (length requests))
  182. requests
  183. (take requests batch-size)))
  184. ;; (format (current-error-port) "connecting (~a requests left)..."
  185. ;; (length requests))
  186. (let ((p (or port (open-connection base-uri
  187. #:verify-certificate?
  188. verify-certificate?))))
  189. ;; For HTTPS, P is not a file port and does not support 'setvbuf'.
  190. (when (file-port? p)
  191. (setvbuf p 'block (expt 2 16)))
  192. ;; Send BATCH in a row.
  193. ;; XXX: Do our own caching to work around inefficiencies when
  194. ;; communicating over TLS: <http://bugs.gnu.org/22966>.
  195. (let-values (((buffer get) (open-bytevector-output-port)))
  196. ;; Inherit the HTTP proxying property from P.
  197. (set-http-proxy-port?! buffer (http-proxy-port? p))
  198. ;; Swallow networking errors that could occur due to connection reuse
  199. ;; and the like; they will be handled down the road when trying to
  200. ;; read responses.
  201. (false-if-networking-error
  202. (begin
  203. (for-each (cut write-request <> buffer) batch)
  204. (put-bytevector p (get))
  205. (force-output p))))
  206. ;; Now start processing responses.
  207. (let loop ((sent batch)
  208. (processed 0)
  209. (result result))
  210. (match sent
  211. (()
  212. (match (drop requests processed)
  213. (()
  214. (unless keep-alive?
  215. (close-port p))
  216. (reverse result))
  217. (remainder
  218. (connect p remainder result))))
  219. ((head tail ...)
  220. (match (false-if-networking-error (read-response p))
  221. ((? response? resp)
  222. (let* ((body (response-body-port resp))
  223. (result (proc head resp body result)))
  224. ;; The server can choose to stop responding at any time,
  225. ;; in which case we have to try again. Check whether
  226. ;; that is the case. Note that even upon "Connection:
  227. ;; close", we can read from BODY.
  228. (match (assq 'connection (response-headers resp))
  229. (('connection 'close)
  230. (close-port p)
  231. (connect #f ;try again
  232. (drop requests (+ 1 processed))
  233. result))
  234. (_
  235. (loop tail (+ 1 processed) result)))))
  236. (#f
  237. (close-port p)
  238. (connect #f ; try again
  239. (drop requests processed)
  240. result)))))))))
  241. ;;;
  242. ;;; Caching.
  243. ;;;
  244. (define %http-cache-ttl
  245. ;; Time-to-live in seconds of the HTTP cache of in ~/.cache/guix.
  246. (make-parameter
  247. (* 3600 (or (and=> (getenv "GUIX_HTTP_CACHE_TTL")
  248. string->number*)
  249. 36))))
  250. (define (cache-file-for-uri uri)
  251. "Return the name of the file in the cache corresponding to URI."
  252. (let ((digest (sha256 (string->utf8 (uri->string uri)))))
  253. ;; Use the "URL" alphabet because it does not contain "/".
  254. (string-append (cache-directory) "/http/"
  255. (base64-encode digest 0 (bytevector-length digest)
  256. #f #f base64url-alphabet))))
  257. (define* (http-fetch/cached uri #:key (ttl (%http-cache-ttl)) text?
  258. (write-cache dump-port)
  259. (cache-miss (const #t))
  260. (log-port (current-error-port))
  261. (timeout 10))
  262. "Like 'http-fetch', return an input port, but cache its contents in
  263. ~/.cache/guix. The cache remains valid for TTL seconds.
  264. Call WRITE-CACHE with the HTTP input port and the cache output port to write
  265. the data to cache. Call CACHE-MISS with URI just before fetching data from
  266. URI.
  267. TIMEOUT specifies the timeout in seconds for connection establishment.
  268. Write information about redirects to LOG-PORT."
  269. (let ((file (cache-file-for-uri uri)))
  270. (define (update-cache cache-port)
  271. (define cache-time
  272. (and cache-port
  273. (stat:mtime (stat cache-port))))
  274. (define headers
  275. `((user-agent . "GNU Guile")
  276. ,@(if cache-time
  277. `((if-modified-since
  278. . ,(time-utc->date (make-time time-utc 0 cache-time))))
  279. '())))
  280. ;; Update the cache and return an input port.
  281. (guard (c ((http-get-error? c)
  282. (if (= 304 (http-get-error-code c)) ;"Not Modified"
  283. (begin
  284. (utime file) ;update FILE's mtime
  285. cache-port)
  286. (raise c))))
  287. (let ((port (http-fetch uri #:text? text?
  288. #:log-port log-port
  289. #:headers headers #:timeout timeout)))
  290. (cache-miss uri)
  291. (mkdir-p (dirname file))
  292. (when cache-port
  293. (close-port cache-port))
  294. (with-atomic-file-output file
  295. (cut write-cache port <>))
  296. (close-port port)
  297. (open-input-file file))))
  298. (define (old? port)
  299. ;; Return true if PORT has passed TTL.
  300. (let* ((s (stat port))
  301. (now (current-time time-utc)))
  302. (< (+ (stat:mtime s) ttl) (time-second now))))
  303. (catch 'system-error
  304. (lambda ()
  305. (let ((port (open-input-file file)))
  306. (if (old? port)
  307. (update-cache port)
  308. port)))
  309. (lambda args
  310. (if (= ENOENT (system-error-errno args))
  311. (update-cache #f)
  312. (apply throw args))))))
  313. ;;; http-client.scm ends here