serialization.scm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 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
  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. ;;; 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 (write-string-pairs l p)
  145. (write-int (length l) p)
  146. (for-each (match-lambda
  147. ((first . second)
  148. (write-string first p)
  149. (write-string second p)))
  150. l))
  151. (define (read-string-list p)
  152. (let ((len (read-int p)))
  153. (unfold (cut >= <> len)
  154. (lambda (i)
  155. (read-string p))
  156. 1+
  157. 0)))
  158. (define (write-store-path f p)
  159. (write-string f p)) ; TODO: assert path
  160. (define (read-store-path p)
  161. (read-string p)) ; TODO: assert path
  162. (define write-store-path-list write-string-list)
  163. (define read-store-path-list read-string-list)
  164. (define-condition-type &nar-read-error &nar-error
  165. nar-read-error?
  166. (token nar-read-error-token)) ; faulty token, or #f
  167. (define (dump in out size)
  168. "Copy SIZE bytes from IN to OUT."
  169. (define buf-size 65536)
  170. (define buf (make-bytevector buf-size))
  171. (let loop ((left size))
  172. (if (<= left 0)
  173. 0
  174. (let ((read (get-bytevector-n! in buf 0 (min left buf-size))))
  175. (if (eof-object? read)
  176. left
  177. (begin
  178. (put-bytevector out buf 0 read)
  179. (loop (- left read))))))))
  180. (define (write-contents-from-port input output size)
  181. "Write SIZE bytes from port INPUT to port OUTPUT."
  182. (write-string "contents" output)
  183. (write-long-long size output)
  184. ;; Use 'sendfile' when both OUTPUT and INPUT are file ports.
  185. (if (and (file-port? output) (file-port? input))
  186. (sendfile output input size 0)
  187. (dump input output size))
  188. (write-padding size output))
  189. (define (read-file-type port)
  190. "Read the file type tag from PORT, and return either 'regular or
  191. 'executable."
  192. (match (read-string port)
  193. ("contents"
  194. 'regular)
  195. ("executable"
  196. (match (list (read-string port) (read-string port))
  197. (("" "contents") 'executable)
  198. (x (raise
  199. (condition (&message
  200. (message "unexpected executable file marker"))
  201. (&nar-read-error (port port)
  202. (file #f)
  203. (token x)))))))
  204. (x
  205. (raise
  206. (condition (&message (message "unsupported nar file type"))
  207. (&nar-read-error (port port) (file #f) (token x)))))))
  208. (define %archive-version-1
  209. ;; Magic cookie for Nix archives.
  210. "nix-archive-1")
  211. (define* (write-file file port
  212. #:key (select? (const #t)))
  213. "Write the contents of FILE to PORT in Nar format, recursing into
  214. sub-directories of FILE as needed. For each directory entry, call (SELECT?
  215. FILE STAT), where FILE is the entry's absolute file name and STAT is the
  216. result of 'lstat'; exclude entries for which SELECT? does not return true."
  217. (write-file-tree file port
  218. #:file-type+size
  219. (lambda (file)
  220. (let* ((stat (lstat file))
  221. (size (stat:size stat)))
  222. (case (stat:type stat)
  223. ((directory)
  224. (values 'directory size))
  225. ((regular)
  226. (values (if (zero? (logand (stat:mode stat)
  227. #o100))
  228. 'regular
  229. 'executable)
  230. size))
  231. (else
  232. (values (stat:type stat) size))))) ;bah!
  233. #:file-port (cut open-file <> "r0b")
  234. #:symlink-target readlink
  235. #:directory-entries
  236. (lambda (directory)
  237. ;; 'scandir' defaults to 'string-locale<?' to sort files,
  238. ;; but this happens to be case-insensitive (at least in
  239. ;; 'en_US' locale on libc 2.18.) Conversely, we want
  240. ;; files to be sorted in a case-sensitive fashion.
  241. (define basenames
  242. (scandir directory (negate (cut member <> '("." "..")))
  243. string<?))
  244. (filter-map (lambda (base)
  245. (let ((file (string-append directory
  246. "/" base)))
  247. (and (select? file (lstat file))
  248. base)))
  249. basenames))
  250. ;; The 'scandir' call above gives us filtered and sorted
  251. ;; entries, so no post-processing is needed.
  252. #:postprocess-entries identity))
  253. (define (filter/sort-directory-entries lst)
  254. "Remove dot and dot-dot entries from LST, and sort it in lexicographical
  255. order."
  256. (delete-duplicates
  257. (sort (remove (cute member <> '("." "..")) lst)
  258. string<?)
  259. string=?))
  260. (define* (write-file-tree file port
  261. #:key
  262. file-type+size
  263. file-port
  264. symlink-target
  265. directory-entries
  266. (postprocess-entries filter/sort-directory-entries))
  267. "Write the contents of FILE to PORT in Nar format, recursing into
  268. sub-directories of FILE as needed.
  269. This procedure does not make any file-system I/O calls. Instead, it calls the
  270. user-provided FILE-TYPE+SIZE, FILE-PORT, SYMLINK-TARGET, and DIRECTORY-ENTRIES
  271. procedures, which roughly correspond to 'lstat', 'readlink', and 'scandir'.
  272. POSTPROCESS-ENTRIES ensures that directory entries are valid; leave it as-is
  273. unless you know that DIRECTORY-ENTRIES provide filtered and sorted entries, in
  274. which case you can use 'identity'."
  275. (define p port)
  276. (write-string %archive-version-1 p)
  277. (let dump ((f file))
  278. (define-values (type size)
  279. (file-type+size f))
  280. (write-string "(" p)
  281. (case type
  282. ((regular executable)
  283. (write-string "type" p)
  284. (write-string "regular" p)
  285. (when (eq? 'executable type)
  286. (write-string "executable" p)
  287. (write-string "" p))
  288. (let ((input (file-port f)))
  289. (dynamic-wind
  290. (const #t)
  291. (lambda ()
  292. (write-contents-from-port input p size))
  293. (lambda ()
  294. (close-port input)))))
  295. ((directory)
  296. (write-string "type" p)
  297. (write-string "directory" p)
  298. (let ((entries (postprocess-entries (directory-entries f))))
  299. (for-each (lambda (e)
  300. (let* ((f (string-append f "/" e)))
  301. (write-string "entry" p)
  302. (write-string "(" p)
  303. (write-string "name" p)
  304. (write-string e p)
  305. (write-string "node" p)
  306. (dump f)
  307. (write-string ")" p)))
  308. entries)))
  309. ((symlink)
  310. (write-string "type" p)
  311. (write-string "symlink" p)
  312. (write-string "target" p)
  313. (write-string (symlink-target f) p))
  314. (else
  315. (raise (condition (&message (message "unsupported file type"))
  316. (&nar-error (file f) (port port))))))
  317. (write-string ")" p)))
  318. (define port-conversion-strategy
  319. (fluid->parameter %default-port-conversion-strategy))
  320. (define (fold-archive proc seed port file)
  321. "Read a file (possibly a directory structure) in Nar format from PORT. Call
  322. PROC on each file or directory read from PORT using:
  323. (PROC FILE TYPE CONTENTS RESULT)
  324. using SEED as the first RESULT. TYPE is a symbol like 'regular, and CONTENTS
  325. depends on TYPE."
  326. (parameterize ((currently-restored-file file)
  327. ;; Error out if we can convert file names to the current
  328. ;; locale. (XXX: We'd prefer UTF-8 encoding for file names
  329. ;; regardless of the locale, but that's what Guile gives us
  330. ;; so far.)
  331. (port-conversion-strategy 'error))
  332. (let ((signature (read-string port)))
  333. (unless (equal? signature %archive-version-1)
  334. (raise
  335. (condition (&message (message "invalid nar signature"))
  336. (&nar-read-error (port port)
  337. (token signature)
  338. (file #f))))))
  339. (let read ((file file)
  340. (result seed))
  341. (define (read-eof-marker)
  342. (match (read-string port)
  343. (")" #t)
  344. (x (raise
  345. (condition
  346. (&message (message "invalid nar end-of-file marker"))
  347. (&nar-read-error (port port) (file file) (token x)))))))
  348. (currently-restored-file file)
  349. (match (list (read-string port) (read-string port) (read-string port))
  350. (("(" "type" "regular")
  351. (let* ((type (read-file-type port))
  352. (size (read-long-long port))
  353. ;; The caller must read exactly SIZE bytes from PORT.
  354. (result (proc file type `(,port . ,size) result)))
  355. (let ((m (modulo size 8)))
  356. (unless (zero? m)
  357. (get-bytevector-n* port (- 8 m))))
  358. (read-eof-marker)
  359. result))
  360. (("(" "type" "symlink")
  361. (match (list (read-string port) (read-string port))
  362. (("target" target)
  363. (let ((result (proc file 'symlink target result)))
  364. (read-eof-marker)
  365. result))
  366. (x (raise
  367. (condition
  368. (&message (message "invalid symlink tokens"))
  369. (&nar-read-error (port port) (file file) (token x)))))))
  370. (("(" "type" "directory")
  371. (let ((dir file))
  372. (let loop ((prefix (read-string port))
  373. (result (proc file 'directory #f result)))
  374. (match prefix
  375. ("entry"
  376. (match (list (read-string port)
  377. (read-string port) (read-string port)
  378. (read-string port))
  379. (("(" "name" file "node")
  380. (let ((result (read (string-append dir "/" file) result)))
  381. (match (read-string port)
  382. (")" #f)
  383. (x
  384. (raise
  385. (condition
  386. (&message
  387. (message "unexpected directory entry termination"))
  388. (&nar-read-error (port port)
  389. (file file)
  390. (token x))))))
  391. (loop (read-string port) result)))))
  392. (")" result) ;done with DIR
  393. (x
  394. (raise
  395. (condition
  396. (&message (message "unexpected directory inter-entry marker"))
  397. (&nar-read-error (port port) (file file) (token x)))))))))
  398. (x
  399. (raise
  400. (condition
  401. (&message (message "unsupported nar entry type"))
  402. (&nar-read-error (port port) (file file) (token x)))))))))
  403. (define (restore-file port file)
  404. "Read a file (possibly a directory structure) in Nar format from PORT.
  405. Restore it as FILE."
  406. (fold-archive (lambda (file type content result)
  407. (match type
  408. ('directory
  409. (mkdir file))
  410. ('symlink
  411. (symlink content file))
  412. ((or 'regular 'executable)
  413. (match content
  414. ((input . size)
  415. (call-with-output-file file
  416. (lambda (output)
  417. (dump input output size)
  418. (when (eq? type 'executable)
  419. (chmod output #o755)))))))))
  420. #t
  421. port
  422. file))
  423. ;;; Local Variables:
  424. ;;; eval: (put 'call-with-binary-input-file 'scheme-indent-function 1)
  425. ;;; End:
  426. ;;; serialization.scm ends here