1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014 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 (guix utils)
23 #:use-module (web uri)
24 #:use-module (web client)
25 #:use-module (web response)
26 #:use-module (srfi srfi-11)
27 #:use-module (srfi srfi-34)
28 #:use-module (srfi srfi-35)
29 #:use-module (rnrs io ports)
30 #:use-module (rnrs bytevectors)
31 #:use-module (guix ui)
32 #:use-module (guix utils)
33 #:use-module ((guix build download) #:select (resolve-uri-reference))
34 #:export (&http-get-error
45 ;;; HTTP client portable among Guile versions, and with proper error condition
51 (define-condition-type &http-get-error &error
53 (uri http-get-error-uri) ; URI
54 (code http-get-error-code) ; integer
55 (reason http-get-error-reason)) ; string
58 (define-syntax when-guile<=2.0.5-or-otherwise-broken
62 ;; Always emit BODY, regardless of VERSION, because sometimes this code
63 ;; might be compiled with a recent Guile and run with 2.0.5---e.g.,
64 ;; when using "guix pull".
65 #'(begin body ...)))))
67 (when-guile<=2.0.5-or-otherwise-broken
68 ;; Backport of Guile commits 312e79f8 ("Add HTTP Chunked Encoding support to
69 ;; web modules.") and 00d3ecf2 ("http: Do not buffer HTTP chunks.")
71 (use-modules (ice-9 rdelim))
74 (resolve-module '(web http)))
77 (define (read-chunk-header port)
78 (let* ((str (read-line port))
79 (extension-start (string-index str (lambda (c) (or (char=? c #\;)
80 (char=? c #\return)))))
81 (size (string->number (if extension-start ; unnecessary?
82 (substring str 0 extension-start)
87 (define* (make-chunked-input-port port #:key (keep-alive? #f))
88 "Returns a new port which translates HTTP chunked transfer encoded
89 data from PORT into a non-encoded format. Returns eof when it has
90 read the final chunk from PORT. This does not necessarily mean
91 that there is no more data on PORT. When the returned port is
92 closed it will also close PORT, unless the KEEP-ALIVE? is true."
97 (define chunk-size 0) ;size of the current chunk
98 (define remaining 0) ;number of bytes left from the current chunk
99 (define finished? #f) ;did we get all the chunks?
101 (define (read! bv idx to-read)
102 (define (loop to-read num-read)
103 (cond ((or finished? (zero? to-read))
105 ((zero? remaining) ;get a new chunk
106 (let ((size (read-chunk-header port)))
107 (set! chunk-size size)
108 (set! remaining size)
113 (loop to-read num-read))))
114 (else ;read from the current chunk
115 (let* ((ask-for (min to-read remaining))
116 (read (get-bytevector-n! port bv (+ idx num-read)
118 (if (eof-object? read)
119 (begin ;premature termination
122 (let ((left (- remaining read)))
123 (set! remaining left)
125 ;; We're done with this chunk; read CR and LF.
126 (get-u8 port) (get-u8 port))
127 (loop (- to-read read)
128 (+ num-read read))))))))
131 (make-custom-binary-input-port "chunked input port" read! #f #f close))
133 ;; Chunked encoding support in Guile <= 2.0.11 would load whole chunks in
134 ;; memory---see <http://bugs.gnu.org/19939>.
135 (when (module-variable %web-http 'read-chunk-body)
136 (module-set! %web-http 'make-chunked-input-port make-chunked-input-port))
138 (define (make-delimited-input-port port len keep-alive?)
139 "Return an input port that reads from PORT, and makes sure that
140 exactly LEN bytes are available from PORT. Closing the returned port
141 closes PORT, unless KEEP-ALIVE? is true."
142 (define bytes-read 0)
145 ((@@ (web response) bad-response)
146 "EOF while reading response body: ~a bytes of ~a"
149 (define (read! bv start count)
150 ;; Read at most LEN bytes in total. HTTP/1.1 doesn't say what to do
151 ;; when a server provides more than the Content-Length, but it seems
152 ;; wise to just stop reading at LEN.
153 (let ((count (min count (- len bytes-read))))
154 (let loop ((ret (get-bytevector-n! port bv start count)))
155 (cond ((eof-object? ret)
156 (if (= bytes-read len)
159 ((and (zero? ret) (> count 0))
160 ;; Do not return zero since zero means EOF, so try again.
161 (loop (get-bytevector-n! port bv start count)))
163 (set! bytes-read (+ bytes-read ret))
167 (and (not keep-alive?)
171 (make-custom-binary-input-port "delimited input port" read! #f #f close))
173 (unless (guile-version>? "2.0.9")
174 ;; Guile <= 2.0.9 had a bug whereby 'response-body-port' would read more
175 ;; than what 'content-length' says. See Guile commit 802a25b.
176 (module-set! (resolve-module '(web response))
177 'make-delimited-input-port make-delimited-input-port))
179 (define (read-response-body* r)
180 "Reads the response body from @var{r}, as a bytevector. Returns
181 @code{#f} if there was no response body."
183 (@@ (web response) bad-response))
185 (if (member '(chunked) (response-transfer-encoding r))
186 (let ((chunk-port (make-chunked-input-port (response-port r)
188 (get-bytevector-all chunk-port))
189 (let ((nbytes (response-content-length r)))
190 ;; Backport of Guile commit 84dfde82ae8f6ec247c1c147c1e2ae50b207bad9
191 ;; ("fix response-body-port for responses without content-length").
193 (let ((bv (get-bytevector-n (response-port r) nbytes)))
194 (if (= (bytevector-length bv) nbytes)
196 (bad-response "EOF while reading response body: ~a bytes of ~a"
197 (bytevector-length bv) nbytes)))
198 (get-bytevector-all (response-port r))))))
200 ;; Install this patch only on Guile 2.0.5.
201 (unless (guile-version>? "2.0.5")
202 (module-set! (resolve-module '(web response))
203 'read-response-body read-response-body*)))
205 ;; XXX: Work around <http://bugs.gnu.org/13095>, present in Guile
207 (module-define! (resolve-module '(web client))
208 'shutdown (const #f))
210 (define* (open-socket-for-uri uri #:key (buffered? #t))
211 "Return an open port for URI. When BUFFERED? is false, the returned port is
214 ;; The maximum size for a receive buffer on Linux, see socket(7).
215 "/proc/sys/net/core/rmem_max")
218 (if (file-exists? rmem-max)
219 (call-with-input-file rmem-max read)
220 126976)) ; the default for Linux, per 'rmem_default'
222 (let ((s ((@ (web client) open-socket-for-uri) uri)))
223 ;; Work around <http://bugs.gnu.org/15368> by restoring a decent
225 (setsockopt s SOL_SOCKET SO_RCVBUF buffer-size)
230 (define* (http-fetch uri #:key port (text? #f) (buffered? #t))
231 "Return an input port containing the data at URI, and the expected number of
232 bytes available or #f. If TEXT? is true, the data at URI is considered to be
233 textual. Follow any HTTP redirection. When BUFFERED? is #f, return an
234 unbuffered port, suitable for use in `filtered-port'.
236 Raise an '&http-get-error' condition if downloading fails."
237 (let loop ((uri uri))
239 (open-socket-for-uri uri
240 #:buffered? buffered?))))
241 (let*-values (((resp data)
242 ;; Try hard to use the API du jour to get an input port.
243 ;; On Guile 2.0.5 and before, we can only get a string or
244 ;; bytevector, and not an input port. Work around that.
245 (if (guile-version>? "2.0.7")
246 (http-get uri #:streaming? #t #:port port) ; 2.0.9+
247 (if (defined? 'http-get*)
248 (http-get* uri #:decode-body? text?
250 (http-get uri #:decode-body? text?
251 #:port port)))) ; 2.0.5-
253 (response-code resp)))
256 (let ((len (response-content-length resp)))
259 ;; Guile 2.0.5 and earlier did not support chunked
260 ;; transfer encoding, which is required for instance when
261 ;; fetching %PACKAGE-LIST-URL (see
262 ;; <http://lists.gnu.org/archive/html/guile-devel/2011-09/msg00089.html>).
263 ;; Normally the `when-guile<=2.0.5' block above fixes
264 ;; that, but who knows what could happen.
265 (warning (_ "using Guile ~a, which does not support ~s encoding~%")
267 (response-transfer-encoding resp))
268 (leave (_ "download failed; use a newer Guile~%")
270 ((string? data) ; `http-get' from 2.0.5-
271 (values (open-input-string data) len))
272 ((bytevector? data) ; likewise
273 (values (open-bytevector-input-port data) len))
275 (values data len)))))
276 ((301 ; moved permanently
277 302) ; found (redirection)
278 (let ((uri (resolve-uri-reference (response-location resp) uri)))
280 (format #t (_ "following redirection to `~a'...~%")
284 (raise (condition (&http-get-error
287 (reason (response-reason-phrase resp)))
289 (message "download failed"))))))))))
291 ;;; http-client.scm ends here