download: Work around Guile small-receive-buffer bug.
[guix.git] / guix / http-client.scm
blob90eca0a946a9c836deeaa601bdebf1e958f1551e
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015 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/>.
21 (define-module (guix http-client)
22   #:use-module (guix utils)
23   #:use-module (web uri)
24   #:use-module ((web client) #:hide (open-socket-for-uri))
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)
34                 #:select (open-socket-for-uri resolve-uri-reference))
35   #:re-export (open-socket-for-uri)
36   #:export (&http-get-error
37             http-get-error?
38             http-get-error-uri
39             http-get-error-code
40             http-get-error-reason
42             http-fetch))
44 ;;; Commentary:
45 ;;;
46 ;;; HTTP client portable among Guile versions, and with proper error condition
47 ;;; reporting.
48 ;;;
49 ;;; Code:
51 ;; HTTP GET error.
52 (define-condition-type &http-get-error &error
53   http-get-error?
54   (uri    http-get-error-uri)                     ; URI
55   (code   http-get-error-code)                    ; integer
56   (reason http-get-error-reason))                 ; string
59 (define-syntax when-guile<=2.0.5-or-otherwise-broken
60   (lambda (s)
61     (syntax-case s ()
62       ((_ body ...)
63        ;; Always emit BODY, regardless of VERSION, because sometimes this code
64        ;; might be compiled with a recent Guile and run with 2.0.5---e.g.,
65        ;; when using "guix pull".
66        #'(begin body ...)))))
68 (when-guile<=2.0.5-or-otherwise-broken
69  ;; Backport of Guile commits 312e79f8 ("Add HTTP Chunked Encoding support to
70  ;; web modules.") and 00d3ecf2 ("http: Do not buffer HTTP chunks.")
72  (use-modules (ice-9 rdelim))
74  (define %web-http
75    (resolve-module '(web http)))
77  ;; Chunked Responses
78  (define (read-chunk-header port)
79    (let* ((str (read-line port))
80           (extension-start (string-index str (lambda (c) (or (char=? c #\;)
81                                                              (char=? c #\return)))))
82           (size (string->number (if extension-start ; unnecessary?
83                                     (substring str 0 extension-start)
84                                     str)
85                                 16)))
86      size))
88  (define* (make-chunked-input-port port #:key (keep-alive? #f))
89    "Returns a new port which translates HTTP chunked transfer encoded
90 data from PORT into a non-encoded format. Returns eof when it has
91 read the final chunk from PORT. This does not necessarily mean
92 that there is no more data on PORT. When the returned port is
93 closed it will also close PORT, unless the KEEP-ALIVE? is true."
94    (define (close)
95      (unless keep-alive?
96        (close-port port)))
98    (define chunk-size 0)     ;size of the current chunk
99    (define remaining 0)      ;number of bytes left from the current chunk
100    (define finished? #f)     ;did we get all the chunks?
102    (define (read! bv idx to-read)
103      (define (loop to-read num-read)
104        (cond ((or finished? (zero? to-read))
105               num-read)
106              ((zero? remaining)                    ;get a new chunk
107               (let ((size (read-chunk-header port)))
108                 (set! chunk-size size)
109                 (set! remaining size)
110                 (if (zero? size)
111                     (begin
112                       (set! finished? #t)
113                       num-read)
114                     (loop to-read num-read))))
115              (else                           ;read from the current chunk
116               (let* ((ask-for (min to-read remaining))
117                      (read    (get-bytevector-n! port bv (+ idx num-read)
118                                                  ask-for)))
119                 (if (eof-object? read)
120                     (begin                         ;premature termination
121                       (set! finished? #t)
122                       num-read)
123                     (let ((left (- remaining read)))
124                       (set! remaining left)
125                       (when (zero? left)
126                         ;; We're done with this chunk; read CR and LF.
127                         (get-u8 port) (get-u8 port))
128                       (loop (- to-read read)
129                             (+ num-read read))))))))
130      (loop to-read 0))
132    (make-custom-binary-input-port "chunked input port" read! #f #f close))
134  ;; Chunked encoding support in Guile <= 2.0.11 would load whole chunks in
135  ;; memory---see <http://bugs.gnu.org/19939>.
136  (when (module-variable %web-http 'read-chunk-body)
137    (module-set! %web-http 'make-chunked-input-port make-chunked-input-port))
139  (define (make-delimited-input-port port len keep-alive?)
140    "Return an input port that reads from PORT, and makes sure that
141 exactly LEN bytes are available from PORT.  Closing the returned port
142 closes PORT, unless KEEP-ALIVE? is true."
143    (define bytes-read 0)
145    (define (fail)
146      ((@@ (web response) bad-response)
147       "EOF while reading response body: ~a bytes of ~a"
148       bytes-read len))
150    (define (read! bv start count)
151      ;; Read at most LEN bytes in total.  HTTP/1.1 doesn't say what to do
152      ;; when a server provides more than the Content-Length, but it seems
153      ;; wise to just stop reading at LEN.
154      (let ((count (min count (- len bytes-read))))
155        (let loop ((ret (get-bytevector-n! port bv start count)))
156          (cond ((eof-object? ret)
157                 (if (= bytes-read len)
158                     0                              ; EOF
159                     (fail)))
160                ((and (zero? ret) (> count 0))
161                 ;; Do not return zero since zero means EOF, so try again.
162                 (loop (get-bytevector-n! port bv start count)))
163                (else
164                 (set! bytes-read (+ bytes-read ret))
165                 ret)))))
167    (define close
168      (and (not keep-alive?)
169           (lambda ()
170             (close port))))
172    (make-custom-binary-input-port "delimited input port" read! #f #f close))
174  (unless (guile-version>? "2.0.9")
175    ;; Guile <= 2.0.9 had a bug whereby 'response-body-port' would read more
176    ;; than what 'content-length' says.  See Guile commit 802a25b.
177    (module-set! (resolve-module '(web response))
178                 'make-delimited-input-port make-delimited-input-port))
180  (define (read-response-body* r)
181    "Reads the response body from @var{r}, as a bytevector.  Returns
182  @code{#f} if there was no response body."
183    (define bad-response
184      (@@ (web response) bad-response))
186    (if (member '(chunked) (response-transfer-encoding r))
187        (let ((chunk-port (make-chunked-input-port (response-port r)
188                                                   #:keep-alive? #t)))
189          (get-bytevector-all chunk-port))
190        (let ((nbytes (response-content-length r)))
191          ;; Backport of Guile commit 84dfde82ae8f6ec247c1c147c1e2ae50b207bad9
192          ;; ("fix response-body-port for responses without content-length").
193          (if nbytes
194              (let ((bv (get-bytevector-n (response-port r) nbytes)))
195                (if (= (bytevector-length bv) nbytes)
196                    bv
197                    (bad-response "EOF while reading response body: ~a bytes of ~a"
198                                  (bytevector-length bv) nbytes)))
199              (get-bytevector-all (response-port r))))))
201  ;; Install this patch only on Guile 2.0.5.
202  (unless (guile-version>? "2.0.5")
203    (module-set! (resolve-module '(web response))
204                 'read-response-body read-response-body*)))
206 ;; XXX: Work around <http://bugs.gnu.org/13095>, present in Guile
207 ;; up to 2.0.7.
208 (module-define! (resolve-module '(web client))
209                 'shutdown (const #f))
211 (define* (http-fetch uri #:key port (text? #f) (buffered? #t))
212   "Return an input port containing the data at URI, and the expected number of
213 bytes available or #f.  If TEXT? is true, the data at URI is considered to be
214 textual.  Follow any HTTP redirection.  When BUFFERED? is #f, return an
215 unbuffered port, suitable for use in `filtered-port'.
217 Raise an '&http-get-error' condition if downloading fails."
218   (let loop ((uri uri))
219     (let ((port (or port (open-socket-for-uri uri))))
220       (unless buffered?
221         (setvbuf port _IONBF))
222       (let*-values (((resp data)
223                      ;; Try hard to use the API du jour to get an input port.
224                      ;; On Guile 2.0.5 and before, we can only get a string or
225                      ;; bytevector, and not an input port.  Work around that.
226                      (if (guile-version>? "2.0.7")
227                          (http-get uri #:streaming? #t #:port port) ; 2.0.9+
228                          (if (defined? 'http-get*)
229                              (http-get* uri #:decode-body? text?
230                                         #:port port) ; 2.0.7
231                              (http-get uri #:decode-body? text?
232                                        #:port port)))) ; 2.0.5-
233                     ((code)
234                      (response-code resp)))
235         (case code
236           ((200)
237            (let ((len (response-content-length resp)))
238              (cond ((not data)
239                     (begin
240                       ;; Guile 2.0.5 and earlier did not support chunked
241                       ;; transfer encoding, which is required for instance when
242                       ;; fetching %PACKAGE-LIST-URL (see
243                       ;; <http://lists.gnu.org/archive/html/guile-devel/2011-09/msg00089.html>).
244                       ;; Normally the `when-guile<=2.0.5' block above fixes
245                       ;; that, but who knows what could happen.
246                       (warning (_ "using Guile ~a, which does not support ~s encoding~%")
247                                (version)
248                                (response-transfer-encoding resp))
249                       (leave (_ "download failed; use a newer Guile~%")
250                              uri resp)))
251                    ((string? data)                ; `http-get' from 2.0.5-
252                     (values (open-input-string data) len))
253                    ((bytevector? data)            ; likewise
254                     (values (open-bytevector-input-port data) len))
255                    (else                          ; input port
256                     (values data len)))))
257           ((301                                   ; moved permanently
258             302)                                  ; found (redirection)
259            (let ((uri (resolve-uri-reference (response-location resp) uri)))
260              (close-port port)
261              (format #t (_ "following redirection to `~a'...~%")
262                      (uri->string uri))
263              (loop uri)))
264           (else
265            (raise (condition (&http-get-error
266                               (uri uri)
267                               (code code)
268                               (reason (response-reason-phrase resp)))
269                              (&message
270                               (message "download failed"))))))))))
272 ;;; http-client.scm ends here