http-client.scm 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2020 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
  4. ;;; Copyright © 2012, 2015 Free Software Foundation, Inc.
  5. ;;; Copyright © 2017 Tobias Geerinckx-Rice <me@tobias.gr>
  6. ;;;
  7. ;;; This file is part of GNU Guix.
  8. ;;;
  9. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  10. ;;; under the terms of the GNU General Public License as published by
  11. ;;; the Free Software Foundation; either version 3 of the License, or (at
  12. ;;; your option) any later version.
  13. ;;;
  14. ;;; GNU Guix is distributed in the hope that it will be useful, but
  15. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;;; GNU General Public License for more details.
  18. ;;;
  19. ;;; You should have received a copy of the GNU General Public License
  20. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  21. (define-module (guix http-client)
  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-19)
  27. #:use-module (srfi srfi-26)
  28. #:use-module (srfi srfi-34)
  29. #:use-module (srfi srfi-35)
  30. #:use-module (ice-9 match)
  31. #:use-module (ice-9 binary-ports)
  32. #:use-module (rnrs bytevectors)
  33. #:use-module (guix ui)
  34. #:use-module (guix utils)
  35. #:use-module (guix base64)
  36. #:autoload (gcrypt hash) (sha256)
  37. #:use-module ((guix build utils)
  38. #:select (mkdir-p dump-port))
  39. #:use-module ((guix build download)
  40. #:select (open-socket-for-uri
  41. (open-connection-for-uri
  42. . guix:open-connection-for-uri)
  43. resolve-uri-reference))
  44. #:re-export (open-socket-for-uri)
  45. #:export (&http-get-error
  46. http-get-error?
  47. http-get-error-uri
  48. http-get-error-code
  49. http-get-error-reason
  50. http-fetch
  51. %http-cache-ttl
  52. http-fetch/cached))
  53. ;;; Commentary:
  54. ;;;
  55. ;;; HTTP client portable among Guile versions, and with proper error condition
  56. ;;; reporting.
  57. ;;;
  58. ;;; Code:
  59. ;; HTTP GET error.
  60. (define-condition-type &http-get-error &error
  61. http-get-error?
  62. (uri http-get-error-uri) ; URI
  63. (code http-get-error-code) ; integer
  64. (reason http-get-error-reason)) ; string
  65. (define* (http-fetch uri #:key port (text? #f) (buffered? #t)
  66. (keep-alive? #f)
  67. (verify-certificate? #t)
  68. (headers '((user-agent . "GNU Guile")))
  69. timeout)
  70. "Return an input port containing the data at URI, and the expected number of
  71. bytes available or #f. If TEXT? is true, the data at URI is considered to be
  72. textual. Follow any HTTP redirection. When BUFFERED? is #f, return an
  73. unbuffered port, suitable for use in `filtered-port'. HEADERS is an alist of
  74. extra HTTP headers.
  75. When KEEP-ALIVE? is true, the connection is marked as 'keep-alive' and PORT is
  76. not closed upon completion.
  77. When VERIFY-CERTIFICATE? is true, verify HTTPS server certificates.
  78. TIMEOUT specifies the timeout in seconds for connection establishment; when
  79. TIMEOUT is #f, connection establishment never times out.
  80. Raise an '&http-get-error' condition if downloading fails."
  81. (let loop ((uri (if (string? uri)
  82. (string->uri uri)
  83. uri)))
  84. (let ((port (or port (guix:open-connection-for-uri uri
  85. #:verify-certificate?
  86. verify-certificate?
  87. #:timeout timeout)))
  88. (headers (match (uri-userinfo uri)
  89. ((? string? str)
  90. (cons (cons 'Authorization
  91. (string-append "Basic "
  92. (base64-encode
  93. (string->utf8 str))))
  94. headers))
  95. (_ headers))))
  96. (unless (or buffered? (not (file-port? port)))
  97. (setvbuf port 'none))
  98. (let*-values (((resp data)
  99. (http-get uri #:streaming? #t #:port port
  100. #:keep-alive? keep-alive?
  101. #:headers headers))
  102. ((code)
  103. (response-code resp)))
  104. (case code
  105. ((200)
  106. (values data (response-content-length resp)))
  107. ((301 ; moved permanently
  108. 302 ; found (redirection)
  109. 303 ; see other
  110. 307 ; temporary redirection
  111. 308) ; permanent redirection
  112. (let ((uri (resolve-uri-reference (response-location resp) uri)))
  113. (close-port port)
  114. (format (current-error-port) (G_ "following redirection to `~a'...~%")
  115. (uri->string uri))
  116. (loop uri)))
  117. (else
  118. (raise (condition (&http-get-error
  119. (uri uri)
  120. (code code)
  121. (reason (response-reason-phrase resp)))
  122. (&message
  123. (message
  124. (format
  125. #f
  126. (G_ "~a: HTTP download failed: ~a (~s)")
  127. (uri->string uri) code
  128. (response-reason-phrase resp))))))))))))
  129. ;;;
  130. ;;; Caching.
  131. ;;;
  132. (define %http-cache-ttl
  133. ;; Time-to-live in seconds of the HTTP cache of in ~/.cache/guix.
  134. (make-parameter
  135. (* 3600 (or (and=> (getenv "GUIX_HTTP_CACHE_TTL")
  136. string->number*)
  137. 36))))
  138. (define (cache-file-for-uri uri)
  139. "Return the name of the file in the cache corresponding to URI."
  140. (let ((digest (sha256 (string->utf8 (uri->string uri)))))
  141. ;; Use the "URL" alphabet because it does not contain "/".
  142. (string-append (cache-directory) "/http/"
  143. (base64-encode digest 0 (bytevector-length digest)
  144. #f #f base64url-alphabet))))
  145. (define* (http-fetch/cached uri #:key (ttl (%http-cache-ttl)) text?
  146. (write-cache dump-port)
  147. (cache-miss (const #t))
  148. (timeout 10))
  149. "Like 'http-fetch', return an input port, but cache its contents in
  150. ~/.cache/guix. The cache remains valid for TTL seconds.
  151. Call WRITE-CACHE with the HTTP input port and the cache output port to write
  152. the data to cache. Call CACHE-MISS with URI just before fetching data from
  153. URI.
  154. TIMEOUT specifies the timeout in seconds for connection establishment."
  155. (let ((file (cache-file-for-uri uri)))
  156. (define (update-cache cache-port)
  157. (define cache-time
  158. (and cache-port
  159. (stat:mtime (stat cache-port))))
  160. (define headers
  161. `((user-agent . "GNU Guile")
  162. ,@(if cache-time
  163. `((if-modified-since
  164. . ,(time-utc->date (make-time time-utc 0 cache-time))))
  165. '())))
  166. ;; Update the cache and return an input port.
  167. (guard (c ((http-get-error? c)
  168. (if (= 304 (http-get-error-code c)) ;"Not Modified"
  169. (begin
  170. (utime file) ;update FILE's mtime
  171. cache-port)
  172. (raise c))))
  173. (let ((port (http-fetch uri #:text? text?
  174. #:headers headers #:timeout timeout)))
  175. (cache-miss uri)
  176. (mkdir-p (dirname file))
  177. (when cache-port
  178. (close-port cache-port))
  179. (with-atomic-file-output file
  180. (cut write-cache port <>))
  181. (close-port port)
  182. (open-input-file file))))
  183. (define (old? port)
  184. ;; Return true if PORT has passed TTL.
  185. (let* ((s (stat port))
  186. (now (current-time time-utc)))
  187. (< (+ (stat:mtime s) ttl) (time-second now))))
  188. (catch 'system-error
  189. (lambda ()
  190. (let ((port (open-input-file file)))
  191. (if (old? port)
  192. (update-cache port)
  193. port)))
  194. (lambda args
  195. (if (= ENOENT (system-error-errno args))
  196. (update-cache #f)
  197. (apply throw args))))))
  198. ;;; http-client.scm ends here