serialization.scm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
  3. ;;;
  4. ;;; This file is part of GNU Guix.
  5. ;;;
  6. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  7. ;;; under the terms of the GNU General Public License as published by
  8. ;;; the Free Software Foundation; either version 3 of the License, or (at
  9. ;;; your option) any later version.
  10. ;;;
  11. ;;; GNU Guix is distributed in the hope that it will be useful, but
  12. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;;; GNU General Public License for more details.
  15. ;;;
  16. ;;; You should have received a copy of the GNU General Public License
  17. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  18. (define-module (guix serialization)
  19. #:use-module (rnrs bytevectors)
  20. #:use-module (srfi srfi-1)
  21. #:use-module (srfi srfi-26)
  22. #:use-module (srfi srfi-34)
  23. #:use-module (srfi srfi-35)
  24. #:use-module (ice-9 binary-ports)
  25. #:use-module ((ice-9 rdelim) #:prefix rdelim:)
  26. #:use-module (ice-9 match)
  27. #:use-module (ice-9 ftw)
  28. #:use-module (system foreign)
  29. #:export (write-int read-int
  30. write-long-long read-long-long
  31. write-padding
  32. write-bytevector write-string
  33. read-string read-latin1-string read-maybe-utf8-string
  34. write-string-list read-string-list
  35. write-string-pairs read-string-pairs
  36. write-store-path read-store-path
  37. write-store-path-list read-store-path-list
  38. (dump . dump-port*)
  39. &nar-error
  40. nar-error?
  41. nar-error-port
  42. nar-error-file
  43. &nar-read-error
  44. nar-read-error?
  45. nar-read-error-token
  46. write-file
  47. write-file-tree
  48. fold-archive
  49. restore-file
  50. dump-file))
  51. ;;; Comment:
  52. ;;;
  53. ;;; Serialization procedures used by the RPCs and the Nar format. This module
  54. ;;; is for internal consumption.
  55. ;;;
  56. ;;; Code:
  57. ;; Similar to serialize.cc in Nix.
  58. (define-condition-type &nar-error &error ; XXX: inherit from &store-error ?
  59. nar-error?
  60. (file nar-error-file) ; file we were restoring, or #f
  61. (port nar-error-port)) ; port from which we read
  62. (define currently-restored-file
  63. ;; Name of the file being restored. Used internally for error reporting.
  64. (make-parameter #f))
  65. (define (get-bytevector-n* port count)
  66. (let ((bv (get-bytevector-n port count)))
  67. (when (or (eof-object? bv)
  68. (< (bytevector-length bv) count))
  69. (raise (condition (&nar-error
  70. (file (currently-restored-file))
  71. (port port)))))
  72. bv))
  73. (define (sub-bytevector bv len)
  74. "Return a bytevector that aliases the first LEN bytes of BV."
  75. (define max (bytevector-length bv))
  76. (cond ((= len max) bv)
  77. ((< len max)
  78. ;; Yes, this is safe because the result of each conversion procedure
  79. ;; has its life cycle synchronized with that of its argument.
  80. (pointer->bytevector (bytevector->pointer bv) len))
  81. (else
  82. (error "sub-bytevector called to get a super bytevector"))))
  83. (define (write-int n p)
  84. (let ((b (make-bytevector 8 0)))
  85. (bytevector-u32-set! b 0 n (endianness little))
  86. (put-bytevector p b)))
  87. (define (read-int p)
  88. (let ((b (get-bytevector-n* p 8)))
  89. (bytevector-u32-ref b 0 (endianness little))))
  90. (define (write-long-long n p)
  91. (let ((b (make-bytevector 8 0)))
  92. (bytevector-u64-set! b 0 n (endianness little))
  93. (put-bytevector p b)))
  94. (define (read-long-long p)
  95. (let ((b (get-bytevector-n* p 8)))
  96. (bytevector-u64-ref b 0 (endianness little))))
  97. (define write-padding
  98. (let ((zero (make-bytevector 8 0)))
  99. (lambda (n p)
  100. (let ((m (modulo n 8)))
  101. (or (zero? m)
  102. (put-bytevector p zero 0 (- 8 m)))))))
  103. (define* (write-bytevector s p
  104. #:optional (l (bytevector-length s)))
  105. (let* ((m (modulo l 8))
  106. (b (make-bytevector (+ 8 l (if (zero? m) 0 (- 8 m))))))
  107. (bytevector-u32-set! b 0 l (endianness little))
  108. (bytevector-copy! s 0 b 8 l)
  109. (put-bytevector p b)))
  110. (define (write-string s p)
  111. (write-bytevector (string->utf8 s) p))
  112. (define (read-byte-string p)
  113. (let* ((len (read-int p))
  114. (m (modulo len 8))
  115. (pad (if (zero? m) 0 (- 8 m)))
  116. (bv (get-bytevector-n* p (+ len pad))))
  117. (sub-bytevector bv len)))
  118. (define (read-string p)
  119. (utf8->string (read-byte-string p)))
  120. (define (read-latin1-string p)
  121. "Read an ISO-8859-1 string from P."
  122. ;; Note: do not use 'get-string-n' to work around Guile bug
  123. ;; <http://bugs.gnu.org/19621>. See <http://bugs.gnu.org/19610> for
  124. ;; a discussion.
  125. (let ((bv (read-byte-string p)))
  126. ;; XXX: Rewrite using (ice-9 iconv).
  127. (list->string (map integer->char (bytevector->u8-list bv)))))
  128. (define (read-maybe-utf8-string p)
  129. "Read a serialized string from port P. Attempt to decode it as UTF-8 and
  130. substitute invalid byte sequences with question marks. This is a
  131. \"permissive\" UTF-8 decoder."
  132. ;; XXX: We rely on the port's decoding mechanism to do permissive decoding
  133. ;; and substitute invalid byte sequences with question marks, but this is
  134. ;; not very efficient. Eventually Guile may provide a lightweight
  135. ;; permissive UTF-8 decoder.
  136. (let* ((bv (read-byte-string p))
  137. (port (open-bytevector-input-port bv)))
  138. (set-port-encoding! port "UTF-8")
  139. (set-port-conversion-strategy! port 'substitute)
  140. (rdelim:read-string port)))
  141. (define (write-string-list l p)
  142. (write-int (length l) p)
  143. (for-each (cut write-string <> p) l))
  144. (define (read-string-list p)
  145. (let ((len (read-int p)))
  146. (unfold (cut >= <> len)
  147. (lambda (i)
  148. (read-string p))
  149. 1+
  150. 0)))
  151. (define (write-string-pairs l p)
  152. (write-int (length l) p)
  153. (for-each (match-lambda
  154. ((first . second)
  155. (write-string first p)
  156. (write-string second p)))
  157. l))
  158. (define (read-string-pairs p)
  159. (let ((len (read-int p)))
  160. (unfold (cut >= <> len)
  161. (lambda (i)
  162. (cons (read-string p) (read-string p)))
  163. 1+
  164. 0)))
  165. (define (write-store-path f p)
  166. (write-string f p)) ; TODO: assert path
  167. (define (read-store-path p)
  168. (read-string p)) ; TODO: assert path
  169. (define write-store-path-list write-string-list)
  170. (define read-store-path-list read-string-list)
  171. (define-syntax write-literal-strings
  172. (lambda (s)
  173. "Write the given literal strings to PORT in an optimized fashion, without
  174. any run-time allocations or computations."
  175. (define (padding len)
  176. (let ((m (modulo len 8)))
  177. (if (zero? m)
  178. 0
  179. (- 8 m))))
  180. (syntax-case s ()
  181. ((_ port strings ...)
  182. (let* ((bytes (map string->utf8 (syntax->datum #'(strings ...))))
  183. (len (fold (lambda (bv size)
  184. (+ size 8 (bytevector-length bv)
  185. (padding (bytevector-length bv))))
  186. 0
  187. bytes))
  188. (bv (make-bytevector len))
  189. (zeros (make-bytevector 8 0)))
  190. (fold (lambda (str offset)
  191. (let ((len (bytevector-length str)))
  192. (bytevector-u32-set! bv offset len (endianness little))
  193. (bytevector-copy! str 0 bv (+ 8 offset) len)
  194. (bytevector-copy! zeros 0 bv (+ 8 offset len)
  195. (padding len))
  196. (+ offset 8 len (padding len))))
  197. 0
  198. bytes)
  199. #`(put-bytevector port #,bv))))))
  200. (define-condition-type &nar-read-error &nar-error
  201. nar-read-error?
  202. (token nar-read-error-token)) ; faulty token, or #f
  203. (define (dump in out size)
  204. "Copy SIZE bytes from IN to OUT."
  205. (define buf-size 65536)
  206. (define buf (make-bytevector buf-size))
  207. (let loop ((left size))
  208. (if (<= left 0)
  209. 0
  210. (let ((read (get-bytevector-n! in buf 0 (min left buf-size))))
  211. (if (eof-object? read)
  212. left
  213. (begin
  214. (put-bytevector out buf 0 read)
  215. (loop (- left read))))))))
  216. (define (write-contents-from-port input output size)
  217. "Write SIZE bytes from port INPUT to port OUTPUT."
  218. (write-string "contents" output)
  219. (write-long-long size output)
  220. ;; Use 'sendfile' when both OUTPUT and INPUT are file ports.
  221. (if (and (file-port? output) (file-port? input))
  222. (sendfile output input size 0)
  223. (dump input output size))
  224. (write-padding size output))
  225. (define (read-file-type port)
  226. "Read the file type tag from PORT, and return either 'regular or
  227. 'executable."
  228. (match (read-string port)
  229. ("contents"
  230. 'regular)
  231. ("executable"
  232. (match (list (read-string port) (read-string port))
  233. (("" "contents") 'executable)
  234. (x (raise
  235. (condition (&message
  236. (message "unexpected executable file marker"))
  237. (&nar-read-error (port port)
  238. (file #f)
  239. (token x)))))))
  240. (x
  241. (raise
  242. (condition (&message (message "unsupported nar file type"))
  243. (&nar-read-error (port port) (file #f) (token x)))))))
  244. (define %archive-version-1
  245. ;; Magic cookie for Nix archives.
  246. "nix-archive-1")
  247. (define* (write-file file port
  248. #:key (select? (const #t)))
  249. "Write the contents of FILE to PORT in Nar format, recursing into
  250. sub-directories of FILE as needed. For each directory entry, call (SELECT?
  251. FILE STAT), where FILE is the entry's absolute file name and STAT is the
  252. result of 'lstat'; exclude entries for which SELECT? does not return true."
  253. (write-file-tree file port
  254. #:file-type+size
  255. (lambda (file)
  256. (let* ((stat (lstat file))
  257. (size (stat:size stat)))
  258. (case (stat:type stat)
  259. ((directory)
  260. (values 'directory size))
  261. ((regular)
  262. (values (if (zero? (logand (stat:mode stat)
  263. #o100))
  264. 'regular
  265. 'executable)
  266. size))
  267. (else
  268. (values (stat:type stat) size))))) ;bah!
  269. #:file-port (cut open-file <> "r0b")
  270. #:symlink-target readlink
  271. #:directory-entries
  272. (lambda (directory)
  273. ;; 'scandir' defaults to 'string-locale<?' to sort files,
  274. ;; but this happens to be case-insensitive (at least in
  275. ;; 'en_US' locale on libc 2.18.) Conversely, we want
  276. ;; files to be sorted in a case-sensitive fashion.
  277. (define basenames
  278. (scandir directory (negate (cut member <> '("." "..")))
  279. string<?))
  280. (filter-map (lambda (base)
  281. (let ((file (string-append directory
  282. "/" base)))
  283. (and (select? file (lstat file))
  284. base)))
  285. basenames))
  286. ;; The 'scandir' call above gives us filtered and sorted
  287. ;; entries, so no post-processing is needed.
  288. #:postprocess-entries identity))
  289. (define (filter/sort-directory-entries lst)
  290. "Remove dot and dot-dot entries from LST, and sort it in lexicographical
  291. order."
  292. (delete-duplicates
  293. (sort (remove (cute member <> '("." "..")) lst)
  294. string<?)
  295. string=?))
  296. (define* (write-file-tree file port
  297. #:key
  298. file-type+size
  299. file-port
  300. symlink-target
  301. directory-entries
  302. (postprocess-entries filter/sort-directory-entries))
  303. "Write the contents of FILE to PORT in Nar format, recursing into
  304. sub-directories of FILE as needed.
  305. This procedure does not make any file-system I/O calls. Instead, it calls the
  306. user-provided FILE-TYPE+SIZE, FILE-PORT, SYMLINK-TARGET, and DIRECTORY-ENTRIES
  307. procedures, which roughly correspond to 'lstat', 'readlink', and 'scandir'.
  308. POSTPROCESS-ENTRIES ensures that directory entries are valid; leave it as-is
  309. unless you know that DIRECTORY-ENTRIES provide filtered and sorted entries, in
  310. which case you can use 'identity'."
  311. (define p port)
  312. (write-string %archive-version-1 p)
  313. (let dump ((f file))
  314. (define-values (type size)
  315. (file-type+size f))
  316. (write-literal-strings p "(")
  317. (case type
  318. ((regular executable)
  319. (write-literal-strings p "type" "regular")
  320. (when (eq? 'executable type)
  321. (write-literal-strings p "executable" ""))
  322. (let ((input (file-port f)))
  323. (dynamic-wind
  324. (const #t)
  325. (lambda ()
  326. (write-contents-from-port input p size))
  327. (lambda ()
  328. (close-port input)))))
  329. ((directory)
  330. (write-literal-strings p "type" "directory")
  331. (let ((entries (postprocess-entries (directory-entries f))))
  332. (for-each (lambda (e)
  333. (let* ((f (string-append f "/" e)))
  334. (write-literal-strings p "entry" "(" "name")
  335. (write-string e p)
  336. (write-literal-strings p "node")
  337. (dump f)
  338. (write-literal-strings p ")")))
  339. entries)))
  340. ((symlink)
  341. (write-literal-strings p "type" "symlink" "target")
  342. (write-string (symlink-target f) p))
  343. (else
  344. (raise (condition (&message (message "unsupported file type"))
  345. (&nar-error (file f) (port port))))))
  346. (write-literal-strings p ")")))
  347. (define port-conversion-strategy
  348. (fluid->parameter %default-port-conversion-strategy))
  349. (define (fold-archive proc seed port file)
  350. "Read a file (possibly a directory structure) in Nar format from PORT. Call
  351. PROC on each file or directory read from PORT using:
  352. (PROC FILE TYPE CONTENTS RESULT)
  353. using SEED as the first RESULT. TYPE is a symbol like 'regular, and CONTENTS
  354. depends on TYPE."
  355. (parameterize ((currently-restored-file file)
  356. ;; Error out if we can convert file names to the current
  357. ;; locale. (XXX: We'd prefer UTF-8 encoding for file names
  358. ;; regardless of the locale, but that's what Guile gives us
  359. ;; so far.)
  360. (port-conversion-strategy 'error))
  361. (let ((signature (read-string port)))
  362. (unless (equal? signature %archive-version-1)
  363. (raise
  364. (condition (&message (message "invalid nar signature"))
  365. (&nar-read-error (port port)
  366. (token signature)
  367. (file #f))))))
  368. (let read ((file file)
  369. (result seed))
  370. (define (read-eof-marker)
  371. (match (read-string port)
  372. (")" #t)
  373. (x (raise
  374. (condition
  375. (&message (message "invalid nar end-of-file marker"))
  376. (&nar-read-error (port port) (file file) (token x)))))))
  377. (currently-restored-file file)
  378. (match (list (read-string port) (read-string port) (read-string port))
  379. (("(" "type" "regular")
  380. (let* ((type (read-file-type port))
  381. (size (read-long-long port))
  382. ;; The caller must read exactly SIZE bytes from PORT.
  383. (result (proc file type `(,port . ,size) result)))
  384. (let ((m (modulo size 8)))
  385. (unless (zero? m)
  386. (get-bytevector-n* port (- 8 m))))
  387. (read-eof-marker)
  388. result))
  389. (("(" "type" "symlink")
  390. (match (list (read-string port) (read-string port))
  391. (("target" target)
  392. (let ((result (proc file 'symlink target result)))
  393. (read-eof-marker)
  394. result))
  395. (x (raise
  396. (condition
  397. (&message (message "invalid symlink tokens"))
  398. (&nar-read-error (port port) (file file) (token x)))))))
  399. (("(" "type" "directory")
  400. (let ((dir file))
  401. (let loop ((prefix (read-string port))
  402. (result (proc file 'directory #f result)))
  403. (match prefix
  404. ("entry"
  405. (match (list (read-string port)
  406. (read-string port) (read-string port)
  407. (read-string port))
  408. (("(" "name" file "node")
  409. (let ((result (read (string-append dir "/" file) result)))
  410. (match (read-string port)
  411. (")" #f)
  412. (x
  413. (raise
  414. (condition
  415. (&message
  416. (message "unexpected directory entry termination"))
  417. (&nar-read-error (port port)
  418. (file file)
  419. (token x))))))
  420. (loop (read-string port) result)))))
  421. (")" ;done with DIR
  422. (proc file 'directory-complete #f result))
  423. (x
  424. (raise
  425. (condition
  426. (&message (message "unexpected directory inter-entry marker"))
  427. (&nar-read-error (port port) (file file) (token x)))))))))
  428. (x
  429. (raise
  430. (condition
  431. (&message (message "unsupported nar entry type"))
  432. (&nar-read-error (port port) (file file) (token x)))))))))
  433. (define (dump-file file input size type)
  434. "Dump SIZE bytes from INPUT to FILE.
  435. This procedure is suitable for use as the #:dump-file argument to
  436. 'restore-file'."
  437. (call-with-output-file file
  438. (lambda (output)
  439. (dump input output size))))
  440. (define* (restore-file port file
  441. #:key (dump-file dump-file))
  442. "Read a file (possibly a directory structure) in Nar format from PORT.
  443. Restore it as FILE with canonical permissions and timestamps. To write a
  444. regular or executable file, call:
  445. (DUMP-FILE FILE INPUT SIZE TYPE)
  446. The default is to dump SIZE bytes from INPUT to FILE, but callers can provide
  447. a custom procedure, for instance to deduplicate FILE on the fly."
  448. (fold-archive (lambda (file type content result)
  449. (match type
  450. ('directory
  451. (mkdir file))
  452. ('directory-complete
  453. (chmod file #o555)
  454. (utime file 1 1 0 0))
  455. ('symlink
  456. (symlink content file)
  457. (utime file 1 1 0 0 AT_SYMLINK_NOFOLLOW))
  458. ((or 'regular 'executable)
  459. (match content
  460. ((input . size)
  461. (dump-file file input size type)
  462. (chmod file (if (eq? type 'executable)
  463. #o555
  464. #o444))
  465. (utime file 1 1 0 0))))))
  466. #t
  467. port
  468. file))
  469. ;;; Local Variables:
  470. ;;; eval: (put 'call-with-binary-input-file 'scheme-indent-function 1)
  471. ;;; End:
  472. ;;; serialization.scm ends here