serialization.scm 19 KB

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