graft.scm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2014, 2015, 2016, 2018 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2016, 2021 Mark H Weaver <mhw@netris.org>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (guix build graft)
  20. #:use-module (guix build utils)
  21. #:use-module (guix build debug-link)
  22. #:use-module (rnrs bytevectors)
  23. #:use-module (ice-9 vlist)
  24. #:use-module (ice-9 match)
  25. #:use-module (ice-9 threads)
  26. #:use-module (ice-9 binary-ports)
  27. #:use-module (srfi srfi-1) ; list library
  28. #:use-module (srfi srfi-26) ; cut and cute
  29. #:export (replace-store-references
  30. rewrite-directory
  31. graft))
  32. ;;; Commentary:
  33. ;;;
  34. ;;; This module supports "grafts". Grafting a directory means rewriting it,
  35. ;;; with references to some specific items replaced by references to other
  36. ;;; store items---the grafts.
  37. ;;;
  38. ;;; This method is used to provide fast security updates as only the leaves of
  39. ;;; the dependency graph need to be grafted, even when the security updates
  40. ;;; affect a core component such as Bash or libc. It is based on the idea of
  41. ;;; 'replace-dependency' implemented by Shea Levy in Nixpkgs.
  42. ;;;
  43. ;;; Code:
  44. (define-constant hash-length %store-hash-string-length)
  45. (define nix-base32-char?
  46. (cute char-set-contains?
  47. ;; ASCII digits and lower case letters except e o t u
  48. (string->char-set "0123456789abcdfghijklmnpqrsvwxyz")
  49. <>))
  50. (define (nix-base32-char-or-nul? c)
  51. "Return true if C is a nix-base32 character or NUL, otherwise return false."
  52. (or (nix-base32-char? c)
  53. (char=? c #\nul)))
  54. (define (possible-utf16-hash? buffer i w)
  55. "Return true if (I - W) is large enough to hold a UTF-16 encoded
  56. nix-base32 hash and if BUFFER contains NULs in all positions where NULs
  57. are to be expected in a UTF-16 encoded hash+dash pattern whose dash is
  58. found at position I. Otherwise, return false."
  59. (and (<= (* 2 hash-length) (- i w))
  60. (let loop ((j (+ 1 (- i (* 2 hash-length)))))
  61. (or (>= j i)
  62. (and (zero? (bytevector-u8-ref buffer j))
  63. (loop (+ j 2)))))))
  64. (define (possible-utf32-hash? buffer i w)
  65. "Return true if (I - W) is large enough to hold a UTF-32 encoded
  66. nix-base32 hash and if BUFFER contains NULs in all positions where NULs
  67. are to be expected in a UTF-32 encoded hash+dash pattern whose dash is
  68. found at position I. Otherwise, return false."
  69. (and (<= (* 4 hash-length) (- i w))
  70. (let loop ((j (+ 1 (- i (* 4 hash-length)))))
  71. (or (>= j i)
  72. (and (zero? (bytevector-u8-ref buffer j))
  73. (zero? (bytevector-u8-ref buffer (+ j 1)))
  74. (zero? (bytevector-u8-ref buffer (+ j 2)))
  75. (loop (+ j 4)))))))
  76. (define (insert-nuls char-size bv)
  77. "Given a bytevector BV, return a bytevector containing the same bytes but
  78. with (CHAR-SIZE - 1) NULs inserted between every two adjacent bytes from BV.
  79. For example, (insert-nuls 4 #u8(1 2 3)) => #u8(1 0 0 0 2 0 0 0 3)."
  80. (if (= char-size 1)
  81. bv
  82. (let* ((len (bytevector-length bv))
  83. (bv* (make-bytevector (+ 1 (* char-size
  84. (- len 1)))
  85. 0)))
  86. (let loop ((i 0))
  87. (when (< i len)
  88. (bytevector-u8-set! bv* (* i char-size)
  89. (bytevector-u8-ref bv i))
  90. (loop (+ i 1))))
  91. bv*)))
  92. (define* (replace-store-references input output replacement-table
  93. #:optional (store (%store-directory)))
  94. "Read data from INPUT, replacing store references according to
  95. REPLACEMENT-TABLE, and writing the result to OUTPUT. REPLACEMENT-TABLE is a
  96. vhash that maps strings (original hashes) to bytevectors (replacement strings
  97. comprising the replacement hash, a dash, and a string).
  98. Note: We use string keys to work around the fact that guile-2.0 hashes all
  99. bytevectors to the same value."
  100. (define (lookup-replacement s)
  101. (match (vhash-assoc s replacement-table)
  102. ((origin . replacement)
  103. replacement)
  104. (#f #f)))
  105. (define (optimize-u8-predicate pred)
  106. (cute vector-ref
  107. (list->vector (map pred (iota 256)))
  108. <>))
  109. (define nix-base32-byte-or-nul?
  110. (optimize-u8-predicate
  111. (compose nix-base32-char-or-nul?
  112. integer->char)))
  113. (define (dash? byte) (= byte 45))
  114. (define request-size (expt 2 20)) ; 1 MiB
  115. ;; We scan the file for the following 33-byte pattern: 32 bytes of
  116. ;; nix-base32 characters followed by a dash. When we find such a pattern
  117. ;; whose hash is in REPLACEMENT-TABLE, we perform the required rewrite and
  118. ;; continue scanning.
  119. ;;
  120. ;; To support UTF-16 and UTF-32 store references, the 33 bytes comprising
  121. ;; this hash+dash pattern may optionally be interspersed by extra NUL bytes.
  122. ;; This simple approach works because the characters we are looking for are
  123. ;; restricted to ASCII. UTF-16 hashes are interspersed with single NUL
  124. ;; bytes ("\0"), and UTF-32 hashes are interspersed with triplets of NULs
  125. ;; ("\0\0\0"). Note that we require NULs to be present only *between* the
  126. ;; other bytes, and not at either end, in order to be insensitive to byte
  127. ;; order.
  128. ;;
  129. ;; To accommodate large files, we do not read the entire file at once, but
  130. ;; instead work on buffers of up to REQUEST-SIZE bytes. To ensure that
  131. ;; every hash+dash pattern appears in its entirety in at least one buffer,
  132. ;; adjacent buffers must overlap by one byte less than the maximum size of a
  133. ;; hash+dash pattern. We accomplish this by "ungetting" a suffix of each
  134. ;; buffer before reading the next buffer, unless we know that we've reached
  135. ;; the end-of-file.
  136. (let ((buffer (make-bytevector request-size)))
  137. (define-syntax-rule (byte-at i)
  138. (bytevector-u8-ref buffer i))
  139. (let outer-loop ()
  140. (match (get-bytevector-n! input buffer 0 request-size)
  141. ((? eof-object?) 'done)
  142. (end
  143. (define (scan-from i w)
  144. ;; Scan the buffer for dashes that might be preceded by nix hashes,
  145. ;; where I is the minimum position where such a dash might be
  146. ;; found, and W is the number of bytes in the buffer that have been
  147. ;; written so far. We assume that I - W >= HASH-LENGTH.
  148. ;;
  149. ;; The key optimization here is that whenever we find a byte at
  150. ;; position I that cannot occur within a nix hash (because it's
  151. ;; neither a nix-base32 character nor NUL), we can infer that the
  152. ;; earliest position where the next hash could start is at I + 1,
  153. ;; and therefore the earliest position for the following dash is
  154. ;; (+ I 1 HASH-LENGTH), which is I + 33.
  155. ;;
  156. ;; Since nix-base32-or-nul characters comprise only about 1/8 of
  157. ;; the 256 possible byte values, and exclude some of the most
  158. ;; common letters in English text (e t o u), we can advance 33
  159. ;; positions much of the time.
  160. (if (< i end)
  161. (let ((byte (byte-at i)))
  162. (cond ((dash? byte)
  163. (found-dash i w))
  164. ((nix-base32-byte-or-nul? byte)
  165. (scan-from (+ i 1) w))
  166. (else
  167. (not-part-of-hash i w))))
  168. (finish-buffer i w)))
  169. (define (not-part-of-hash i w)
  170. ;; Position I is known to not be within a nix hash that we must
  171. ;; rewrite. Therefore, the earliest position where the next hash
  172. ;; might start is I + 1, and therefore the earliest position of
  173. ;; the following dash is (+ I 1 HASH-LENGTH).
  174. (scan-from (+ i 1 hash-length) w))
  175. (define (found-dash i w)
  176. ;; We know that there is a dash '-' at position I, and that
  177. ;; I - W >= HASH-LENGTH. The immediately preceding bytes *might*
  178. ;; contain a nix-base32 hash, but that is not yet known. Here,
  179. ;; we rule out all but one possible encoding (ASCII, UTF-16,
  180. ;; UTF-32) by counting how many NULs precede the dash.
  181. (cond ((not (zero? (byte-at (- i 1))))
  182. ;; The dash is *not* preceded by a NUL, therefore it
  183. ;; cannot possibly be a UTF-16 or UTF-32 hash. Proceed
  184. ;; to check for an ASCII hash.
  185. (found-possible-hash 1 i w))
  186. ((not (zero? (byte-at (- i 2))))
  187. ;; The dash is preceded by exactly one NUL, therefore it
  188. ;; cannot be an ASCII or UTF-32 hash. Proceed to check
  189. ;; for a UTF-16 hash.
  190. (if (possible-utf16-hash? buffer i w)
  191. (found-possible-hash 2 i w)
  192. (not-part-of-hash i w)))
  193. (else
  194. ;; The dash is preceded by at least two NULs, therefore
  195. ;; it cannot be an ASCII or UTF-16 hash. Proceed to
  196. ;; check for a UTF-32 hash.
  197. (if (possible-utf32-hash? buffer i w)
  198. (found-possible-hash 4 i w)
  199. (not-part-of-hash i w)))))
  200. (define (found-possible-hash char-size i w)
  201. ;; We know that there is a dash '-' at position I, that
  202. ;; I - W >= CHAR-SIZE * HASH-LENGTH, and that the only
  203. ;; possible encoding for the preceding hash is as indicated by
  204. ;; CHAR-SIZE. Here we check to see if the given hash is in
  205. ;; REPLACEMENT-TABLE, and if so, we perform the required
  206. ;; rewrite.
  207. (let* ((hash (string-tabulate
  208. (lambda (j)
  209. (integer->char
  210. (byte-at (- i (* char-size
  211. (- hash-length j))))))
  212. hash-length))
  213. (replacement* (lookup-replacement hash))
  214. (replacement (and replacement*
  215. (insert-nuls char-size replacement*))))
  216. (cond
  217. ((not replacement)
  218. (not-part-of-hash i w))
  219. (else
  220. ;; We've found a hash that needs to be replaced.
  221. ;; First, write out all bytes preceding the hash
  222. ;; that have not yet been written.
  223. (put-bytevector output buffer w
  224. (- i (* char-size hash-length) w))
  225. ;; Now write the replacement string.
  226. (put-bytevector output replacement)
  227. ;; Now compute the new values of W and I and continue.
  228. (let ((w (+ (- i (* char-size hash-length))
  229. (bytevector-length replacement))))
  230. (scan-from (+ w hash-length) w))))))
  231. (define (finish-buffer i w)
  232. ;; We have finished scanning the buffer. Now we determine how many
  233. ;; bytes have not yet been written, and how many bytes to "unget".
  234. ;; If END is less than REQUEST-SIZE then we read less than we asked
  235. ;; for, which indicates that we are at EOF, so we needn't unget
  236. ;; anything. Otherwise, we unget up to (* 4 HASH-LENGTH) bytes.
  237. ;; However, we must be careful not to unget bytes that have already
  238. ;; been written, because that would cause them to be written again
  239. ;; from the next buffer. In practice, this case occurs when a
  240. ;; replacement is made near or beyond the end of the buffer. When
  241. ;; REPLACEMENT went beyond END, we consume the extra bytes from
  242. ;; INPUT.
  243. (if (> w end)
  244. (get-bytevector-n! input buffer 0 (- w end))
  245. (let* ((unwritten (- end w))
  246. (unget-size (if (= end request-size)
  247. (min (* 4 hash-length)
  248. unwritten)
  249. 0))
  250. (write-size (- unwritten unget-size)))
  251. (put-bytevector output buffer w write-size)
  252. (unget-bytevector input buffer (+ w write-size)
  253. unget-size)))
  254. (outer-loop))
  255. (scan-from hash-length 0))))))
  256. (define (rename-matching-files directory mapping)
  257. "Apply MAPPING to the names of all the files in DIRECTORY, where MAPPING is
  258. a list of store file name pairs."
  259. (let* ((mapping (map (match-lambda
  260. ((source . target)
  261. (cons (basename source) (basename target))))
  262. mapping))
  263. (matches (find-files directory
  264. (lambda (file stat)
  265. (assoc-ref mapping (basename file)))
  266. #:directories? #t)))
  267. ;; XXX: This is not quite correct: if MAPPING contains "foo", and
  268. ;; DIRECTORY contains "bar/foo/foo", we first rename "bar/foo" and then
  269. ;; "bar/foo/foo" no longer exists so we fail. Oh well, surely that's good
  270. ;; enough!
  271. (for-each (lambda (file)
  272. (let ((target (assoc-ref mapping (basename file))))
  273. (rename-file file
  274. (string-append (dirname file) "/" target))))
  275. matches)))
  276. (define (exit-on-exception proc)
  277. "Return a procedure that wraps PROC so that 'primitive-exit' is called when
  278. an exception is caught."
  279. (lambda (arg)
  280. (catch #t
  281. (lambda ()
  282. (proc arg))
  283. (lambda (key . args)
  284. ;; Since ports are not thread-safe as of Guile 2.0, reopen stderr.
  285. (let ((port (fdopen 2 "w0")))
  286. (print-exception port #f key args)
  287. (primitive-exit 1))))))
  288. ;; We need this as long as we support Guile < 2.0.13.
  289. (define* (mkdir-p* dir #:optional (mode #o755))
  290. "This is a variant of 'mkdir-p' that works around
  291. <http://bugs.gnu.org/24659> by passing MODE explicitly in each 'mkdir' call."
  292. (define absolute?
  293. (string-prefix? "/" dir))
  294. (define not-slash
  295. (char-set-complement (char-set #\/)))
  296. (let loop ((components (string-tokenize dir not-slash))
  297. (root (if absolute?
  298. ""
  299. ".")))
  300. (match components
  301. ((head tail ...)
  302. (let ((path (string-append root "/" head)))
  303. (catch 'system-error
  304. (lambda ()
  305. (mkdir path mode)
  306. (loop tail path))
  307. (lambda args
  308. (if (= EEXIST (system-error-errno args))
  309. (loop tail path)
  310. (apply throw args))))))
  311. (() #t))))
  312. (define* (rewrite-directory directory output mapping
  313. #:optional (store (%store-directory)))
  314. "Copy DIRECTORY to OUTPUT, replacing strings according to MAPPING, a list of
  315. file name pairs."
  316. (define hash-mapping
  317. ;; List of hash/replacement pairs, where the hash is a nix-base32 string
  318. ;; and the replacement is a string that includes the replacement's name,
  319. ;; like "r837zajjc1q8z9hph4b6860a9c05blyy-openssl-1.0.2j".
  320. (let* ((prefix (string-append store "/"))
  321. (start (string-length prefix))
  322. (end (+ start hash-length)))
  323. (define (valid-hash? h)
  324. (every nix-base32-char? (string->list h)))
  325. (define (hash+rest s)
  326. (and (< end (string-length s))
  327. (let ((hash (substring s start end))
  328. (all (substring s start)))
  329. (and (string-prefix? prefix s)
  330. (valid-hash? hash)
  331. (eqv? #\- (string-ref s end))
  332. (list hash all)))))
  333. (map (match-lambda
  334. (((= hash+rest (origin-hash origin-string))
  335. .
  336. (= hash+rest (replacement-hash replacement-string)))
  337. (unless (= (string-length origin-string)
  338. (string-length replacement-string))
  339. (error "replacement length differs from the original length"
  340. origin-string replacement-string))
  341. (cons origin-hash (string->utf8 replacement-string)))
  342. ((origin . replacement)
  343. (error "invalid replacement" origin replacement)))
  344. mapping)))
  345. (define replacement-table
  346. (alist->vhash hash-mapping))
  347. (define prefix-len
  348. (string-length directory))
  349. (define (destination file)
  350. (string-append output (string-drop file prefix-len)))
  351. (define (rewrite-leaf file)
  352. (let ((stat (lstat file))
  353. (dest (destination file)))
  354. (mkdir-p* (dirname dest))
  355. (case (stat:type stat)
  356. ((symlink)
  357. (let ((target (readlink file)))
  358. (symlink (call-with-output-string
  359. (lambda (output)
  360. (replace-store-references (open-input-string target)
  361. output replacement-table
  362. store)))
  363. dest)))
  364. ((regular)
  365. (call-with-input-file file
  366. (lambda (input)
  367. (call-with-output-file dest
  368. (lambda (output)
  369. (replace-store-references input output replacement-table
  370. store)
  371. (chmod output (stat:perms stat)))))))
  372. ((directory)
  373. (mkdir-p* dest))
  374. (else
  375. (error "unsupported file type" stat)))))
  376. ;; Use 'exit-on-exception' to force an exit upon I/O errors, given that
  377. ;; 'n-par-for-each' silently swallows exceptions.
  378. ;; See <http://bugs.gnu.org/23581>.
  379. (n-par-for-each (parallel-job-count)
  380. (exit-on-exception rewrite-leaf)
  381. (find-files directory (const #t)
  382. #:directories? #t))
  383. (rename-matching-files output mapping))
  384. (define %graft-hooks
  385. ;; Default list of hooks run after grafting.
  386. (list graft-debug-links))
  387. (define* (graft old-outputs new-outputs mapping
  388. #:key (log-port (current-output-port))
  389. (hooks %graft-hooks))
  390. "Apply the grafts described by MAPPING on OLD-OUTPUTS, leading to
  391. NEW-OUTPUTS. MAPPING must be a list of file name pairs; OLD-OUTPUTS and
  392. NEW-OUTPUTS are lists of output name/file name pairs."
  393. (for-each (lambda (input output)
  394. (format log-port "grafting '~a' -> '~a'...~%" input output)
  395. (force-output)
  396. (rewrite-directory input output mapping))
  397. (match old-outputs
  398. (((names . files) ...)
  399. files))
  400. (match new-outputs
  401. (((names . files) ...)
  402. files)))
  403. (for-each (lambda (hook)
  404. (hook old-outputs new-outputs mapping
  405. #:log-port log-port))
  406. hooks))
  407. ;;; graft.scm ends here