substitute.scm 45 KB

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