substitute.scm 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>
  4. ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>
  5. ;;; Copyright © 2020 Christopher Baines <mail@cbaines.net>
  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 scripts substitute)
  22. #:use-module (guix ui)
  23. #:use-module (guix scripts)
  24. #:use-module (guix narinfo)
  25. #:use-module (guix store)
  26. #:use-module (guix utils)
  27. #:use-module (guix combinators)
  28. #:use-module (guix config)
  29. #:use-module (guix records)
  30. #:use-module (guix diagnostics)
  31. #:use-module (guix i18n)
  32. #:use-module ((guix serialization) #:select (restore-file dump-file))
  33. #:autoload (guix store deduplication) (dump-file/deduplicate)
  34. #:autoload (guix scripts discover) (read-substitute-urls)
  35. #:use-module (gcrypt hash)
  36. #:use-module (guix base32)
  37. #:use-module (guix base64)
  38. #:use-module (guix cache)
  39. #:use-module (gcrypt pk-crypto)
  40. #:use-module (guix pki)
  41. #:use-module ((guix build utils) #:select (mkdir-p dump-port))
  42. #:use-module ((guix build download)
  43. #:select (uri-abbreviation nar-uri-abbreviation
  44. (open-connection-for-uri
  45. . guix:open-connection-for-uri)
  46. store-path-abbreviation byte-count->string))
  47. #:autoload (gnutls) (error/invalid-session)
  48. #:use-module (guix progress)
  49. #:use-module ((guix build syscalls)
  50. #:select (set-thread-name))
  51. #:use-module (ice-9 rdelim)
  52. #:use-module (ice-9 regex)
  53. #:use-module (ice-9 match)
  54. #:use-module (ice-9 format)
  55. #:use-module (ice-9 ftw)
  56. #:use-module (ice-9 binary-ports)
  57. #:use-module (ice-9 vlist)
  58. #:use-module (rnrs bytevectors)
  59. #:use-module (srfi srfi-1)
  60. #:use-module (srfi srfi-9)
  61. #:use-module (srfi srfi-11)
  62. #:use-module (srfi srfi-19)
  63. #:use-module (srfi srfi-26)
  64. #:use-module (srfi srfi-34)
  65. #:use-module (srfi srfi-35)
  66. #:use-module (web uri)
  67. #:use-module (web http)
  68. #:use-module (web request)
  69. #:use-module (web response)
  70. #:use-module (guix http-client)
  71. #:export (lookup-narinfos
  72. lookup-narinfos/diverse
  73. %allow-unauthenticated-substitutes?
  74. %error-to-file-descriptor-4?
  75. substitute-urls
  76. guix-substitute))
  77. ;;; Comment:
  78. ;;;
  79. ;;; This is the "binary substituter". It is invoked by the daemon do check
  80. ;;; for the existence of available "substitutes" (pre-built binaries), and to
  81. ;;; actually use them as a substitute to building things locally.
  82. ;;;
  83. ;;; If possible, substitute a binary for the requested store path, using a Nix
  84. ;;; "binary cache". This program implements the Nix "substituter" protocol.
  85. ;;;
  86. ;;; Code:
  87. (define %narinfo-cache-directory
  88. ;; A local cache of narinfos, to avoid going to the network. Most of the
  89. ;; time, 'guix substitute' is called by guix-daemon as root and stores its
  90. ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'
  91. ;; as a user, it stores its cache in ~/.cache.
  92. (if (zero? (getuid))
  93. (or (and=> (getenv "XDG_CACHE_HOME")
  94. (cut string-append <> "/guix/substitute"))
  95. (string-append %state-directory "/substitute/cache"))
  96. (string-append (cache-directory #:ensure? #f) "/substitute")))
  97. (define (warn-about-missing-authentication)
  98. (warning (G_ "authentication and authorization of substitutes \
  99. disabled!~%"))
  100. #t)
  101. (define %allow-unauthenticated-substitutes?
  102. ;; Whether to allow unchecked substitutes. This is useful for testing
  103. ;; purposes, and should be avoided otherwise.
  104. (make-parameter
  105. (and=> (getenv "GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES")
  106. (cut string-ci=? <> "yes"))))
  107. (define %narinfo-ttl
  108. ;; Number of seconds during which cached narinfo lookups are considered
  109. ;; valid for substitute servers that do not advertise a TTL via the
  110. ;; 'Cache-Control' response header.
  111. (* 36 3600))
  112. (define %narinfo-negative-ttl
  113. ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).
  114. (* 1 3600))
  115. (define %narinfo-transient-error-ttl
  116. ;; Likewise, but for transient errors such as 504 ("Gateway timeout").
  117. (* 10 60))
  118. (define %narinfo-expired-cache-entry-removal-delay
  119. ;; How often we want to remove files corresponding to expired cache entries.
  120. (* 7 24 3600))
  121. (define %fetch-timeout
  122. ;; Number of seconds after which networking is considered "slow".
  123. 5)
  124. (define %random-state
  125. (seed->random-state (+ (ash (cdr (gettimeofday)) 32) (getpid))))
  126. (define-syntax-rule (with-timeout duration handler body ...)
  127. "Run BODY; when DURATION seconds have expired, call HANDLER, and run BODY
  128. again."
  129. (begin
  130. (sigaction SIGALRM
  131. (lambda (signum)
  132. (sigaction SIGALRM SIG_DFL)
  133. handler))
  134. (alarm duration)
  135. (call-with-values
  136. (lambda ()
  137. (let try ()
  138. (catch 'system-error
  139. (lambda ()
  140. body ...)
  141. (lambda args
  142. ;; Before Guile v2.0.9-39-gfe51c7b, the SIGALRM triggers EINTR
  143. ;; because of the bug at
  144. ;; <http://lists.gnu.org/archive/html/guile-devel/2013-06/msg00050.html>.
  145. ;; When that happens, try again. Note: SA_RESTART cannot be
  146. ;; used because of <http://bugs.gnu.org/14640>.
  147. (if (= EINTR (system-error-errno args))
  148. (begin
  149. ;; Wait a little to avoid bursts.
  150. (usleep (random 3000000 %random-state))
  151. (try))
  152. (apply throw args))))))
  153. (lambda result
  154. (alarm 0)
  155. (sigaction SIGALRM SIG_DFL)
  156. (apply values result)))))
  157. (define* (fetch uri #:key (buffered? #t) (timeout? #t)
  158. (keep-alive? #f) (port #f))
  159. "Return a binary input port to URI and the number of bytes it's expected to
  160. provide.
  161. When PORT is true, use it as the underlying I/O port for HTTP transfers; when
  162. PORT is false, open a new connection for URI. When KEEP-ALIVE? is true, the
  163. connection (typically PORT) is kept open once data has been fetched from URI."
  164. (case (uri-scheme uri)
  165. ((file)
  166. (let ((port (open-file (uri-path uri)
  167. (if buffered? "rb" "r0b"))))
  168. (values port (stat:size (stat port)))))
  169. ((http https)
  170. (guard (c ((http-get-error? c)
  171. (leave (G_ "download from '~a' failed: ~a, ~s~%")
  172. (uri->string (http-get-error-uri c))
  173. (http-get-error-code c)
  174. (http-get-error-reason c))))
  175. ;; Test this with:
  176. ;; sudo tc qdisc add dev eth0 root netem delay 1500ms
  177. ;; and then cancel with:
  178. ;; sudo tc qdisc del dev eth0 root
  179. (let ((port port))
  180. (with-timeout (if timeout?
  181. %fetch-timeout
  182. 0)
  183. (begin
  184. (warning (G_ "while fetching ~a: server is somewhat slow~%")
  185. (uri->string uri))
  186. (warning (G_ "try `--no-substitutes' if the problem persists~%")))
  187. (begin
  188. (when (or (not port) (port-closed? port))
  189. (set! port (guix:open-connection-for-uri
  190. uri #:verify-certificate? #f)))
  191. (unless (or buffered? (not (file-port? port)))
  192. (setvbuf port 'none))
  193. (http-fetch uri #:text? #f #:port port
  194. #:keep-alive? keep-alive?
  195. #:verify-certificate? #f))))))
  196. (else
  197. (leave (G_ "unsupported substitute URI scheme: ~a~%")
  198. (uri->string uri)))))
  199. (define (narinfo-cache-file cache-url path)
  200. "Return the name of the local file that contains an entry for PATH. The
  201. entry is stored in a sub-directory specific to CACHE-URL."
  202. ;; The daemon does not sanitize its input, so PATH could be something like
  203. ;; "/gnu/store/foo". Gracefully handle that.
  204. (match (store-path-hash-part path)
  205. (#f
  206. (leave (G_ "'~a' does not name a store item~%") path))
  207. ((? string? hash-part)
  208. (string-append %narinfo-cache-directory "/"
  209. (bytevector->base32-string (sha256 (string->utf8 cache-url)))
  210. "/" hash-part))))
  211. (define (cached-narinfo cache-url path)
  212. "Check locally if we have valid info about PATH coming from CACHE-URL.
  213. Return two values: a Boolean indicating whether we have valid cached info, and
  214. that info, which may be either #f (when PATH is unavailable) or the narinfo
  215. for PATH."
  216. (define now
  217. (current-time time-monotonic))
  218. (define cache-file
  219. (narinfo-cache-file cache-url path))
  220. (catch 'system-error
  221. (lambda ()
  222. (call-with-input-file cache-file
  223. (lambda (p)
  224. (match (read p)
  225. (('narinfo ('version 2)
  226. ('cache-uri cache-uri)
  227. ('date date) ('ttl ttl) ('value #f))
  228. ;; A cached negative lookup.
  229. (if (obsolete? date now ttl)
  230. (values #f #f)
  231. (values #t #f)))
  232. (('narinfo ('version 2)
  233. ('cache-uri cache-uri)
  234. ('date date) ('ttl ttl) ('value value))
  235. ;; A cached positive lookup
  236. (if (obsolete? date now ttl)
  237. (values #f #f)
  238. (values #t (string->narinfo value cache-uri))))
  239. (('narinfo ('version v) _ ...)
  240. (values #f #f))))))
  241. (lambda _
  242. (values #f #f))))
  243. (define (cache-narinfo! cache-url path narinfo ttl)
  244. "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the
  245. given TTL (a number of seconds or #f). NARINFO may be #f, in which case it
  246. indicates that PATH is unavailable at CACHE-URL."
  247. (define now
  248. (current-time time-monotonic))
  249. (define (cache-entry cache-uri narinfo)
  250. `(narinfo (version 2)
  251. (cache-uri ,cache-uri)
  252. (date ,(time-second now))
  253. (ttl ,(or ttl
  254. (if narinfo %narinfo-ttl %narinfo-negative-ttl)))
  255. (value ,(and=> narinfo narinfo->string))))
  256. (let ((file (narinfo-cache-file cache-url path)))
  257. (mkdir-p (dirname file))
  258. (with-atomic-file-output file
  259. (lambda (out)
  260. (write (cache-entry cache-url narinfo) out))))
  261. narinfo)
  262. (define (narinfo-request cache-url path)
  263. "Return an HTTP request for the narinfo of PATH at CACHE-URL."
  264. (let ((url (string-append cache-url "/" (store-path-hash-part path)
  265. ".narinfo"))
  266. (headers '((User-Agent . "GNU Guile"))))
  267. (build-request (string->uri url) #:method 'GET #:headers headers)))
  268. (define (at-most max-length lst)
  269. "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise
  270. return its MAX-LENGTH first elements and its tail."
  271. (let loop ((len 0)
  272. (lst lst)
  273. (result '()))
  274. (match lst
  275. (()
  276. (values (reverse result) '()))
  277. ((head . tail)
  278. (if (>= len max-length)
  279. (values (reverse result) lst)
  280. (loop (+ 1 len) tail (cons head result)))))))
  281. (define* (http-multiple-get base-uri proc seed requests
  282. #:key port (verify-certificate? #t)
  283. (open-connection guix:open-connection-for-uri)
  284. (keep-alive? #t)
  285. (batch-size 1000))
  286. "Send all of REQUESTS to the server at BASE-URI. Call PROC for each
  287. response, passing it the request object, the response, a port from which to
  288. read the response body, and the previous result, starting with SEED, à la
  289. 'fold'. Return the final result.
  290. When PORT is specified, use it as the initial connection on which HTTP
  291. requests are sent; otherwise call OPEN-CONNECTION to open a new connection for
  292. a URI. When KEEP-ALIVE? is false, close the connection port before
  293. returning."
  294. (let connect ((port port)
  295. (requests requests)
  296. (result seed))
  297. (define batch
  298. (at-most batch-size requests))
  299. ;; (format (current-error-port) "connecting (~a requests left)..."
  300. ;; (length requests))
  301. (let ((p (or port (open-connection base-uri
  302. #:verify-certificate?
  303. verify-certificate?))))
  304. ;; For HTTPS, P is not a file port and does not support 'setvbuf'.
  305. (when (file-port? p)
  306. (setvbuf p 'block (expt 2 16)))
  307. ;; Send BATCH in a row.
  308. ;; XXX: Do our own caching to work around inefficiencies when
  309. ;; communicating over TLS: <http://bugs.gnu.org/22966>.
  310. (let-values (((buffer get) (open-bytevector-output-port)))
  311. ;; Inherit the HTTP proxying property from P.
  312. (set-http-proxy-port?! buffer (http-proxy-port? p))
  313. (for-each (cut write-request <> buffer)
  314. batch)
  315. (put-bytevector p (get))
  316. (force-output p))
  317. ;; Now start processing responses.
  318. (let loop ((sent batch)
  319. (processed 0)
  320. (result result))
  321. (match sent
  322. (()
  323. (match (drop requests processed)
  324. (()
  325. (unless keep-alive?
  326. (close-port p))
  327. (reverse result))
  328. (remainder
  329. (connect p remainder result))))
  330. ((head tail ...)
  331. (let* ((resp (read-response p))
  332. (body (response-body-port resp))
  333. (result (proc head resp body result)))
  334. ;; The server can choose to stop responding at any time, in which
  335. ;; case we have to try again. Check whether that is the case.
  336. ;; Note that even upon "Connection: close", we can read from BODY.
  337. (match (assq 'connection (response-headers resp))
  338. (('connection 'close)
  339. (close-port p)
  340. (connect #f ;try again
  341. (drop requests (+ 1 processed))
  342. result))
  343. (_
  344. (loop tail (+ 1 processed) result)))))))))) ;keep going
  345. (define (read-to-eof port)
  346. "Read from PORT until EOF is reached. The data are discarded."
  347. (dump-port port (%make-void-port "w")))
  348. (define (narinfo-from-file file url)
  349. "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f
  350. if file doesn't exist, and the narinfo otherwise."
  351. (catch 'system-error
  352. (lambda ()
  353. (call-with-input-file file
  354. (cut read-narinfo <> url)))
  355. (lambda args
  356. (if (= ENOENT (system-error-errno args))
  357. #f
  358. (apply throw args)))))
  359. (define %unreachable-hosts
  360. ;; Set of names of unreachable hosts.
  361. (make-hash-table))
  362. (define* (open-connection-for-uri/maybe uri
  363. #:key
  364. fresh?
  365. (time %fetch-timeout))
  366. "Open a connection to URI via 'open-connection-for-uri/cached' and return a
  367. port to it, or, if connection failed, print a warning and return #f. Pass
  368. #:fresh? to 'open-connection-for-uri/cached'."
  369. (define host
  370. (uri-host uri))
  371. (catch #t
  372. (lambda ()
  373. (open-connection-for-uri/cached uri #:timeout time
  374. #:fresh? fresh?))
  375. (match-lambda*
  376. (('getaddrinfo-error error)
  377. (unless (hash-ref %unreachable-hosts host)
  378. (hash-set! %unreachable-hosts host #t) ;warn only once
  379. (warning (G_ "~a: host not found: ~a~%")
  380. host (gai-strerror error)))
  381. #f)
  382. (('system-error . args)
  383. (unless (hash-ref %unreachable-hosts host)
  384. (hash-set! %unreachable-hosts host #t)
  385. (warning (G_ "~a: connection failed: ~a~%") host
  386. (strerror
  387. (system-error-errno `(system-error ,@args)))))
  388. #f)
  389. (args
  390. (apply throw args)))))
  391. (define (fetch-narinfos url paths)
  392. "Retrieve all the narinfos for PATHS from the cache at URL and return them."
  393. (define update-progress!
  394. (let ((done 0)
  395. (total (length paths)))
  396. (lambda ()
  397. (display "\r\x1b[K" (current-error-port)) ;erase current line
  398. (force-output (current-error-port))
  399. (format (current-error-port)
  400. (G_ "updating substitutes from '~a'... ~5,1f%")
  401. url (* 100. (/ done total)))
  402. (set! done (+ 1 done)))))
  403. (define hash-part->path
  404. (let ((mapping (fold (lambda (path result)
  405. (vhash-cons (store-path-hash-part path) path
  406. result))
  407. vlist-null
  408. paths)))
  409. (lambda (hash)
  410. (match (vhash-assoc hash mapping)
  411. (#f #f)
  412. ((_ . path) path)))))
  413. (define (handle-narinfo-response request response port result)
  414. (let* ((code (response-code response))
  415. (len (response-content-length response))
  416. (cache (response-cache-control response))
  417. (ttl (and cache (assoc-ref cache 'max-age))))
  418. (update-progress!)
  419. ;; Make sure to read no more than LEN bytes since subsequent bytes may
  420. ;; belong to the next response.
  421. (if (= code 200) ; hit
  422. (let ((narinfo (read-narinfo port url #:size len)))
  423. (if (string=? (dirname (narinfo-path narinfo))
  424. (%store-prefix))
  425. (begin
  426. (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)
  427. (cons narinfo result))
  428. result))
  429. (let* ((path (uri-path (request-uri request)))
  430. (hash-part (basename
  431. (string-drop-right path 8)))) ;drop ".narinfo"
  432. (if len
  433. (get-bytevector-n port len)
  434. (read-to-eof port))
  435. (cache-narinfo! url (hash-part->path hash-part) #f
  436. (if (or (= 404 code) (= 202 code))
  437. ttl
  438. %narinfo-transient-error-ttl))
  439. result))))
  440. (define (do-fetch uri)
  441. (case (and=> uri uri-scheme)
  442. ((http https)
  443. ;; Note: Do not check HTTPS server certificates to avoid depending
  444. ;; on the X.509 PKI. We can do it because we authenticate
  445. ;; narinfos, which provides a much stronger guarantee.
  446. (let* ((requests (map (cut narinfo-request url <>) paths))
  447. (result (call-with-cached-connection uri
  448. (lambda (port)
  449. (if port
  450. (begin
  451. (update-progress!)
  452. (http-multiple-get uri
  453. handle-narinfo-response '()
  454. requests
  455. #:open-connection
  456. open-connection-for-uri/cached
  457. #:verify-certificate? #f
  458. #:port port))
  459. '()))
  460. open-connection-for-uri/maybe)))
  461. (newline (current-error-port))
  462. result))
  463. ((file #f)
  464. (let* ((base (string-append (uri-path uri) "/"))
  465. (files (map (compose (cut string-append base <> ".narinfo")
  466. store-path-hash-part)
  467. paths)))
  468. (filter-map (cut narinfo-from-file <> url) files)))
  469. (else
  470. (leave (G_ "~s: unsupported server URI scheme~%")
  471. (if uri (uri-scheme uri) url)))))
  472. (do-fetch (string->uri url)))
  473. (define (lookup-narinfos cache paths)
  474. "Return the narinfos for PATHS, invoking the server at CACHE when no
  475. information is available locally."
  476. (let-values (((cached missing)
  477. (fold2 (lambda (path cached missing)
  478. (let-values (((valid? value)
  479. (cached-narinfo cache path)))
  480. (if valid?
  481. (if value
  482. (values (cons value cached) missing)
  483. (values cached missing))
  484. (values cached (cons path missing)))))
  485. '()
  486. '()
  487. paths)))
  488. (if (null? missing)
  489. cached
  490. (let ((missing (fetch-narinfos cache missing)))
  491. (append cached (or missing '()))))))
  492. (define (lookup-narinfos/diverse caches paths authorized?)
  493. "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.
  494. That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next
  495. cache, and so on.
  496. Return a list of narinfos for PATHS or a subset thereof. The returned
  497. narinfos are either AUTHORIZED?, or they claim a hash that matches an
  498. AUTHORIZED? narinfo."
  499. (define (select-hit result)
  500. (lambda (path)
  501. (match (vhash-fold* cons '() path result)
  502. ((one)
  503. one)
  504. ((several ..1)
  505. (let ((authorized (find authorized? (reverse several))))
  506. (and authorized
  507. (find (cut equivalent-narinfo? <> authorized)
  508. several)))))))
  509. (let loop ((caches caches)
  510. (paths paths)
  511. (result vlist-null) ;path->narinfo vhash
  512. (hits '())) ;paths
  513. (match paths
  514. (() ;we're done
  515. ;; Now iterate on all the HITS, and return exactly one match for each
  516. ;; hit: the first narinfo that is authorized, or that has the same hash
  517. ;; as an authorized narinfo, in the order of CACHES.
  518. (filter-map (select-hit result) hits))
  519. (_
  520. (match caches
  521. ((cache rest ...)
  522. (let* ((narinfos (lookup-narinfos cache paths))
  523. (definite (map narinfo-path (filter authorized? narinfos)))
  524. (missing (lset-difference string=? paths definite))) ;XXX: perf
  525. (loop rest missing
  526. (fold vhash-cons result
  527. (map narinfo-path narinfos) narinfos)
  528. (append definite hits))))
  529. (() ;that's it
  530. (filter-map (select-hit result) hits)))))))
  531. (define (lookup-narinfo caches path authorized?)
  532. "Return the narinfo for PATH in CACHES, or #f when no substitute for PATH
  533. was found."
  534. (match (lookup-narinfos/diverse caches (list path) authorized?)
  535. ((answer) answer)
  536. (_ #f)))
  537. (define (cached-narinfo-expiration-time file)
  538. "Return the expiration time for FILE, which is a cached narinfo."
  539. (catch 'system-error
  540. (lambda ()
  541. (call-with-input-file file
  542. (lambda (port)
  543. (match (read port)
  544. (('narinfo ('version 2) ('cache-uri uri)
  545. ('date date) ('ttl ttl) ('value #f))
  546. (+ date ttl))
  547. (('narinfo ('version 2) ('cache-uri uri)
  548. ('date date) ('ttl ttl) ('value value))
  549. (+ date ttl))
  550. (x
  551. 0)))))
  552. (lambda args
  553. ;; FILE may have been deleted.
  554. 0)))
  555. (define (narinfo-cache-directories directory)
  556. "Return the list of narinfo cache directories (one per cache URL.)"
  557. (map (cut string-append directory "/" <>)
  558. (scandir %narinfo-cache-directory
  559. (lambda (item)
  560. (and (not (member item '("." "..")))
  561. (file-is-directory?
  562. (string-append %narinfo-cache-directory
  563. "/" item)))))))
  564. (define* (cached-narinfo-files #:optional
  565. (directory %narinfo-cache-directory))
  566. "Return the list of cached narinfo files under DIRECTORY."
  567. (append-map (lambda (directory)
  568. (map (cut string-append directory "/" <>)
  569. (scandir directory
  570. (lambda (file)
  571. (= (string-length file) 32)))))
  572. (narinfo-cache-directories directory)))
  573. (define-syntax with-networking
  574. (syntax-rules ()
  575. "Catch DNS lookup errors and TLS errors and gracefully exit."
  576. ;; Note: no attempt is made to catch other networking errors, because DNS
  577. ;; lookup errors are typically the first one, and because other errors are
  578. ;; a subset of `system-error', which is harder to filter.
  579. ((_ exp ...)
  580. (catch #t
  581. (lambda () exp ...)
  582. (match-lambda*
  583. (('getaddrinfo-error error)
  584. (leave (G_ "host name lookup error: ~a~%")
  585. (gai-strerror error)))
  586. (('gnutls-error error proc . rest)
  587. (let ((error->string (module-ref (resolve-interface '(gnutls))
  588. 'error->string)))
  589. (leave (G_ "TLS error in procedure '~a': ~a~%")
  590. proc (error->string error))))
  591. (args
  592. (apply throw args)))))))
  593. ;;;
  594. ;;; Help.
  595. ;;;
  596. (define (show-help)
  597. (display (G_ "Usage: guix substitute [OPTION]...
  598. Internal tool to substitute a pre-built binary to a local build.\n"))
  599. (display (G_ "
  600. --query report on the availability of substitutes for the
  601. store file names passed on the standard input"))
  602. (display (G_ "
  603. --substitute STORE-FILE DESTINATION
  604. download STORE-FILE and store it as a Nar in file
  605. DESTINATION"))
  606. (newline)
  607. (display (G_ "
  608. -h, --help display this help and exit"))
  609. (display (G_ "
  610. -V, --version display version information and exit"))
  611. (newline)
  612. (show-bug-report-information))
  613. ;;;
  614. ;;; Daemon/substituter protocol.
  615. ;;;
  616. (define (display-narinfo-data narinfo)
  617. "Write to the current output port the contents of NARINFO in the format
  618. expected by the daemon."
  619. (format #t "~a\n~a\n~a\n"
  620. (narinfo-path narinfo)
  621. (or (and=> (narinfo-deriver narinfo)
  622. (cute string-append (%store-prefix) "/" <>))
  623. "")
  624. (length (narinfo-references narinfo)))
  625. (for-each (cute format #t "~a/~a~%" (%store-prefix) <>)
  626. (narinfo-references narinfo))
  627. (let-values (((uri compression file-size) (narinfo-best-uri narinfo)))
  628. (format #t "~a\n~a\n"
  629. (or file-size 0)
  630. (or (narinfo-size narinfo) 0))))
  631. (define* (process-query command
  632. #:key cache-urls acl)
  633. "Reply to COMMAND, a query as written by the daemon to this process's
  634. standard input. Use ACL as the access-control list against which to check
  635. authorized substitutes."
  636. (define valid?
  637. (if (%allow-unauthenticated-substitutes?)
  638. (begin
  639. (warn-about-missing-authentication)
  640. (const #t))
  641. (lambda (obj)
  642. (valid-narinfo? obj acl))))
  643. (match (string-tokenize command)
  644. (("have" paths ..1)
  645. ;; Return the subset of PATHS available in CACHE-URLS.
  646. (let ((substitutable (lookup-narinfos/diverse cache-urls paths valid?)))
  647. (for-each (lambda (narinfo)
  648. (format #t "~a~%" (narinfo-path narinfo)))
  649. substitutable)
  650. (newline)))
  651. (("info" paths ..1)
  652. ;; Reply info about PATHS if it's in CACHE-URLS.
  653. (let ((substitutable (lookup-narinfos/diverse cache-urls paths valid?)))
  654. (for-each display-narinfo-data substitutable)
  655. (newline)))
  656. (wtf
  657. (error "unknown `--query' command" wtf))))
  658. (define %max-cached-connections
  659. ;; Maximum number of connections kept in cache by
  660. ;; 'open-connection-for-uri/cached'.
  661. 16)
  662. (define open-connection-for-uri/cached
  663. (let ((cache '()))
  664. (lambda* (uri #:key fresh? timeout verify-certificate?)
  665. "Return a connection for URI, possibly reusing a cached connection.
  666. When FRESH? is true, delete any cached connections for URI and open a new one.
  667. Return #f if URI's scheme is 'file' or #f.
  668. When true, TIMEOUT is the maximum number of milliseconds to wait for
  669. connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS
  670. server certificates."
  671. (define host (uri-host uri))
  672. (define scheme (uri-scheme uri))
  673. (define key (list host scheme (uri-port uri)))
  674. (and (not (memq scheme '(file #f)))
  675. (match (assoc-ref cache key)
  676. (#f
  677. ;; Open a new connection to URI and evict old entries from
  678. ;; CACHE, if any.
  679. (let-values (((socket)
  680. (guix:open-connection-for-uri
  681. uri
  682. #:verify-certificate? verify-certificate?
  683. #:timeout timeout))
  684. ((new-cache evicted)
  685. (at-most (- %max-cached-connections 1) cache)))
  686. (for-each (match-lambda
  687. ((_ . port)
  688. (false-if-exception (close-port port))))
  689. evicted)
  690. (set! cache (alist-cons key socket new-cache))
  691. socket))
  692. (socket
  693. (if (or fresh? (port-closed? socket))
  694. (begin
  695. (false-if-exception (close-port socket))
  696. (set! cache (alist-delete key cache))
  697. (open-connection-for-uri/cached uri #:timeout timeout
  698. #:verify-certificate?
  699. verify-certificate?))
  700. (begin
  701. ;; Drain input left from the previous use.
  702. (drain-input socket)
  703. socket))))))))
  704. (define* (call-with-cached-connection uri proc
  705. #:optional
  706. (open-connection
  707. open-connection-for-uri/cached))
  708. (let ((port (open-connection uri)))
  709. (catch #t
  710. (lambda ()
  711. (proc port))
  712. (lambda (key . args)
  713. ;; If PORT was cached and the server closed the connection in the
  714. ;; meantime, we get EPIPE. In that case, open a fresh connection and
  715. ;; retry. We might also get 'bad-response or a similar exception from
  716. ;; (web response) later on, once we've sent the request, or a
  717. ;; ERROR/INVALID-SESSION from GnuTLS.
  718. (if (or (and (eq? key 'system-error)
  719. (= EPIPE (system-error-errno `(,key ,@args))))
  720. (and (eq? key 'gnutls-error)
  721. (eq? (first args) error/invalid-session))
  722. (memq key '(bad-response bad-header bad-header-component)))
  723. (proc (open-connection uri #:fresh? #t))
  724. (apply throw key args))))))
  725. (define-syntax-rule (with-cached-connection uri port exp ...)
  726. "Bind PORT with EXP... to a socket connected to URI."
  727. (call-with-cached-connection uri (lambda (port) exp ...)))
  728. (define* (process-substitution store-item destination
  729. #:key cache-urls acl
  730. deduplicate? print-build-trace?)
  731. "Substitute STORE-ITEM (a store file name) from CACHE-URLS, and write it to
  732. DESTINATION as a nar file. Verify the substitute against ACL, and verify its
  733. hash against what appears in the narinfo. When DEDUPLICATE? is true, and if
  734. DESTINATION is in the store, deduplicate its files. Print a status line on
  735. the current output port."
  736. (define narinfo
  737. (lookup-narinfo cache-urls store-item
  738. (if (%allow-unauthenticated-substitutes?)
  739. (const #t)
  740. (cut valid-narinfo? <> acl))))
  741. (define destination-in-store?
  742. (string-prefix? (string-append (%store-prefix) "/")
  743. destination))
  744. (define (dump-file/deduplicate* . args)
  745. ;; Make sure deduplication looks at the right store (necessary in test
  746. ;; environments).
  747. (apply dump-file/deduplicate
  748. (append args (list #:store (%store-prefix)))))
  749. (unless narinfo
  750. (leave (G_ "no valid substitute for '~a'~%")
  751. store-item))
  752. (let-values (((uri compression file-size)
  753. (narinfo-best-uri narinfo)))
  754. (unless print-build-trace?
  755. (format (current-error-port)
  756. (G_ "Downloading ~a...~%") (uri->string uri)))
  757. (let*-values (((raw download-size)
  758. ;; 'guix publish' without '--cache' doesn't specify a
  759. ;; Content-Length, so DOWNLOAD-SIZE is #f in this case.
  760. (with-cached-connection uri port
  761. (fetch uri #:buffered? #f #:timeout? #f
  762. #:port port
  763. #:keep-alive? #t)))
  764. ((progress)
  765. (let* ((dl-size (or download-size
  766. (and (equal? compression "none")
  767. (narinfo-size narinfo))))
  768. (reporter (if print-build-trace?
  769. (progress-reporter/trace
  770. destination
  771. (uri->string uri) dl-size
  772. (current-error-port))
  773. (progress-reporter/file
  774. (uri->string uri) dl-size
  775. (current-error-port)
  776. #:abbreviation nar-uri-abbreviation))))
  777. ;; Keep RAW open upon completion so we can later reuse
  778. ;; the underlying connection.
  779. (progress-report-port reporter raw #:close? #f)))
  780. ((input pids)
  781. ;; NOTE: This 'progress' port of current process will be
  782. ;; closed here, while the child process doing the
  783. ;; reporting will close it upon exit.
  784. (decompressed-port (string->symbol compression)
  785. progress))
  786. ;; Compute the actual nar hash as we read it.
  787. ((algorithm expected)
  788. (narinfo-hash-algorithm+value narinfo))
  789. ((hashed get-hash)
  790. (open-hash-input-port algorithm input)))
  791. ;; Unpack the Nar at INPUT into DESTINATION.
  792. (restore-file hashed destination
  793. #:dump-file (if (and destination-in-store?
  794. deduplicate?)
  795. dump-file/deduplicate*
  796. dump-file))
  797. (close-port hashed)
  798. (close-port input)
  799. ;; Wait for the reporter to finish.
  800. (every (compose zero? cdr waitpid) pids)
  801. ;; Skip a line after what 'progress-reporter/file' printed, and another
  802. ;; one to visually separate substitutions.
  803. (display "\n\n" (current-error-port))
  804. ;; Check whether we got the data announced in NARINFO.
  805. (let ((actual (get-hash)))
  806. (if (bytevector=? actual expected)
  807. ;; Tell the daemon that we're done.
  808. (format (current-output-port) "success ~a ~a~%"
  809. (narinfo-hash narinfo) (narinfo-size narinfo))
  810. ;; The actual data has a different hash than that in NARINFO.
  811. (format (current-output-port) "hash-mismatch ~a ~a ~a~%"
  812. (hash-algorithm-name algorithm)
  813. (bytevector->nix-base32-string expected)
  814. (bytevector->nix-base32-string actual)))))))
  815. ;;;
  816. ;;; Entry point.
  817. ;;;
  818. (define (check-acl-initialized)
  819. "Warn if the ACL is uninitialized."
  820. (define (singleton? acl)
  821. ;; True if ACL contains just the user's public key.
  822. (and (file-exists? %public-key-file)
  823. (let ((key (call-with-input-file %public-key-file
  824. (compose string->canonical-sexp
  825. read-string))))
  826. (match acl
  827. ((thing)
  828. (equal? (canonical-sexp->string thing)
  829. (canonical-sexp->string key)))
  830. (_
  831. #f)))))
  832. (let ((acl (acl->public-keys (current-acl))))
  833. (when (or (null? acl) (singleton? acl))
  834. (warning (G_ "ACL for archive imports seems to be uninitialized, \
  835. substitutes may be unavailable\n")))))
  836. (define (daemon-options)
  837. "Return a list of name/value pairs denoting build daemon options."
  838. (define %not-newline
  839. (char-set-complement (char-set #\newline)))
  840. (match (getenv "_NIX_OPTIONS")
  841. (#f ;should not happen when called by the daemon
  842. '())
  843. (newline-separated
  844. ;; Here we get something of the form "OPTION1=VALUE1\nOPTION2=VALUE2\n".
  845. (filter-map (lambda (option=value)
  846. (match (string-index option=value #\=)
  847. (#f ;invalid option setting
  848. #f)
  849. (equal-sign
  850. (cons (string-take option=value equal-sign)
  851. (string-drop option=value (+ 1 equal-sign))))))
  852. (string-tokenize newline-separated %not-newline)))))
  853. (define (find-daemon-option option)
  854. "Return the value of build daemon option OPTION, or #f if it could not be
  855. found."
  856. (assoc-ref (daemon-options) option))
  857. (define %default-substitute-urls
  858. (match (and=> (or (find-daemon-option "untrusted-substitute-urls") ;client
  859. (find-daemon-option "substitute-urls")) ;admin
  860. string-tokenize)
  861. ((urls ...)
  862. urls)
  863. (#f
  864. ;; This can only happen when this script is not invoked by the
  865. ;; daemon.
  866. '("http://ci.guix.gnu.org"))))
  867. ;; In order to prevent using large number of discovered local substitute
  868. ;; servers, limit the local substitute urls list size.
  869. (define %max-substitute-urls 50)
  870. (define* (randomize-substitute-urls urls
  871. #:key
  872. (max %max-substitute-urls))
  873. "Return a list containing MAX urls from URLS, picked randomly. If URLS list
  874. is shorter than MAX elements, then it is directly returned."
  875. (define (random-item list)
  876. (list-ref list (random (length list))))
  877. (if (<= (length urls) max)
  878. urls
  879. (let loop ((res '())
  880. (urls urls))
  881. (if (eq? (length res) max)
  882. res
  883. (let ((url (random-item urls)))
  884. (loop (cons url res) (delete url urls)))))))
  885. (define %local-substitute-urls
  886. ;; If the following option is passed to the daemon, use the substitutes list
  887. ;; provided by "guix discover" process.
  888. (let* ((option (find-daemon-option "discover"))
  889. (discover? (and option (string=? option "yes"))))
  890. (if discover?
  891. (randomize-substitute-urls (read-substitute-urls))
  892. '())))
  893. (define substitute-urls
  894. ;; List of substitute URLs.
  895. (make-parameter (append %local-substitute-urls
  896. %default-substitute-urls)))
  897. (define (client-terminal-columns)
  898. "Return the number of columns in the client's terminal, if it is known, or a
  899. default value."
  900. (or (and=> (or (find-daemon-option "untrusted-terminal-columns")
  901. (find-daemon-option "terminal-columns"))
  902. (lambda (str)
  903. (let ((number (string->number str)))
  904. (and number (max 20 (- number 1))))))
  905. 80))
  906. (define (validate-uri uri)
  907. (unless (string->uri uri)
  908. (leave (G_ "~a: invalid URI~%") uri)))
  909. (define %error-to-file-descriptor-4?
  910. ;; Whether to direct 'current-error-port' to file descriptor 4 like
  911. ;; 'guix-daemon' expects.
  912. (make-parameter #t))
  913. (define-command (guix-substitute . args)
  914. (category internal)
  915. (synopsis "implement the build daemon's substituter protocol")
  916. (define print-build-trace?
  917. (match (or (find-daemon-option "untrusted-print-extended-build-trace")
  918. (find-daemon-option "print-extended-build-trace"))
  919. (#f #f)
  920. ((= string->number number) (> number 0))
  921. (_ #f)))
  922. (define deduplicate?
  923. (find-daemon-option "deduplicate"))
  924. ;; The daemon's agent code opens file descriptor 4 for us and this is where
  925. ;; stderr should go.
  926. (parameterize ((current-error-port (if (%error-to-file-descriptor-4?)
  927. (fdopen 4 "wl")
  928. (current-error-port))))
  929. ;; Redirect diagnostics to file descriptor 4 as well.
  930. (guix-warning-port (current-error-port))
  931. (mkdir-p %narinfo-cache-directory)
  932. (maybe-remove-expired-cache-entries %narinfo-cache-directory
  933. cached-narinfo-files
  934. #:entry-expiration
  935. cached-narinfo-expiration-time
  936. #:cleanup-period
  937. %narinfo-expired-cache-entry-removal-delay)
  938. (check-acl-initialized)
  939. ;; Sanity-check SUBSTITUTE-URLS so we can provide a meaningful error
  940. ;; message.
  941. (for-each validate-uri (substitute-urls))
  942. ;; Attempt to install the client's locale so that messages are suitably
  943. ;; translated. LC_CTYPE must be a UTF-8 locale; it's the case by default
  944. ;; so don't change it.
  945. (match (or (find-daemon-option "untrusted-locale")
  946. (find-daemon-option "locale"))
  947. (#f #f)
  948. (locale (false-if-exception (setlocale LC_MESSAGES locale))))
  949. (catch 'system-error
  950. (lambda ()
  951. (set-thread-name "guix substitute"))
  952. (const #t)) ;GNU/Hurd lacks 'prctl'
  953. (with-networking
  954. (with-error-handling ; for signature errors
  955. (match args
  956. (("--query")
  957. (let ((acl (current-acl)))
  958. (let loop ((command (read-line)))
  959. (or (eof-object? command)
  960. (begin
  961. (process-query command
  962. #:cache-urls (substitute-urls)
  963. #:acl acl)
  964. (loop (read-line)))))))
  965. (("--substitute")
  966. ;; Download STORE-PATH and store it as a Nar in file DESTINATION.
  967. ;; Specify the number of columns of the terminal so the progress
  968. ;; report displays nicely.
  969. (parameterize ((current-terminal-columns (client-terminal-columns)))
  970. (let loop ()
  971. (match (read-line)
  972. ((? eof-object?)
  973. #t)
  974. ((= string-tokenize ("substitute" store-path destination))
  975. (process-substitution store-path destination
  976. #:cache-urls (substitute-urls)
  977. #:acl (current-acl)
  978. #:deduplicate? deduplicate?
  979. #:print-build-trace?
  980. print-build-trace?)
  981. (loop))))))
  982. ((or ("-V") ("--version"))
  983. (show-version-and-exit "guix substitute"))
  984. (("--help")
  985. (show-help))
  986. (opts
  987. (leave (G_ "~a: unrecognized options~%") opts)))))))
  988. ;;; Local Variables:
  989. ;;; eval: (put 'with-timeout 'scheme-indent-function 1)
  990. ;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)
  991. ;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1)
  992. ;;; End:
  993. ;;; substitute.scm ends here