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.

318 lines
12 KiB

  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2012, 2013, 2014, 2015, 2016 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 (web uri)
  22. #:use-module ((web client) #:hide (open-socket-for-uri))
  23. #:use-module (web response)
  24. #:use-module (srfi srfi-11)
  25. #:use-module (srfi srfi-19)
  26. #:use-module (srfi srfi-26)
  27. #:use-module (srfi srfi-34)
  28. #:use-module (srfi srfi-35)
  29. #:use-module (ice-9 match)
  30. #:use-module (rnrs io ports)
  31. #:use-module (rnrs bytevectors)
  32. #:use-module (guix ui)
  33. #:use-module (guix utils)
  34. #:use-module (guix base64)
  35. #:use-module ((guix build utils)
  36. #:select (mkdir-p dump-port))
  37. #:use-module ((guix build download)
  38. #:select (open-socket-for-uri
  39. open-connection-for-uri resolve-uri-reference))
  40. #:re-export (open-socket-for-uri)
  41. #:export (&http-get-error
  42. http-get-error?
  43. http-get-error-uri
  44. http-get-error-code
  45. http-get-error-reason
  46. http-fetch
  47. %http-cache-ttl
  48. http-fetch/cached))
  49. ;;; Commentary:
  50. ;;;
  51. ;;; HTTP client portable among Guile versions, and with proper error condition
  52. ;;; reporting.
  53. ;;;
  54. ;;; Code:
  55. ;; HTTP GET error.
  56. (define-condition-type &http-get-error &error
  57. http-get-error?
  58. (uri http-get-error-uri) ; URI
  59. (code http-get-error-code) ; integer
  60. (reason http-get-error-reason)) ; string
  61. (define-syntax when-guile<=2.0.5-or-otherwise-broken
  62. (lambda (s)
  63. (syntax-case s ()
  64. ((_ body ...)
  65. ;; Always emit BODY, regardless of VERSION, because sometimes this code
  66. ;; might be compiled with a recent Guile and run with 2.0.5---e.g.,
  67. ;; when using "guix pull".
  68. #'(begin body ...)))))
  69. (when-guile<=2.0.5-or-otherwise-broken
  70. ;; Backport of Guile commits 312e79f8 ("Add HTTP Chunked Encoding support to
  71. ;; web modules."), 00d3ecf2 ("http: Do not buffer HTTP chunks."), and 53b8d5f
  72. ;; ("web: Gracefully handle premature EOF when reading chunk header.")
  73. (use-modules (ice-9 rdelim))
  74. (define %web-http
  75. (resolve-module '(web http)))
  76. ;; Chunked Responses
  77. (define (read-chunk-header port)
  78. "Read a chunk header from PORT and return the size in bytes of the
  79. upcoming chunk."
  80. (match (read-line port)
  81. ((? eof-object?)
  82. ;; Connection closed prematurely: there's nothing left to read.
  83. 0)
  84. (str
  85. (let ((extension-start (string-index str
  86. (lambda (c)
  87. (or (char=? c #\;)
  88. (char=? c #\return))))))
  89. (string->number (if extension-start ; unnecessary?
  90. (substring str 0 extension-start)
  91. str)
  92. 16)))))
  93. (define* (make-chunked-input-port port #:key (keep-alive? #f))
  94. "Returns a new port which translates HTTP chunked transfer encoded
  95. data from PORT into a non-encoded format. Returns eof when it has
  96. read the final chunk from PORT. This does not necessarily mean
  97. that there is no more data on PORT. When the returned port is
  98. closed it will also close PORT, unless the KEEP-ALIVE? is true."
  99. (define (close)
  100. (unless keep-alive?
  101. (close-port port)))
  102. (define chunk-size 0) ;size of the current chunk
  103. (define remaining 0) ;number of bytes left from the current chunk
  104. (define finished? #f) ;did we get all the chunks?
  105. (define (read! bv idx to-read)
  106. (define (loop to-read num-read)
  107. (cond ((or finished? (zero? to-read))
  108. num-read)
  109. ((zero? remaining) ;get a new chunk
  110. (let ((size (read-chunk-header port)))
  111. (set! chunk-size size)
  112. (set! remaining size)
  113. (if (zero? size)
  114. (begin
  115. (set! finished? #t)
  116. num-read)
  117. (loop to-read num-read))))
  118. (else ;read from the current chunk
  119. (let* ((ask-for (min to-read remaining))
  120. (read (get-bytevector-n! port bv (+ idx num-read)
  121. ask-for)))
  122. (if (eof-object? read)
  123. (begin ;premature termination
  124. (set! finished? #t)
  125. num-read)
  126. (let ((left (- remaining read)))
  127. (set! remaining left)
  128. (when (zero? left)
  129. ;; We're done with this chunk; read CR and LF.
  130. (get-u8 port) (get-u8 port))
  131. (loop (- to-read read)
  132. (+ num-read read))))))))
  133. (loop to-read 0))
  134. (make-custom-binary-input-port "chunked input port" read! #f #f close))
  135. ;; Chunked encoding support in Guile <= 2.0.11 would load whole chunks in
  136. ;; memory---see <http://bugs.gnu.org/19939>.
  137. (when (module-variable %web-http 'read-chunk-body)
  138. (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)
  144. (define (fail)
  145. ((@@ (web response) bad-response)
  146. "EOF while reading response body: ~a bytes of ~a"
  147. bytes-read len))
  148. (define (read! bv start count)
  149. ;; Read at most LEN bytes in total. HTTP/1.1 doesn't say what to do
  150. ;; when a server provides more than the Content-Length, but it seems
  151. ;; wise to just stop reading at LEN.
  152. (let ((count (min count (- len bytes-read))))
  153. (let loop ((ret (get-bytevector-n! port bv start count)))
  154. (cond ((eof-object? ret)
  155. (if (= bytes-read len)
  156. 0 ; EOF
  157. (fail)))
  158. ((and (zero? ret) (> count 0))
  159. ;; Do not return zero since zero means EOF, so try again.
  160. (loop (get-bytevector-n! port bv start count)))
  161. (else
  162. (set! bytes-read (+ bytes-read ret))
  163. ret)))))
  164. (define close
  165. (and (not keep-alive?)
  166. (lambda ()
  167. (close-port port))))
  168. (make-custom-binary-input-port "delimited input port" read! #f #f close))
  169. (define (read-header-line port)
  170. "Read an HTTP header line and return it without its final CRLF or LF.
  171. Raise a 'bad-header' exception if the line does not end in CRLF or LF,
  172. or if EOF is reached."
  173. (match (%read-line port)
  174. (((? string? line) . #\newline)
  175. ;; '%read-line' does not consider #\return a delimiter; so if it's
  176. ;; there, remove it. We are more tolerant than the RFC in that we
  177. ;; tolerate LF-only endings.
  178. (if (string-suffix? "\r" line)
  179. (string-drop-right line 1)
  180. line))
  181. ((line . _) ;EOF or missing delimiter
  182. ((@@ (web http) bad-header) 'read-header-line line))))
  183. (unless (guile-version>? "2.0.11")
  184. ;; Guile <= 2.0.9 had a bug whereby 'response-body-port' would read more
  185. ;; than what 'content-length' says. See Guile commit 802a25b.
  186. ;; Guile <= 2.0.11 had a bug whereby the 'close' method of the response
  187. ;; body port would fail with wrong-arg-num. See Guile commit 5a10e41.
  188. (module-set! (resolve-module '(web response))
  189. 'make-delimited-input-port make-delimited-input-port)
  190. ;; Guile <= 2.0.11 was affected by <http://bugs.gnu.org/22273>. See Guile
  191. ;; commit 4c7732c.
  192. (when (module-variable %web-http 'read-line*)
  193. (module-set! %web-http 'read-line* read-header-line))))
  194. ;; XXX: Work around <http://bugs.gnu.org/13095>, present in Guile
  195. ;; up to 2.0.7.
  196. (module-define! (resolve-module '(web client))
  197. 'shutdown (const #f))
  198. (define* (http-fetch uri #:key port (text? #f) (buffered? #t))
  199. "Return an input port containing the data at URI, and the expected number of
  200. bytes available or #f. If TEXT? is true, the data at URI is considered to be
  201. textual. Follow any HTTP redirection. When BUFFERED? is #f, return an
  202. unbuffered port, suitable for use in `filtered-port'.
  203. Raise an '&http-get-error' condition if downloading fails."
  204. (let loop ((uri (if (string? uri)
  205. (string->uri uri)
  206. uri)))
  207. (let ((port (or port (open-connection-for-uri uri)))
  208. (auth-header (match (uri-userinfo uri)
  209. ((? string? str)
  210. (list (cons 'Authorization
  211. (string-append "Basic "
  212. (base64-encode
  213. (string->utf8 str))))))
  214. (_ '()))))
  215. (unless buffered?
  216. (setvbuf port _IONBF))
  217. (let*-values (((resp data)
  218. ;; Try hard to use the API du jour to get an input port.
  219. (if (guile-version>? "2.0.7")
  220. (http-get uri #:streaming? #t #:port port
  221. #:headers auth-header) ; 2.0.9+
  222. (http-get* uri #:decode-body? text? ; 2.0.7
  223. #:port port #:headers auth-header)))
  224. ((code)
  225. (response-code resp)))
  226. (case code
  227. ((200)
  228. (values data (response-content-length resp)))
  229. ((301 ; moved permanently
  230. 302) ; found (redirection)
  231. (let ((uri (resolve-uri-reference (response-location resp) uri)))
  232. (close-port port)
  233. (format #t (_ "following redirection to `~a'...~%")
  234. (uri->string uri))
  235. (loop uri)))
  236. (else
  237. (raise (condition (&http-get-error
  238. (uri uri)
  239. (code code)
  240. (reason (response-reason-phrase resp)))
  241. (&message
  242. (message "download failed"))))))))))
  243. ;;;
  244. ;;; Caching.
  245. ;;;
  246. (define %http-cache-ttl
  247. ;; Time-to-live in seconds of the HTTP cache of in ~/.cache/guix.
  248. (make-parameter
  249. (* 3600 (or (and=> (getenv "GUIX_HTTP_CACHE_TTL")
  250. string->number*)
  251. 36))))
  252. (define* (http-fetch/cached uri #:key (ttl (%http-cache-ttl)) text?)
  253. "Like 'http-fetch', return an input port, but cache its contents in
  254. ~/.cache/guix. The cache remains valid for TTL seconds."
  255. (let* ((directory (string-append (cache-directory) "/http/"
  256. (uri-host uri)))
  257. (file (string-append directory "/"
  258. (basename (uri-path uri)))))
  259. (define (update-cache)
  260. ;; Update the cache and return an input port.
  261. (let ((port (http-fetch uri #:text? text?)))
  262. (mkdir-p directory)
  263. (with-atomic-file-output file
  264. (cut dump-port port <>))
  265. (close-port port)
  266. (open-input-file file)))
  267. (define (old? port)
  268. ;; Return true if PORT has passed TTL.
  269. (let* ((s (stat port))
  270. (now (current-time time-utc)))
  271. (< (+ (stat:mtime s) ttl) (time-second now))))
  272. (catch 'system-error
  273. (lambda ()
  274. (let ((port (open-input-file file)))
  275. (if (old? port)
  276. (begin
  277. (close-port port)
  278. (update-cache))
  279. port)))
  280. (lambda args
  281. (if (= ENOENT (system-error-errno args))
  282. (update-cache)
  283. (apply throw args))))))
  284. ;;; http-client.scm ends here