Mirror of GNU Guix
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

272 lines
12 KiB

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