1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2012, 2015 Free Software Foundation, Inc.
6 ;;; This file is part of GNU Guix.
8 ;;; GNU Guix is free software; you can redistribute it and/or modify it
9 ;;; under the terms of the GNU General Public License as published by
10 ;;; the Free Software Foundation; either version 3 of the License, or (at
11 ;;; your option) any later version.
13 ;;; GNU Guix is distributed in the hope that it will be useful, but
14 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;;; GNU General Public License for more details.
18 ;;; You should have received a copy of the GNU General Public License
19 ;;; 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 client) #:hide (open-socket-for-uri))
24 #:use-module (web response)
25 #:use-module (srfi srfi-11)
26 #:use-module (srfi srfi-19)
27 #:use-module (srfi srfi-26)
28 #:use-module (srfi srfi-34)
29 #:use-module (srfi srfi-35)
30 #:use-module (ice-9 match)
31 #:use-module (ice-9 binary-ports)
32 #:use-module (rnrs bytevectors)
33 #:use-module (guix ui)
34 #:use-module (guix utils)
35 #:use-module (guix base64)
36 #:autoload (guix hash) (sha256)
37 #:use-module ((guix build utils)
38 #:select (mkdir-p dump-port))
39 #:use-module ((guix build download)
40 #:select (open-socket-for-uri
41 (open-connection-for-uri
42 . guix:open-connection-for-uri)
43 resolve-uri-reference))
44 #:re-export (open-socket-for-uri)
45 #:export (&http-get-error
58 ;;; HTTP client portable among Guile versions, and with proper error condition
64 (define-condition-type &http-get-error &error
66 (uri http-get-error-uri) ; URI
67 (code http-get-error-code) ; integer
68 (reason http-get-error-reason)) ; string
71 (define-syntax when-guile<=2.0.5-or-otherwise-broken
75 ;; Always emit BODY, regardless of VERSION, because sometimes this code
76 ;; might be compiled with a recent Guile and run with 2.0.5---e.g.,
77 ;; when using "guix pull".
78 #'(begin body ...)))))
80 (when-guile<=2.0.5-or-otherwise-broken
81 ;; Backport of Guile commits 312e79f8 ("Add HTTP Chunked Encoding support to
82 ;; web modules."), 00d3ecf2 ("http: Do not buffer HTTP chunks."), and 53b8d5f
83 ;; ("web: Gracefully handle premature EOF when reading chunk header.")
85 (use-modules (ice-9 rdelim))
88 (resolve-module '(web http)))
91 (define (read-chunk-header port)
92 "Read a chunk header from PORT and return the size in bytes of the
94 (match (read-line port)
96 ;; Connection closed prematurely: there's nothing left to read.
99 (let ((extension-start (string-index str
102 (char=? c #\return))))))
103 (string->number (if extension-start ; unnecessary?
104 (substring str 0 extension-start)
108 (define* (make-chunked-input-port port #:key (keep-alive? #f))
109 "Returns a new port which translates HTTP chunked transfer encoded
110 data from PORT into a non-encoded format. Returns eof when it has
111 read the final chunk from PORT. This does not necessarily mean
112 that there is no more data on PORT. When the returned port is
113 closed it will also close PORT, unless the KEEP-ALIVE? is true."
118 (define chunk-size 0) ;size of the current chunk
119 (define remaining 0) ;number of bytes left from the current chunk
120 (define finished? #f) ;did we get all the chunks?
122 (define (read! bv idx to-read)
123 (define (loop to-read num-read)
124 (cond ((or finished? (zero? to-read))
126 ((zero? remaining) ;get a new chunk
127 (let ((size (read-chunk-header port)))
128 (set! chunk-size size)
129 (set! remaining size)
134 (loop to-read num-read))))
135 (else ;read from the current chunk
136 (let* ((ask-for (min to-read remaining))
137 (read (get-bytevector-n! port bv (+ idx num-read)
139 (if (eof-object? read)
140 (begin ;premature termination
143 (let ((left (- remaining read)))
144 (set! remaining left)
146 ;; We're done with this chunk; read CR and LF.
147 (get-u8 port) (get-u8 port))
148 (loop (- to-read read)
149 (+ num-read read))))))))
152 (make-custom-binary-input-port "chunked input port" read! #f #f close))
154 ;; Chunked encoding support in Guile <= 2.0.11 would load whole chunks in
155 ;; memory---see <http://bugs.gnu.org/19939>.
156 (when (module-variable %web-http 'read-chunk-body)
157 (module-set! %web-http 'make-chunked-input-port make-chunked-input-port))
159 (define (make-delimited-input-port port len keep-alive?)
160 "Return an input port that reads from PORT, and makes sure that
161 exactly LEN bytes are available from PORT. Closing the returned port
162 closes PORT, unless KEEP-ALIVE? is true."
163 (define bytes-read 0)
166 ((@@ (web response) bad-response)
167 "EOF while reading response body: ~a bytes of ~a"
170 (define (read! bv start count)
171 ;; Read at most LEN bytes in total. HTTP/1.1 doesn't say what to do
172 ;; when a server provides more than the Content-Length, but it seems
173 ;; wise to just stop reading at LEN.
174 (let ((count (min count (- len bytes-read))))
175 (let loop ((ret (get-bytevector-n! port bv start count)))
176 (cond ((eof-object? ret)
177 (if (= bytes-read len)
180 ((and (zero? ret) (> count 0))
181 ;; Do not return zero since zero means EOF, so try again.
182 (loop (get-bytevector-n! port bv start count)))
184 (set! bytes-read (+ bytes-read ret))
188 (and (not keep-alive?)
192 (make-custom-binary-input-port "delimited input port" read! #f #f close))
194 (define (read-header-line port)
195 "Read an HTTP header line and return it without its final CRLF or LF.
196 Raise a 'bad-header' exception if the line does not end in CRLF or LF,
197 or if EOF is reached."
198 (match (%read-line port)
199 (((? string? line) . #\newline)
200 ;; '%read-line' does not consider #\return a delimiter; so if it's
201 ;; there, remove it. We are more tolerant than the RFC in that we
202 ;; tolerate LF-only endings.
203 (if (string-suffix? "\r" line)
204 (string-drop-right line 1)
206 ((line . _) ;EOF or missing delimiter
207 ((@@ (web http) bad-header) 'read-header-line line))))
209 (unless (guile-version>? "2.0.11")
210 ;; Guile <= 2.0.9 had a bug whereby 'response-body-port' would read more
211 ;; than what 'content-length' says. See Guile commit 802a25b.
212 ;; Guile <= 2.0.11 had a bug whereby the 'close' method of the response
213 ;; body port would fail with wrong-arg-num. See Guile commit 5a10e41.
214 (module-set! (resolve-module '(web response))
215 'make-delimited-input-port make-delimited-input-port)
217 ;; Guile <= 2.0.11 was affected by <http://bugs.gnu.org/22273>. See Guile
219 (when (module-variable %web-http 'read-line*)
220 (module-set! %web-http 'read-line* read-header-line))))
223 (define* (http-fetch uri #:key port (text? #f) (buffered? #t)
224 keep-alive? (verify-certificate? #t)
225 (headers '((user-agent . "GNU Guile"))))
226 "Return an input port containing the data at URI, and the expected number of
227 bytes available or #f. If TEXT? is true, the data at URI is considered to be
228 textual. Follow any HTTP redirection. When BUFFERED? is #f, return an
229 unbuffered port, suitable for use in `filtered-port'. When KEEP-ALIVE? is
230 true, send a 'Connection: keep-alive' HTTP header, in which case PORT may be
231 reused for future HTTP requests. HEADERS is an alist of extra HTTP headers.
233 When VERIFY-CERTIFICATE? is true, verify HTTPS server certificates.
235 Raise an '&http-get-error' condition if downloading fails."
236 (let loop ((uri (if (string? uri)
239 (let ((port (or port (guix:open-connection-for-uri uri
240 #:verify-certificate?
241 verify-certificate?)))
242 (headers (match (uri-userinfo uri)
244 (cons (cons 'Authorization
245 (string-append "Basic "
247 (string->utf8 str))))
250 (unless (or buffered? (not (file-port? port)))
251 (setvbuf port _IONBF))
252 (let*-values (((resp data)
253 (http-get uri #:streaming? #t #:port port
257 (response-code resp)))
260 (values data (response-content-length resp)))
261 ((301 ; moved permanently
262 302) ; found (redirection)
263 (let ((uri (resolve-uri-reference (response-location resp) uri)))
265 (format #t (G_ "following redirection to `~a'...~%")
269 (raise (condition (&http-get-error
272 (reason (response-reason-phrase resp)))
277 (G_ "~a: HTTP download failed: ~a (~s)")
278 (uri->string uri) code
279 (response-reason-phrase resp))))))))))))
286 (define %http-cache-ttl
287 ;; Time-to-live in seconds of the HTTP cache of in ~/.cache/guix.
289 (* 3600 (or (and=> (getenv "GUIX_HTTP_CACHE_TTL")
293 (define (cache-file-for-uri uri)
294 "Return the name of the file in the cache corresponding to URI."
295 (let ((digest (sha256 (string->utf8 (uri->string uri)))))
296 ;; Use the "URL" alphabet because it does not contain "/".
297 (string-append (cache-directory) "/http/"
298 (base64-encode digest 0 (bytevector-length digest)
299 #f #f base64url-alphabet))))
301 (define* (http-fetch/cached uri #:key (ttl (%http-cache-ttl)) text?)
302 "Like 'http-fetch', return an input port, but cache its contents in
303 ~/.cache/guix. The cache remains valid for TTL seconds."
304 (let ((file (cache-file-for-uri uri)))
305 (define (update-cache)
306 ;; Update the cache and return an input port.
307 (let ((port (http-fetch uri #:text? text?)))
308 (mkdir-p (dirname file))
309 (with-atomic-file-output file
310 (cut dump-port port <>))
312 (open-input-file file)))
315 ;; Return true if PORT has passed TTL.
316 (let* ((s (stat port))
317 (now (current-time time-utc)))
318 (< (+ (stat:mtime s) ttl) (time-second now))))
322 (let ((port (open-input-file file)))
329 (if (= ENOENT (system-error-errno args))
331 (apply throw args))))))
333 ;;; http-client.scm ends here