Merge branch 'master' into core-updates
[jackhill/guix/guix.git] / guix / http-client.scm
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.
5 ;;;
6 ;;; This file is part of GNU Guix.
7 ;;;
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.
12 ;;;
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.
17 ;;;
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/>.
20
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
46 http-get-error?
47 http-get-error-uri
48 http-get-error-code
49 http-get-error-reason
50
51 http-fetch
52
53 %http-cache-ttl
54 http-fetch/cached))
55
56 ;;; Commentary:
57 ;;;
58 ;;; HTTP client portable among Guile versions, and with proper error condition
59 ;;; reporting.
60 ;;;
61 ;;; Code:
62
63 ;; HTTP GET error.
64 (define-condition-type &http-get-error &error
65 http-get-error?
66 (uri http-get-error-uri) ; URI
67 (code http-get-error-code) ; integer
68 (reason http-get-error-reason)) ; string
69
70
71 (define-syntax when-guile<=2.0.5-or-otherwise-broken
72 (lambda (s)
73 (syntax-case s ()
74 ((_ body ...)
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 ...)))))
79
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.")
84
85 (use-modules (ice-9 rdelim))
86
87 (define %web-http
88 (resolve-module '(web http)))
89
90 ;; Chunked Responses
91 (define (read-chunk-header port)
92 "Read a chunk header from PORT and return the size in bytes of the
93 upcoming chunk."
94 (match (read-line port)
95 ((? eof-object?)
96 ;; Connection closed prematurely: there's nothing left to read.
97 0)
98 (str
99 (let ((extension-start (string-index str
100 (lambda (c)
101 (or (char=? c #\;)
102 (char=? c #\return))))))
103 (string->number (if extension-start ; unnecessary?
104 (substring str 0 extension-start)
105 str)
106 16)))))
107
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."
114 (define (close)
115 (unless keep-alive?
116 (close-port port)))
117
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?
121
122 (define (read! bv idx to-read)
123 (define (loop to-read num-read)
124 (cond ((or finished? (zero? to-read))
125 num-read)
126 ((zero? remaining) ;get a new chunk
127 (let ((size (read-chunk-header port)))
128 (set! chunk-size size)
129 (set! remaining size)
130 (if (zero? size)
131 (begin
132 (set! finished? #t)
133 num-read)
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)
138 ask-for)))
139 (if (eof-object? read)
140 (begin ;premature termination
141 (set! finished? #t)
142 num-read)
143 (let ((left (- remaining read)))
144 (set! remaining left)
145 (when (zero? 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))))))))
150 (loop to-read 0))
151
152 (make-custom-binary-input-port "chunked input port" read! #f #f close))
153
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))
158
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)
164
165 (define (fail)
166 ((@@ (web response) bad-response)
167 "EOF while reading response body: ~a bytes of ~a"
168 bytes-read len))
169
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)
178 0 ; EOF
179 (fail)))
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)))
183 (else
184 (set! bytes-read (+ bytes-read ret))
185 ret)))))
186
187 (define close
188 (and (not keep-alive?)
189 (lambda ()
190 (close-port port))))
191
192 (make-custom-binary-input-port "delimited input port" read! #f #f close))
193
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)
205 line))
206 ((line . _) ;EOF or missing delimiter
207 ((@@ (web http) bad-header) 'read-header-line line))))
208
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)
216
217 ;; Guile <= 2.0.11 was affected by <http://bugs.gnu.org/22273>. See Guile
218 ;; commit 4c7732c.
219 (when (module-variable %web-http 'read-line*)
220 (module-set! %web-http 'read-line* read-header-line))))
221
222
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.
232
233 When VERIFY-CERTIFICATE? is true, verify HTTPS server certificates.
234
235 Raise an '&http-get-error' condition if downloading fails."
236 (let loop ((uri (if (string? uri)
237 (string->uri uri)
238 uri)))
239 (let ((port (or port (guix:open-connection-for-uri uri
240 #:verify-certificate?
241 verify-certificate?)))
242 (headers (match (uri-userinfo uri)
243 ((? string? str)
244 (cons (cons 'Authorization
245 (string-append "Basic "
246 (base64-encode
247 (string->utf8 str))))
248 headers))
249 (_ headers))))
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
254 #:keep-alive? #t
255 #:headers headers))
256 ((code)
257 (response-code resp)))
258 (case code
259 ((200)
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)))
264 (close-port port)
265 (format #t (G_ "following redirection to `~a'...~%")
266 (uri->string uri))
267 (loop uri)))
268 (else
269 (raise (condition (&http-get-error
270 (uri uri)
271 (code code)
272 (reason (response-reason-phrase resp)))
273 (&message
274 (message
275 (format
276 #f
277 (G_ "~a: HTTP download failed: ~a (~s)")
278 (uri->string uri) code
279 (response-reason-phrase resp))))))))))))
280
281 \f
282 ;;;
283 ;;; Caching.
284 ;;;
285
286 (define %http-cache-ttl
287 ;; Time-to-live in seconds of the HTTP cache of in ~/.cache/guix.
288 (make-parameter
289 (* 3600 (or (and=> (getenv "GUIX_HTTP_CACHE_TTL")
290 string->number*)
291 36))))
292
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))))
300
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 <>))
311 (close-port port)
312 (open-input-file file)))
313
314 (define (old? port)
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))))
319
320 (catch 'system-error
321 (lambda ()
322 (let ((port (open-input-file file)))
323 (if (old? port)
324 (begin
325 (close-port port)
326 (update-cache))
327 port)))
328 (lambda args
329 (if (= ENOENT (system-error-errno args))
330 (update-cache)
331 (apply throw args))))))
332
333 ;;; http-client.scm ends here