file-systems: Use creation time if modification time is unset for ISO9660.
[jackhill/guix/guix.git] / gnu / build / file-systems.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2016, 2017 David Craven <david@craven.ch>
4 ;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.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
21 (define-module (gnu build file-systems)
22 #:use-module (guix build utils)
23 #:use-module (guix build bournish)
24 #:use-module (guix build syscalls)
25 #:use-module (rnrs io ports)
26 #:use-module (rnrs bytevectors)
27 #:use-module (ice-9 match)
28 #:use-module (ice-9 rdelim)
29 #:use-module (ice-9 format)
30 #:use-module (ice-9 regex)
31 #:use-module (system foreign)
32 #:autoload (system repl repl) (start-repl)
33 #:use-module (srfi srfi-1)
34 #:use-module (srfi srfi-26)
35 #:export (disk-partitions
36 partition-label-predicate
37 partition-uuid-predicate
38 partition-luks-uuid-predicate
39 find-partition-by-label
40 find-partition-by-uuid
41 find-partition-by-luks-uuid
42 canonicalize-device-spec
43
44 uuid->string
45 string->uuid
46
47 bind-mount
48
49 mount-flags->bit-mask
50 check-file-system
51 mount-file-system))
52
53 ;;; Commentary:
54 ;;;
55 ;;; This modules provides tools to deal with disk partitions, and to mount and
56 ;;; check file systems.
57 ;;;
58 ;;; Code:
59
60 (define (bind-mount source target)
61 "Bind-mount SOURCE at TARGET."
62 (mount source target "" MS_BIND))
63
64 (define (seek* fd/port offset whence)
65 "Like 'seek' but return -1 instead of throwing to 'system-error' upon
66 EINVAL. This makes it easier to catch cases like OFFSET being too large for
67 FD/PORT."
68 (catch 'system-error
69 (lambda ()
70 (seek fd/port offset whence))
71 (lambda args
72 (if (= EINVAL (system-error-errno args))
73 -1
74 (apply throw args)))))
75
76 (define (read-superblock device offset size magic?)
77 "Read a superblock of SIZE from OFFSET and DEVICE. Return the raw
78 superblock on success, and #f if no valid superblock was found. MAGIC?
79 takes a bytevector and returns #t when it's a valid superblock."
80 (call-with-input-file device
81 (lambda (port)
82 (and (= offset (seek* port offset SEEK_SET))
83 (let ((block (make-bytevector size)))
84 (match (get-bytevector-n! port block 0 (bytevector-length block))
85 ((? eof-object?)
86 #f)
87 ((? number? len)
88 (and (= len (bytevector-length block))
89 (and (magic? block)
90 block)))))))))
91
92 (define (sub-bytevector bv start size)
93 "Return a copy of the SIZE bytes of BV starting from offset START."
94 (let ((result (make-bytevector size)))
95 (bytevector-copy! bv start result 0 size)
96 result))
97
98 (define (latin1->string bv terminator)
99 "Return a string of BV, a latin1 bytevector, or #f. TERMINATOR is a predicate
100 that takes a number and returns #t when a termination character is found."
101 (let ((bytes (take-while (negate terminator) (bytevector->u8-list bv))))
102 (if (null? bytes)
103 #f
104 (list->string (map integer->char bytes)))))
105
106 (define null-terminated-latin1->string
107 (cut latin1->string <> zero?))
108
109 \f
110 ;;;
111 ;;; Ext2 file systems.
112 ;;;
113
114 ;; <http://www.nongnu.org/ext2-doc/ext2.html#DEF-SUPERBLOCK>.
115 ;; TODO: Use "packed structs" from Guile-OpenGL or similar.
116
117 (define-syntax %ext2-endianness
118 ;; Endianness of ext2 file systems.
119 (identifier-syntax (endianness little)))
120
121 (define (ext2-superblock? sblock)
122 "Return #t when SBLOCK is an ext2 superblock."
123 (let ((magic (bytevector-u16-ref sblock 56 %ext2-endianness)))
124 (= magic #xef53)))
125
126 (define (read-ext2-superblock device)
127 "Return the raw contents of DEVICE's ext2 superblock as a bytevector, or #f
128 if DEVICE does not contain an ext2 file system."
129 (read-superblock device 1024 264 ext2-superblock?))
130
131 (define (ext2-superblock-uuid sblock)
132 "Return the UUID of ext2 superblock SBLOCK as a 16-byte bytevector."
133 (sub-bytevector sblock 104 16))
134
135 (define (ext2-superblock-volume-name sblock)
136 "Return the volume name of SBLOCK as a string of at most 16 characters, or
137 #f if SBLOCK has no volume name."
138 (null-terminated-latin1->string (sub-bytevector sblock 120 16)))
139
140 (define (check-ext2-file-system device)
141 "Return the health of an ext2 file system on DEVICE."
142 (match (status:exit-val
143 (system* "e2fsck" "-v" "-p" "-C" "0" device))
144 (0 'pass)
145 (1 'errors-corrected)
146 (2 'reboot-required)
147 (_ 'fatal-error)))
148
149 \f
150 ;;;
151 ;;; Btrfs file systems.
152 ;;;
153
154 ;; <https://btrfs.wiki.kernel.org/index.php/On-disk_Format#Superblock>.
155
156 (define-syntax %btrfs-endianness
157 ;; Endianness of btrfs file systems.
158 (identifier-syntax (endianness little)))
159
160 (define (btrfs-superblock? sblock)
161 "Return #t when SBLOCK is a btrfs superblock."
162 (bytevector=? (sub-bytevector sblock 64 8)
163 (string->utf8 "_BHRfS_M")))
164
165 (define (read-btrfs-superblock device)
166 "Return the raw contents of DEVICE's btrfs superblock as a bytevector, or #f
167 if DEVICE does not contain a btrfs file system."
168 (read-superblock device 65536 4096 btrfs-superblock?))
169
170 (define (btrfs-superblock-uuid sblock)
171 "Return the UUID of a btrfs superblock SBLOCK as a 16-byte bytevector."
172 (sub-bytevector sblock 32 16))
173
174 (define (btrfs-superblock-volume-name sblock)
175 "Return the volume name of SBLOCK as a string of at most 256 characters, or
176 #f if SBLOCK has no volume name."
177 (null-terminated-latin1->string (sub-bytevector sblock 299 256)))
178
179 (define (check-btrfs-file-system device)
180 "Return the health of a btrfs file system on DEVICE."
181 (match (status:exit-val
182 (system* "btrfs" "device" "scan"))
183 (0 'pass)
184 (_ 'fatal-error)))
185
186 \f
187 ;;;
188 ;;; FAT32 file systems.
189 ;;;
190
191 ;; <http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-107.pdf>.
192
193 (define-syntax %fat32-endianness
194 ;; Endianness of fat file systems.
195 (identifier-syntax (endianness little)))
196
197 (define (fat32-superblock? sblock)
198 "Return #t when SBLOCK is a fat32 superblock."
199 (bytevector=? (sub-bytevector sblock 82 8)
200 (string->utf8 "FAT32 ")))
201
202 (define (read-fat32-superblock device)
203 "Return the raw contents of DEVICE's fat32 superblock as a bytevector, or
204 #f if DEVICE does not contain a fat32 file system."
205 (read-superblock device 0 90 fat32-superblock?))
206
207 (define (fat32-superblock-uuid sblock)
208 "Return the Volume ID of a fat superblock SBLOCK as a 4-byte bytevector."
209 (sub-bytevector sblock 67 4))
210
211 (define (fat32-uuid->string uuid)
212 "Convert fat32 UUID, a 4-byte bytevector, to its string representation."
213 (let ((high (bytevector-uint-ref uuid 0 %fat32-endianness 2))
214 (low (bytevector-uint-ref uuid 2 %fat32-endianness 2)))
215 (format #f "~:@(~x-~x~)" low high)))
216
217 (define (fat32-superblock-volume-name sblock)
218 "Return the volume name of SBLOCK as a string of at most 11 characters, or
219 #f if SBLOCK has no volume name. The volume name is a latin1 string.
220 Trailing spaces are trimmed."
221 (string-trim-right (latin1->string (sub-bytevector sblock 71 11) (lambda (c) #f)) #\space))
222
223 (define (check-fat32-file-system device)
224 "Return the health of a fat file system on DEVICE."
225 (match (status:exit-val
226 (system* "fsck.vfat" "-v" "-a" device))
227 (0 'pass)
228 (1 'errors-corrected)
229 (_ 'fatal-error)))
230
231 \f
232 ;;;
233 ;;; ISO9660 file systems.
234 ;;;
235
236 ;; <http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-119.pdf>.
237
238 (define (iso9660-superblock? sblock)
239 "Return #t when SBLOCK is an iso9660 volume descriptor."
240 (bytevector=? (sub-bytevector sblock 1 6)
241 ;; Note: "\x01" is the volume descriptor format version
242 (string->utf8 "CD001\x01")))
243
244 (define (read-iso9660-primary-volume-descriptor device offset)
245 "Find and read the first primary volume descriptor, starting at OFFSET.
246 Return #f if not found."
247 (let* ((sblock (read-superblock device offset 2048 iso9660-superblock?))
248 (type-code (if sblock
249 (bytevector-u8-ref sblock 0)
250 (error (format #f
251 "Could not read ISO9660 primary
252 volume descriptor from ~s"
253 device)))))
254 (match type-code
255 (255 #f) ; Volume Descriptor Set Terminator.
256 (1 sblock) ; Primary Volume Descriptor
257 (_ (read-iso9660-primary-volume-descriptor device (+ offset 2048))))))
258
259 (define (read-iso9660-superblock device)
260 "Return the raw contents of DEVICE's iso9660 primary volume descriptor
261 as a bytevector, or #f if DEVICE does not contain an iso9660 file system."
262 ;; Start reading at sector 16.
263 ;; Since we are not sure that the device contains an ISO9660 filesystem,
264 ;; we have to find that out first.
265 (if (read-superblock device (* 2048 16) 2048 iso9660-superblock?)
266 (read-iso9660-primary-volume-descriptor device (* 2048 16))
267 #f)) ; Device does not contain an iso9660 filesystem.
268
269 (define (iso9660-superblock-uuid sblock)
270 "Return the modification time of an iso9660 primary volume descriptor
271 SBLOCK as a bytevector. If that's not set, returns the creation time."
272 ;; Drops GMT offset for compatibility with Grub, blkid and /dev/disk/by-uuid.
273 ;; Compare Grub: "2014-12-02-19-30-23-00".
274 ;; Compare blkid result: "2014-12-02-19-30-23-00".
275 ;; Compare /dev/disk/by-uuid entry: "2014-12-02-19-30-23-00".
276 (let* ((creation-time (sub-bytevector sblock 813 17))
277 (modification-time (sub-bytevector sblock 830 17))
278 (unset-time (make-bytevector 17 0))
279 (time (if (bytevector=? unset-time modification-time)
280 creation-time
281 modification-time)))
282 (sub-bytevector time 0 16))) ; strips GMT offset.
283
284 (define (iso9660-uuid->string uuid)
285 "Given an UUID bytevector, return its timestamp string."
286 (define (digits->string bytes)
287 (latin1->string bytes (lambda (c) #f)))
288 (let* ((year (sub-bytevector uuid 0 4))
289 (month (sub-bytevector uuid 4 2))
290 (day (sub-bytevector uuid 6 2))
291 (hour (sub-bytevector uuid 8 2))
292 (minute (sub-bytevector uuid 10 2))
293 (second (sub-bytevector uuid 12 2))
294 (hundredths (sub-bytevector uuid 14 2))
295 (parts (list year month day hour minute second hundredths)))
296 (string-append (string-join (map digits->string parts)))))
297
298 (define (iso9660-superblock-volume-name sblock)
299 "Return the volume name of SBLOCK as a string. The volume name is an ASCII
300 string. Trailing spaces are trimmed."
301 ;; Note: Valid characters are of the set "[0-9][A-Z]_" (ECMA-119 Appendix A)
302 (string-trim-right (latin1->string (sub-bytevector sblock 40 32)
303 (lambda (c) #f)) #\space))
304
305 \f
306 ;;;
307 ;;; LUKS encrypted devices.
308 ;;;
309
310 ;; The LUKS header format is described in "LUKS On-Disk Format Specification":
311 ;; <https://gitlab.com/cryptsetup/cryptsetup/wikis/Specification>. We follow
312 ;; version 1.2.1 of this document.
313
314 (define-syntax %luks-endianness
315 ;; Endianness of LUKS headers.
316 (identifier-syntax (endianness big)))
317
318 (define (luks-superblock? sblock)
319 "Return #t when SBLOCK is a luks superblock."
320 (define %luks-magic
321 ;; The 'LUKS_MAGIC' constant.
322 (u8-list->bytevector (append (map char->integer (string->list "LUKS"))
323 (list #xba #xbe))))
324 (let ((magic (sub-bytevector sblock 0 6))
325 (version (bytevector-u16-ref sblock 6 %luks-endianness)))
326 (and (bytevector=? magic %luks-magic)
327 (= version 1))))
328
329 (define (read-luks-header file)
330 "Read a LUKS header from FILE. Return the raw header on success, and #f if
331 not valid header was found."
332 ;; Size in bytes of the LUKS header, including key slots.
333 (read-superblock file 0 592 luks-superblock?))
334
335 (define (luks-header-uuid header)
336 "Return the LUKS UUID from HEADER, as a 16-byte bytevector."
337 ;; 40 bytes are reserved for the UUID, but in practice, it contains the 36
338 ;; bytes of its ASCII representation.
339 (let ((uuid (sub-bytevector header 168 36)))
340 (string->uuid (utf8->string uuid))))
341
342 \f
343 ;;;
344 ;;; Partition lookup.
345 ;;;
346
347 (define (disk-partitions)
348 "Return the list of device names corresponding to valid disk partitions."
349 (define (last-character str)
350 (string-ref str (- (string-length str) 1)))
351
352 (define (partition? name major minor)
353 ;; Select device names that end in a digit, like libblkid's 'probe_all'
354 ;; function does. Checking for "/sys/dev/block/MAJOR:MINOR/partition"
355 ;; doesn't work for partitions coming from mapped devices.
356 (and (char-set-contains? char-set:digit (last-character name))
357 (> major 2))) ;ignore RAM disks and floppy disks
358
359 (call-with-input-file "/proc/partitions"
360 (lambda (port)
361 ;; Skip the two header lines.
362 (read-line port)
363 (read-line port)
364
365 ;; Read each subsequent line, and extract the last space-separated
366 ;; field.
367 (let loop ((parts '()))
368 (let ((line (read-line port)))
369 (if (eof-object? line)
370 (reverse parts)
371 (match (string-tokenize line)
372 (((= string->number major) (= string->number minor)
373 blocks name)
374 (if (partition? name major minor)
375 (loop (cons name parts))
376 (loop parts))))))))))
377
378 (define (ENOENT-safe proc)
379 "Wrap the one-argument PROC such that ENOENT errors are caught and lead to a
380 warning and #f as the result."
381 (lambda (device)
382 (catch 'system-error
383 (lambda ()
384 (proc device))
385 (lambda args
386 ;; When running on the hand-made /dev,
387 ;; 'disk-partitions' could return partitions for which
388 ;; we have no /dev node. Handle that gracefully.
389 (let ((errno (system-error-errno args)))
390 (cond ((= ENOENT errno)
391 (format (current-error-port)
392 "warning: device '~a' not found~%" device)
393 #f)
394 ((= ENOMEDIUM errno) ;for removable media
395 #f)
396 (else
397 (apply throw args))))))))
398
399 (define (partition-field-reader read field)
400 "Return a procedure that takes a device and returns the value of a FIELD in
401 the partition superblock or #f."
402 (let ((read (ENOENT-safe read)))
403 (lambda (device)
404 (let ((sblock (read device)))
405 (and sblock
406 (field sblock))))))
407
408 (define (read-partition-field device partition-field-readers)
409 "Returns the value of a FIELD in the partition superblock of DEVICE or #f. It
410 takes a list of PARTITION-FIELD-READERS and returns the result of the first
411 partition field reader that returned a value."
412 (match (filter-map (cut apply <> (list device)) partition-field-readers)
413 ((field . _) field)
414 (_ #f)))
415
416 (define %partition-label-readers
417 (list (partition-field-reader read-iso9660-superblock
418 iso9660-superblock-volume-name)
419 (partition-field-reader read-ext2-superblock
420 ext2-superblock-volume-name)
421 (partition-field-reader read-btrfs-superblock
422 btrfs-superblock-volume-name)
423 (partition-field-reader read-fat32-superblock
424 fat32-superblock-volume-name)))
425
426 (define %partition-uuid-readers
427 (list (partition-field-reader read-iso9660-superblock
428 iso9660-superblock-uuid)
429 (partition-field-reader read-ext2-superblock
430 ext2-superblock-uuid)
431 (partition-field-reader read-btrfs-superblock
432 btrfs-superblock-uuid)
433 (partition-field-reader read-fat32-superblock
434 fat32-superblock-uuid)))
435
436 (define read-partition-label
437 (cut read-partition-field <> %partition-label-readers))
438
439 (define read-partition-uuid
440 (cut read-partition-field <> %partition-uuid-readers))
441
442 (define (partition-predicate reader =)
443 "Return a predicate that returns true if the FIELD of partition header that
444 was READ is = to the given value."
445 (lambda (expected)
446 (lambda (device)
447 (let ((actual (reader device)))
448 (and actual
449 (= actual expected))))))
450
451 (define partition-label-predicate
452 (partition-predicate read-partition-label string=?))
453
454 (define partition-uuid-predicate
455 (partition-predicate read-partition-uuid bytevector=?))
456
457 (define luks-partition-uuid-predicate
458 (partition-predicate
459 (partition-field-reader read-luks-header luks-header-uuid)
460 bytevector=?))
461
462 (define (find-partition predicate)
463 "Return the first partition found that matches PREDICATE, or #f if none
464 were found."
465 (lambda (expected)
466 (find (predicate expected)
467 (map (cut string-append "/dev/" <>)
468 (disk-partitions)))))
469
470 (define find-partition-by-label
471 (find-partition partition-label-predicate))
472
473 (define find-partition-by-uuid
474 (find-partition partition-uuid-predicate))
475
476 (define find-partition-by-luks-uuid
477 (find-partition luks-partition-uuid-predicate))
478
479 \f
480 ;;;
481 ;;; UUIDs.
482 ;;;
483
484 (define-syntax %network-byte-order
485 (identifier-syntax (endianness big)))
486
487 (define (uuid->string uuid)
488 "Convert UUID, a 16-byte bytevector, to its string representation, something
489 like \"6b700d61-5550-48a1-874c-a3d86998990e\"."
490 ;; See <https://tools.ietf.org/html/rfc4122>.
491 (let ((time-low (bytevector-uint-ref uuid 0 %network-byte-order 4))
492 (time-mid (bytevector-uint-ref uuid 4 %network-byte-order 2))
493 (time-hi (bytevector-uint-ref uuid 6 %network-byte-order 2))
494 (clock-seq (bytevector-uint-ref uuid 8 %network-byte-order 2))
495 (node (bytevector-uint-ref uuid 10 %network-byte-order 6)))
496 (format #f "~8,'0x-~4,'0x-~4,'0x-~4,'0x-~12,'0x"
497 time-low time-mid time-hi clock-seq node)))
498
499 (define %uuid-rx
500 ;; The regexp of a UUID.
501 (make-regexp "^([[:xdigit:]]{8})-([[:xdigit:]]{4})-([[:xdigit:]]{4})-([[:xdigit:]]{4})-([[:xdigit:]]{12})$"))
502
503 (define (string->uuid str)
504 "Parse STR as a DCE UUID (see <https://tools.ietf.org/html/rfc4122>) and
505 return its contents as a 16-byte bytevector. Return #f if STR is not a valid
506 UUID representation."
507 (and=> (regexp-exec %uuid-rx str)
508 (lambda (match)
509 (letrec-syntax ((hex->number
510 (syntax-rules ()
511 ((_ index)
512 (string->number (match:substring match index)
513 16))))
514 (put!
515 (syntax-rules ()
516 ((_ bv index (number len) rest ...)
517 (begin
518 (bytevector-uint-set! bv index number
519 (endianness big) len)
520 (put! bv (+ index len) rest ...)))
521 ((_ bv index)
522 bv))))
523 (let ((time-low (hex->number 1))
524 (time-mid (hex->number 2))
525 (time-hi (hex->number 3))
526 (clock-seq (hex->number 4))
527 (node (hex->number 5))
528 (uuid (make-bytevector 16)))
529 (put! uuid 0
530 (time-low 4) (time-mid 2) (time-hi 2)
531 (clock-seq 2) (node 6)))))))
532
533 \f
534 (define* (canonicalize-device-spec spec #:optional (title 'any))
535 "Return the device name corresponding to SPEC. TITLE is a symbol, one of
536 the following:
537
538 • 'device', in which case SPEC is known to designate a device node--e.g.,
539 \"/dev/sda1\";
540 • 'label', in which case SPEC is known to designate a partition label--e.g.,
541 \"my-root-part\";
542 • 'uuid', in which case SPEC must be a UUID (a 16-byte bytevector)
543 designating a partition;
544 • 'any', in which case SPEC can be anything.
545 "
546 (define max-trials
547 ;; Number of times we retry partition label resolution, 1 second per
548 ;; trial. Note: somebody reported a delay of 16 seconds (!) before their
549 ;; USB key would be detected by the kernel, so we must wait for at least
550 ;; this long.
551 20)
552
553 (define canonical-title
554 ;; The realm of canonicalization.
555 (if (eq? title 'any)
556 (if (string? spec)
557 ;; The "--root=SPEC" kernel command-line option always provides a
558 ;; string, but the string can represent a device, a UUID, or a
559 ;; label. So check for all three.
560 (cond ((string-prefix? "/" spec) 'device)
561 ((string->uuid spec) 'uuid)
562 (else 'label))
563 'uuid)
564 title))
565
566 (define (resolve find-partition spec fmt)
567 (let loop ((count 0))
568 (let ((device (find-partition spec)))
569 (or device
570 ;; Some devices take a bit of time to appear, most notably USB
571 ;; storage devices. Thus, wait for the device to appear.
572 (if (> count max-trials)
573 (error "failed to resolve partition" (fmt spec))
574 (begin
575 (format #t "waiting for partition '~a' to appear...~%"
576 (fmt spec))
577 (sleep 1)
578 (loop (+ 1 count))))))))
579
580 (case canonical-title
581 ((device)
582 ;; Nothing to do.
583 spec)
584 ((label)
585 ;; Resolve the label.
586 (resolve find-partition-by-label spec identity))
587 ((uuid)
588 (resolve find-partition-by-uuid
589 (if (string? spec)
590 (string->uuid spec)
591 spec)
592 uuid->string))
593 (else
594 (error "unknown device title" title))))
595
596 (define (check-file-system device type)
597 "Run a file system check of TYPE on DEVICE."
598 (define check-procedure
599 (cond
600 ((string-prefix? "ext" type) check-ext2-file-system)
601 ((string-prefix? "btrfs" type) check-btrfs-file-system)
602 ((string-suffix? "fat" type) check-fat32-file-system)
603 (else #f)))
604
605 (if check-procedure
606 (match (check-procedure device)
607 ('pass
608 #t)
609 ('errors-corrected
610 (format (current-error-port)
611 "File system check corrected errors on ~a; continuing~%"
612 device))
613 ('reboot-required
614 (format (current-error-port)
615 "File system check corrected errors on ~a; rebooting~%"
616 device)
617 (sleep 3)
618 (reboot))
619 ('fatal-error
620 (format (current-error-port)
621 "File system check on ~a failed; spawning Bourne-like REPL~%"
622 device)
623 (start-repl %bournish-language)))
624 (format (current-error-port)
625 "No file system check procedure for ~a; skipping~%"
626 device)))
627
628 (define (mount-flags->bit-mask flags)
629 "Return the number suitable for the 'flags' argument of 'mount' that
630 corresponds to the symbols listed in FLAGS."
631 (let loop ((flags flags))
632 (match flags
633 (('read-only rest ...)
634 (logior MS_RDONLY (loop rest)))
635 (('bind-mount rest ...)
636 (logior MS_BIND (loop rest)))
637 (('no-suid rest ...)
638 (logior MS_NOSUID (loop rest)))
639 (('no-dev rest ...)
640 (logior MS_NODEV (loop rest)))
641 (('no-exec rest ...)
642 (logior MS_NOEXEC (loop rest)))
643 (()
644 0))))
645
646 (define* (mount-file-system spec #:key (root "/root"))
647 "Mount the file system described by SPEC under ROOT. SPEC must have the
648 form:
649
650 (DEVICE TITLE MOUNT-POINT TYPE (FLAGS ...) OPTIONS CHECK?)
651
652 DEVICE, MOUNT-POINT, and TYPE must be strings; OPTIONS can be a string or #f;
653 FLAGS must be a list of symbols. CHECK? is a Boolean indicating whether to
654 run a file system check."
655
656 (define (mount-nfs source mount-point type flags options)
657 (let* ((idx (string-rindex source #\:))
658 (host-part (string-take source idx))
659 ;; Strip [] from around host if present
660 (host (match (string-split host-part (string->char-set "[]"))
661 (("" h "") h)
662 ((h) h)))
663 (aa (match (getaddrinfo host "nfs") ((x . _) x)))
664 (sa (addrinfo:addr aa))
665 (inet-addr (inet-ntop (sockaddr:fam sa)
666 (sockaddr:addr sa))))
667
668 ;; Mounting an NFS file system requires passing the address
669 ;; of the server in the addr= option
670 (mount source mount-point type flags
671 (string-append "addr="
672 inet-addr
673 (if options
674 (string-append "," options)
675 "")))))
676 (match spec
677 ((source title mount-point type (flags ...) options check?)
678 (let ((source (canonicalize-device-spec source title))
679 (mount-point (string-append root "/" mount-point))
680 (flags (mount-flags->bit-mask flags)))
681 (when check?
682 (check-file-system source type))
683
684 ;; Create the mount point. Most of the time this is a directory, but
685 ;; in the case of a bind mount, a regular file or socket may be needed.
686 (if (and (= MS_BIND (logand flags MS_BIND))
687 (not (file-is-directory? source)))
688 (unless (file-exists? mount-point)
689 (mkdir-p (dirname mount-point))
690 (call-with-output-file mount-point (const #t)))
691 (mkdir-p mount-point))
692
693 (cond
694 ((string-prefix? "nfs" type)
695 (mount-nfs source mount-point type flags options))
696 (else
697 (mount source mount-point type flags options)))
698
699 ;; For read-only bind mounts, an extra remount is needed, as per
700 ;; <http://lwn.net/Articles/281157/>, which still applies to Linux 4.0.
701 (when (and (= MS_BIND (logand flags MS_BIND))
702 (= MS_RDONLY (logand flags MS_RDONLY)))
703 (let ((flags (logior MS_BIND MS_REMOUNT MS_RDONLY)))
704 (mount source mount-point type flags #f)))))))
705
706 ;;; file-systems.scm ends here