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.

340 lines
14 KiB

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