code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014, 2015, 2016, 2017, 2018 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2016, 2017 David Craven <david@craven.ch>
;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2019 Guillaume Le Vaillant <glv@posteo.net>
;;; Copyright © 2019 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2019 David C. Trudgian <dave@trudgian.net>
;;; Copyright © 2020 Maxim Cournoyer <maxim.cournoyer@gmail.com>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu build file-systems)
  #:use-module (gnu system uuid)
  #:use-module (gnu system file-systems)
  #:use-module (guix build utils)
  #:use-module (guix build bournish)
  #:use-module ((guix build syscalls)
                #:hide (file-system-type))
  #:use-module (rnrs io ports)
  #:use-module (rnrs bytevectors)
  #:use-module (ice-9 match)
  #:use-module (ice-9 rdelim)
  #:use-module (system foreign)
  #:autoload   (system repl repl) (start-repl)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (disk-partitions
            partition-label-predicate
            partition-uuid-predicate
            partition-luks-uuid-predicate
            find-partition-by-label
            find-partition-by-uuid
            find-partition-by-luks-uuid
            canonicalize-device-spec

            read-partition-label
            read-partition-uuid
            read-luks-partition-uuid

            bind-mount

            mount-flags->bit-mask
            check-file-system
            mount-file-system))

;;; Commentary:
;;;
;;; This modules provides tools to deal with disk partitions, and to mount and
;;; check file systems.
;;;
;;; Code:

(define (bind-mount source target)
  "Bind-mount SOURCE at TARGET."
  (mount source target "" MS_BIND))

(define (seek* fd/port offset whence)
  "Like 'seek' but return -1 instead of throwing to 'system-error' upon
EINVAL.  This makes it easier to catch cases like OFFSET being too large for
FD/PORT."
  (catch 'system-error
    (lambda ()
      (seek fd/port offset whence))
    (lambda args
      (if (= EINVAL (system-error-errno args))
          -1
          (apply throw args)))))

(define (read-superblock device offset size magic?)
  "Read a superblock of SIZE from OFFSET and DEVICE.  Return the raw
superblock on success, and #f if no valid superblock was found.  MAGIC?
takes a bytevector and returns #t when it's a valid superblock."
  (call-with-input-file device
    (lambda (port)
      (and (= offset (seek* port offset SEEK_SET))
           (let ((block (make-bytevector size)))
             (match (get-bytevector-n! port block 0 (bytevector-length block))
               ((? eof-object?)
                #f)
               ((? number? len)
                (and (= len (bytevector-length block))
                     (and (magic? block)
                          block)))))))))

(define null-terminated-latin1->string
  (cut latin1->string <> zero?))

(define (bytevector-utf16-length bv)
  "Given a bytevector BV containing a NUL-terminated UTF16-encoded string,
determine where the NUL terminator is and return its index.  If there's no
NUL terminator, return the size of the bytevector."
  (let ((length (bytevector-length bv)))
    (let loop ((index 0))
      (if (< index length)
          (if (zero? (bytevector-u16-ref bv index 'little))
              index
              (loop (+ index 2)))
          length))))

(define* (bytevector->u16-list bv endianness #:optional (index 0))
  (if (< index (bytevector-length bv))
      (cons (bytevector-u16-ref bv index endianness)
            (bytevector->u16-list bv endianness (+ index 2)))
      '()))

;; The initrd doesn't have iconv data, so do the conversion ourselves.
(define (utf16->string bv endianness)
  (list->string
   (map integer->char
        (reverse
         (let loop ((remainder (bytevector->u16-list bv endianness))
                    (result '()))
             (match remainder
              (() result)
              ((a) (cons a result))
              ((a b x ...)
               (if (and (>= a #xD800) (< a #xDC00) ; high surrogate
                        (>= b #xDC00) (< b #xE000)) ; low surrogate
                   (loop x (cons (+ #x10000
                                    (* #x400 (- a #xD800))
                                    (- b #xDC00))
                                 result))
                   (loop (cons b x) (cons a result))))))))))

(define (null-terminated-utf16->string bv endianness)
  (utf16->string (sub-bytevector bv 0 (bytevector-utf16-length bv))
                 endianness))

;;;
;;; Ext2 file systems.
;;;

;; <http://www.nongnu.org/ext2-doc/ext2.html#DEF-SUPERBLOCK>.
;; TODO: Use "packed structs" from Guile-OpenGL or similar.

(define-syntax %ext2-endianness
  ;; Endianness of ext2 file systems.
  (identifier-syntax (endianness little)))

(define (ext2-superblock? sblock)
  "Return #t when SBLOCK is an ext2 superblock."
  (let ((magic (bytevector-u16-ref sblock 56 %ext2-endianness)))
    (= magic #xef53)))

(define (read-ext2-superblock device)
  "Return the raw contents of DEVICE's ext2 superblock as a bytevector, or #f
if DEVICE does not contain an ext2 file system."
  (read-superblock device 1024 264 ext2-superblock?))

(define (ext2-superblock-uuid sblock)
  "Return the UUID of ext2 superblock SBLOCK as a 16-byte bytevector."
  (sub-bytevector sblock 104 16))

(define (ext2-superblock-volume-name sblock)
  "Return the volume name of SBLOCK as a string of at most 16 characters, or
#f if SBLOCK has no volume name."
  (null-terminated-latin1->string (sub-bytevector sblock 120 16)))

(define (check-ext2-file-system device)
  "Return the health of an ext2 file system on DEVICE."
  (match (status:exit-val
          (system* "e2fsck" "-v" "-p" "-C" "0" device))
    (0 'pass)
    (1 'errors-corrected)
    (2 'reboot-required)
    (_ 'fatal-error)))

;;;
;;; Btrfs file systems.
;;;

;; <https://btrfs.wiki.kernel.org/index.php/On-disk_Format#Superblock>.

(define-syntax %btrfs-endianness
  ;; Endianness of btrfs file systems.
  (identifier-syntax (endianness little)))

(define (btrfs-superblock? sblock)
  "Return #t when SBLOCK is a btrfs superblock."
  (bytevector=? (sub-bytevector sblock 64 8)
                (string->utf8 "_BHRfS_M")))

(define (read-btrfs-superblock device)
  "Return the raw contents of DEVICE's btrfs superblock as a bytevector, or #f
if DEVICE does not contain a btrfs file system."
  (read-superblock device 65536 4096 btrfs-superblock?))

(define (btrfs-superblock-uuid sblock)
  "Return the UUID of a btrfs superblock SBLOCK as a 16-byte bytevector."
  (sub-bytevector sblock 32 16))

(define (btrfs-superblock-volume-name sblock)
  "Return the volume name of SBLOCK as a string of at most 256 characters, or
#f if SBLOCK has no volume name."
  (null-terminated-latin1->string (sub-bytevector sblock 299 256)))

(define (check-btrfs-file-system device)
  "Return the health of a btrfs file system on DEVICE."
  (match (status:exit-val
          (system* "btrfs" "device" "scan"))
    (0 'pass)
    (_ 'fatal-error)))

;;;
;;; FAT32 file systems.
;;;

;; <http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-107.pdf>.

(define (fat32-superblock? sblock)
  "Return #t when SBLOCK is a fat32 superblock."
  (bytevector=? (sub-bytevector sblock 82 8)
                (string->utf8 "FAT32   ")))

(define (read-fat32-superblock device)
  "Return the raw contents of DEVICE's fat32 superblock as a bytevector, or
#f if DEVICE does not contain a fat32 file system."
  (read-superblock device 0 90 fat32-superblock?))

(define (fat32-superblock-uuid sblock)
  "Return the Volume ID of a fat superblock SBLOCK as a 4-byte bytevector."
  (sub-bytevector sblock 67 4))

(define (fat32-superblock-volume-name sblock)
  "Return the volume name of SBLOCK as a string of at most 11 characters, or
#f if SBLOCK has no volume name.  The volume name is a latin1 string.
Trailing spaces are trimmed."
  (string-trim-right (latin1->string (sub-bytevector sblock 71 11) (lambda (c) #f)) #\space))

(define (check-fat-file-system device)
  "Return the health of a fat file system on DEVICE."
  (match (status:exit-val
          (system* "fsck.vfat" "-v" "-a" device))
    (0 'pass)
    (1 'errors-corrected)
    (_ 'fatal-error)))

;;;
;;; FAT16 file systems.
;;;

(define (fat16-superblock? sblock)
  "Return #t when SBLOCK is a fat16 boot record."
  (bytevector=? (sub-bytevector sblock 54 8)
                (string->utf8 "FAT16   ")))

(define (read-fat16-superblock device)
  "Return the raw contents of DEVICE's fat16 superblock as a bytevector, or
#f if DEVICE does not contain a fat16 file system."
  (read-superblock device 0 62 fat16-superblock?))

(define (fat16-superblock-uuid sblock)
  "Return the Volume ID of a fat superblock SBLOCK as a 4-byte bytevector."
  (sub-bytevector sblock 39 4))

(define (fat16-superblock-volume-name sblock)
  "Return the volume name of SBLOCK as a string of at most 11 characters, or
#f if SBLOCK has no volume name.  The volume name is a latin1 string.
Trailing spaces are trimmed."
  (string-trim-right (latin1->string (sub-bytevector sblock 43 11)
                                     (lambda (c) #f))
                     #\space))

;;;
;;; ISO9660 file systems.
;;;

;; <http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-119.pdf>.

(define (iso9660-superblock? sblock)
  "Return #t when SBLOCK is an iso9660 volume descriptor."
  (bytevector=? (sub-bytevector sblock 1 6)
                ;; Note: "\x01" is the volume descriptor format version
                (string->utf8 "CD001\x01")))

(define (read-iso9660-primary-volume-descriptor device offset)
  "Find and read the first primary volume descriptor, starting at OFFSET.
   Return #f if not found."
  (let* ((sblock    (read-superblock device offset 2048 iso9660-superblock?))
         (type-code (if sblock
                        (bytevector-u8-ref sblock 0)
                        (error (format #f
                                       "Could not read ISO9660 primary
volume descriptor from ~s"
                                       device)))))
    (match type-code
      (255 #f) ; Volume Descriptor Set Terminator.
      (1 sblock) ; Primary Volume Descriptor
      (_ (read-iso9660-primary-volume-descriptor device (+ offset 2048))))))

(define (read-iso9660-superblock device)
  "Return the raw contents of DEVICE's iso9660 primary volume descriptor
as a bytevector, or #f if DEVICE does not contain an iso9660 file system."
  ;; Start reading at sector 16.
  ;; Since we are not sure that the device contains an ISO9660 file system,
  ;; we have to find that out first.
  (if (read-superblock device (* 2048 16) 2048 iso9660-superblock?)
      (read-iso9660-primary-volume-descriptor device (* 2048 16))
      #f)) ; Device does not contain an iso9660 file system.

(define (iso9660-superblock-uuid sblock)
  "Return the modification time of an iso9660 primary volume descriptor
SBLOCK as a bytevector.  If that's not set, returns the creation time."
  ;; Drops GMT offset for compatibility with Grub, blkid and /dev/disk/by-uuid.
  ;; Compare Grub: "2014-12-02-19-30-23-00".
  ;; Compare blkid result: "2014-12-02-19-30-23-00".
  ;; Compare /dev/disk/by-uuid entry: "2014-12-02-19-30-23-00".
  (let* ((creation-time (sub-bytevector sblock 813 17))
         (modification-time (sub-bytevector sblock 830 17))
         (unset-time (make-bytevector 17 0))
         (time (if (bytevector=? unset-time modification-time)
                   creation-time
                   modification-time)))
    (sub-bytevector time 0 16))) ; strips GMT offset.

(define (iso9660-superblock-volume-name sblock)
  "Return the volume name of SBLOCK as a string.  The volume name is an ASCII
string.  Trailing spaces are trimmed."
  ;; Note: Valid characters are of the set "[0-9][A-Z]_" (ECMA-119 Appendix A)
  (string-trim-right (latin1->string (sub-bytevector sblock 40 32)
                                     (lambda (c) #f)) #\space))

;;;
;;; JFS file systems.
;;;

;; Taken from <linux-libre>/fs/jfs/jfs_superblock.h.

(define-syntax %jfs-endianness
  ;; Endianness of JFS file systems.
  (identifier-syntax (endianness little)))

(define (jfs-superblock? sblock)
  "Return #t when SBLOCK is a JFS superblock."
  (bytevector=? (sub-bytevector sblock 0 4)
                (string->utf8 "JFS1")))

(define (read-jfs-superblock device)
  "Return the raw contents of DEVICE's JFS superblock as a bytevector, or #f
if DEVICE does not contain a JFS file system."
  (read-superblock device 32768 184 jfs-superblock?))

(define (jfs-superblock-uuid sblock)
  "Return the UUID of JFS superblock SBLOCK as a 16-byte bytevector."
  (sub-bytevector sblock 136 16))

(define (jfs-superblock-volume-name sblock)
  "Return the volume name of SBLOCK as a string of at most 16 characters, or
#f if SBLOCK has no volume name."
  (null-terminated-latin1->string (sub-bytevector sblock 152 16)))

(define (check-jfs-file-system device)
  "Return the health of a JFS file system on DEVICE."
  (match (status:exit-val
          (system* "jfs_fsck" "-p" "-v" device))
    (0 'pass)
    (1 'errors-corrected)
    (2 'reboot-required)
    (_ 'fatal-error)))

;;;
;;; F2FS (Flash-Friendly File System)
;;;

;;; https://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk/f2fs.git/tree/include/linux/f2fs_fs.h
;;; (but using xxd proved to be simpler)

(define-syntax %f2fs-endianness
  ;; Endianness of F2FS file systems
  (identifier-syntax (endianness little)))

;; F2FS actually stores two adjacent copies of the superblock.
;; should we read both?
(define (f2fs-superblock? sblock)
  "Return #t when SBLOCK is an F2FS superblock."
  (let ((magic (bytevector-u32-ref sblock 0 %f2fs-endianness)))
    (= magic #xF2F52010)))

(define (read-f2fs-superblock device)
  "Return the raw contents of DEVICE's F2FS superblock as a bytevector, or #f
if DEVICE does not contain an F2FS file system."
  (read-superblock device
                   ;; offset of magic in first copy
                   #x400
                   ;; difference between magic of second
                   ;; and first copies
                   (- #x1400 #x400)
                   f2fs-superblock?))

(define (f2fs-superblock-uuid sblock)
  "Return the UUID of F2FS superblock SBLOCK as a 16-byte bytevector."
  (sub-bytevector sblock
                  (- (+ #x460 12)
                     ;; subtract superblock offset
                     #x400)
                  16))

(define (f2fs-superblock-volume-name sblock)
  "Return the volume name of SBLOCK as a string of at most 512 characters, or
#f if SBLOCK has no volume name."
  (null-terminated-utf16->string
   (sub-bytevector sblock (- (+ #x470 12) #x400) 512)
   %f2fs-endianness))

(define (check-f2fs-file-system device)
  "Return the health of a F2FS file system on DEVICE."
  (match (status:exit-val
          (system* "fsck.f2fs" "-p" device))
    ;; 0 and -1 are the only two possibilities
    ;; (according to the manpage)
    (0 'pass)
    (_ 'fatal-error)))

;;;
;;; LUKS encrypted devices.
;;;

;; The LUKS header format is described in "LUKS On-Disk Format Specification":
;; <https://gitlab.com/cryptsetup/cryptsetup/wikis/Specification>.  We follow
;; version 1.2.1 of this document.

;; The LUKS2 header format is described in "LUKS2 On-Disk Format Specification":
;; <https://gitlab.com/cryptsetup/LUKS2-docs/blob/master/luks2_doc_wip.pdf>.
;; It is a WIP document.

(define-syntax %luks-endianness
  ;; Endianness of LUKS headers.
  (identifier-syntax (endianness big)))

(define (luks-superblock? sblock)
  "Return #t when SBLOCK is a luks superblock."
  (define %luks-magic
    ;; The 'LUKS_MAGIC' constant.
    (u8-list->bytevector (append (map char->integer (string->list "LUKS"))
                                 (list #xba #xbe))))
  (let ((magic   (sub-bytevector sblock 0 6))
        (version (bytevector-u16-ref sblock 6 %luks-endianness)))
    (and (bytevector=? magic %luks-magic)
         (or (= version 1) (= version 2)))))

(define (read-luks-header file)
  "Read a LUKS header from FILE.  Return the raw header on success, and #f if
not valid header was found."
  ;; Size in bytes of the LUKS binary header, which includes key slots in
  ;; LUKS1.  In LUKS2 the binary header is partially backward compatible, so
  ;; that UUID can be extracted as for LUKS1. Keyslots and other metadata are
  ;; not part of this header in LUKS2, but are included in the JSON metadata
  ;; area that follows.
  (read-superblock file 0 592 luks-superblock?))

(define (luks-header-uuid header)
  "Return the LUKS UUID from HEADER, as a 16-byte bytevector."
  ;; 40 bytes are reserved for the UUID, but in practice, it contains the 36
  ;; bytes of its ASCII representation.
  (let ((uuid (sub-bytevector header 168 36)))
    (string->uuid (utf8->string uuid))))

;;;
;;; NTFS file systems.
;;;

;; Taken from <linux-libre>/fs/ntfs/layout.h

(define-syntax %ntfs-endianness
  ;; Endianness of NTFS file systems.
  (identifier-syntax (endianness little)))

(define (ntfs-superblock? sblock)
  "Return #t when SBLOCK is a NTFS superblock."
  (bytevector=? (sub-bytevector sblock 3 8)
                (string->utf8 "NTFS    ")))

(define (read-ntfs-superblock device)
  "Return the raw contents of DEVICE's NTFS superblock as a bytevector, or #f
if DEVICE does not contain a NTFS file system."
  (read-superblock device 0 511 ntfs-superblock?))

(define (ntfs-superblock-uuid sblock)
  "Return the UUID of NTFS superblock SBLOCK as a 8-byte bytevector."
  (sub-bytevector sblock 72 8))

;; TODO: Add ntfs-superblock-volume-name.  The partition label is not stored
;; in the BOOT SECTOR like the UUID, but in the MASTER FILE TABLE, which seems
;; way harder to access.

(define (check-ntfs-file-system device)
  "Return the health of a NTFS file system on DEVICE."
  (match (status:exit-val
          (system* "ntfsfix" device))
    (0 'pass)
    (_ 'fatal-error)))

;;;
;;; Partition lookup.
;;;

(define (disk-partitions)
  "Return the list of device names corresponding to valid disk partitions."
  (define (partition? name major minor)
    ;; grub-mkrescue does some funny things for EFI support which
    ;; makes it a lot more difficult than one would expect to support
    ;; booting an ISO-9660 image from an USB flash drive.
    ;; For example there's a buggy (too small) hidden partition in it
    ;; which Linux mounts and then proceeds to fail while trying to
    ;; fall off the edge.
    ;; In any case, partition tables are supposed to be optional so
    ;; here we allow checking entire disks for file systems, too.
    (> major 2))                      ;ignore RAM disks and floppy disks

  (call-with-input-file "/proc/partitions"
    (lambda (port)
      ;; Skip the two header lines.
      (read-line port)
      (read-line port)

      ;; Read each subsequent line, and extract the last space-separated
      ;; field.
      (let loop ((parts '()))
        (let ((line  (read-line port)))
          (if (eof-object? line)
              (reverse parts)
              (match (string-tokenize line)
                (((= string->number major) (= string->number minor)
                  blocks name)
                 (if (partition? name major minor)
                     (loop (cons name parts))
                     (loop parts))))))))))

(define (ENOENT-safe proc)
  "Wrap the one-argument PROC such that ENOENT errors are caught and lead to a
warning and #f as the result."
  (lambda (device)
    (catch 'system-error
      (lambda ()
        (proc device))
      (lambda args
        ;; When running on the hand-made /dev,
        ;; 'disk-partitions' could return partitions for which
        ;; we have no /dev node.  Handle that gracefully.
        (let ((errno (system-error-errno args)))
          (cond ((= ENOENT errno)
                 (format (current-error-port)
                         "warning: device '~a' not found~%" device)
                 #f)
                ((= ENOMEDIUM errno)              ;for removable media
                 #f)
                ((= EIO errno)                    ;unreadable hardware like audio CDs
                 (format (current-error-port)
                         "warning: failed to read from device '~a'~%" device)
                 #f)
                (else
                 (apply throw args))))))))

(define (partition-field-reader read field)
  "Return a procedure that takes a device and returns the value of a FIELD in
the partition superblock or #f."
  (let ((read (ENOENT-safe read)))
    (lambda (device)
      (let ((sblock (read device)))
        (and sblock
             (field sblock))))))

(define (read-partition-field device partition-field-readers)
  "Returns the value of a FIELD in the partition superblock of DEVICE or #f. It
takes a list of PARTITION-FIELD-READERS and returns the result of the first
partition field reader that returned a value."
  (match (filter-map (cut apply <> (list device)) partition-field-readers)
    ((field . _) field)
    (_ #f)))

(define %partition-label-readers
  (list (partition-field-reader read-iso9660-superblock
                                iso9660-superblock-volume-name)
        (partition-field-reader read-ext2-superblock
                                ext2-superblock-volume-name)
        (partition-field-reader read-btrfs-superblock
                                btrfs-superblock-volume-name)
        (partition-field-reader read-fat32-superblock
                                fat32-superblock-volume-name)
        (partition-field-reader read-fat16-superblock
                                fat16-superblock-volume-name)
        (partition-field-reader read-jfs-superblock
                                jfs-superblock-volume-name)
        (partition-field-reader read-f2fs-superblock
                                f2fs-superblock-volume-name)))

(define %partition-uuid-readers
  (list (partition-field-reader read-iso9660-superblock
                                iso9660-superblock-uuid)
        (partition-field-reader read-ext2-superblock
                                ext2-superblock-uuid)
        (partition-field-reader read-btrfs-superblock
                                btrfs-superblock-uuid)
        (partition-field-reader read-fat32-superblock
                                fat32-superblock-uuid)
        (partition-field-reader read-fat16-superblock
                                fat16-superblock-uuid)
        (partition-field-reader read-jfs-superblock
                                jfs-superblock-uuid)
        (partition-field-reader read-f2fs-superblock
                                f2fs-superblock-uuid)
        (partition-field-reader read-ntfs-superblock
                                ntfs-superblock-uuid)))

(define read-partition-label
  (cut read-partition-field <> %partition-label-readers))

(define read-partition-uuid
  (cut read-partition-field <> %partition-uuid-readers))

(define luks-partition-field-reader
  (partition-field-reader read-luks-header luks-header-uuid))

(define read-luks-partition-uuid
  (cut read-partition-field <> (list luks-partition-field-reader)))

(define (partition-predicate reader =)
  "Return a predicate that returns true if the FIELD of partition header that
was READ is = to the given value."
  (lambda (expected)
    (lambda (device)
      (let ((actual (reader device)))
        (and actual
             (= actual expected))))))

(define partition-label-predicate
  (partition-predicate read-partition-label string=?))

(define partition-uuid-predicate
  (partition-predicate read-partition-uuid uuid=?))

(define luks-partition-uuid-predicate
  (partition-predicate luks-partition-field-reader uuid=?))

(define (find-partition predicate)
  "Return the first partition found that matches PREDICATE, or #f if none
were found."
  (lambda (expected)
    (find (predicate expected)
          (map (cut string-append "/dev/" <>)
               (disk-partitions)))))

(define find-partition-by-label
  (find-partition partition-label-predicate))

(define find-partition-by-uuid
  (find-partition partition-uuid-predicate))

(define find-partition-by-luks-uuid
  (find-partition luks-partition-uuid-predicate))

(define (canonicalize-device-spec spec)
  "Return the device name corresponding to SPEC, which can be a <uuid>, a
<file-system-label>, or a string (typically a /dev file name or an nfs-root
containing ':/')."
  (define max-trials
    ;; Number of times we retry partition label resolution, 1 second per
    ;; trial.  Note: somebody reported a delay of 16 seconds (!) before their
    ;; USB key would be detected by the kernel, so we must wait for at least
    ;; this long.
    20)

  (define (resolve find-partition spec fmt)
    (let loop ((count 0))
      (let ((device (find-partition spec)))
        (or device
            ;; Some devices take a bit of time to appear, most notably USB
            ;; storage devices.  Thus, wait for the device to appear.
            (if (> count max-trials)
                (error "failed to resolve partition" (fmt spec))
                (begin
                  (format #t "waiting for partition '~a' to appear...~%"
                          (fmt spec))
                  (sleep 1)
                  (loop (+ 1 count))))))))

  (match spec
    ((? string?)
     (if (string-contains spec ":/")
         spec                  ; do not resolve NFS devices
         ;; Nothing to do, but wait until SPEC shows up.
         (resolve identity spec identity)))
    ((? file-system-label?)
     ;; Resolve the label.
     (resolve find-partition-by-label
              (file-system-label->string spec)
              identity))
    ((? uuid?)
     (resolve find-partition-by-uuid
              (uuid-bytevector spec)
              uuid->string))))

(define (check-file-system device type)
  "Run a file system check of TYPE on DEVICE."
  (define check-procedure
    (cond
     ((string-prefix? "ext" type) check-ext2-file-system)
     ((string-prefix? "btrfs" type) check-btrfs-file-system)
     ((string-suffix? "fat" type) check-fat-file-system)
     ((string-prefix? "jfs" type) check-jfs-file-system)
     ((string-prefix? "f2fs" type) check-f2fs-file-system)
     ((string-prefix? "ntfs" type) check-ntfs-file-system)
     ((string-prefix? "nfs" type) (const 'pass))
     (else #f)))

  (if check-procedure
      (match (check-procedure device)
        ('pass
         #t)
        ('errors-corrected
         (format (current-error-port)
                 "File system check corrected errors on ~a; continuing~%"
                 device))
        ('reboot-required
         (format (current-error-port)
                 "File system check corrected errors on ~a; rebooting~%"
                 device)
         (sleep 3)
         (reboot))
        ('fatal-error
         (format (current-error-port) "File system check on ~a failed~%"
                 device)

         ;; Spawn a REPL only if someone would be able to interact with it.
         (when (isatty? (current-input-port))
           (format (current-error-port) "Spawning Bourne-like REPL.~%")

           ;; 'current-output-port' is typically connected to /dev/klog (in
           ;; PID 1), but here we want to make sure we talk directly to the
           ;; user.
           (with-output-to-file "/dev/console"
             (lambda ()
               (start-repl %bournish-language))))))
      (format (current-error-port)
              "No file system check procedure for ~a; skipping~%"
              device)))

(define (mount-flags->bit-mask flags)
  "Return the number suitable for the 'flags' argument of 'mount' that
corresponds to the symbols listed in FLAGS."
  (let loop ((flags flags))
    (match flags
      (('read-only rest ...)
       (logior MS_RDONLY (loop rest)))
      (('bind-mount rest ...)
       (logior MS_BIND (loop rest)))
      (('no-suid rest ...)
       (logior MS_NOSUID (loop rest)))
      (('no-dev rest ...)
       (logior MS_NODEV (loop rest)))
      (('no-exec rest ...)
       (logior MS_NOEXEC (loop rest)))
      (('no-atime rest ...)
       (logior MS_NOATIME (loop rest)))
      (('strict-atime rest ...)
       (logior MS_STRICTATIME (loop rest)))
      (('lazy-time rest ...)
       (logior MS_LAZYTIME (loop rest)))
      (()
       0))))

(define* (mount-file-system fs #:key (root "/root"))
  "Mount the file system described by FS, a <file-system> object, under ROOT."

  (define (mount-nfs source mount-point type flags options)
    (let* ((idx (string-rindex source #\:))
           (host-part (string-take source idx))
           ;; Strip [] from around host if present
           (host (match (string-split host-part (string->char-set "[]"))
                 (("" h "") h)
                 ((h) h)))
           (aa (match (getaddrinfo host "nfs") ((x . _) x)))
           (sa (addrinfo:addr aa))
           (inet-addr (inet-ntop (sockaddr:fam sa)
                                 (sockaddr:addr sa))))

      ;; Mounting an NFS file system requires passing the address
      ;; of the server in the addr= option
      (mount source mount-point type flags
             (string-append "addr="
                            inet-addr
                            (if options
                                (string-append "," options)
                                "")))))
  (let ((type        (file-system-type fs))
        (options     (file-system-options fs))
        (source      (canonicalize-device-spec (file-system-device fs)))
        (mount-point (string-append root "/"
                                    (file-system-mount-point fs)))
        (flags       (mount-flags->bit-mask (file-system-flags fs))))
    (when (file-system-check? fs)
      (check-file-system source type))

    (catch 'system-error
      (lambda ()
        ;; Create the mount point.  Most of the time this is a directory, but
        ;; in the case of a bind mount, a regular file or socket may be
        ;; needed.
        (if (and (= MS_BIND (logand flags MS_BIND))
                 (not (file-is-directory? source)))
            (unless (file-exists? mount-point)
              (mkdir-p (dirname mount-point))
              (call-with-output-file mount-point (const #t)))
            (mkdir-p mount-point))

        (cond
         ((string-prefix? "nfs" type)
          (mount-nfs source mount-point type flags options))
         (else
          (mount source mount-point type flags options)))

        ;; For read-only bind mounts, an extra remount is needed, as per
        ;; <http://lwn.net/Articles/281157/>, which still applies to Linux
        ;; 4.0.
        (when (and (= MS_BIND (logand flags MS_BIND))
                   (= MS_RDONLY (logand flags MS_RDONLY)))
          (let ((flags (logior MS_BIND MS_REMOUNT MS_RDONLY)))
            (mount source mount-point type flags #f))))
      (lambda args
        (or (file-system-mount-may-fail? fs)
            (apply throw args))))))

;;; file-systems.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu build hurd-boot)
  #:use-module (system repl error-handling)
  #:autoload   (system repl repl) (start-repl)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 match)
  #:use-module (guix build utils)
  #:use-module ((guix build syscalls)
                #:hide (file-system-type))
  #:export (make-hurd-device-nodes
            boot-hurd-system))

;;; Commentary:
;;;
;;; Utility procedures useful to boot a Hurd system.
;;;
;;; Code:

;; XXX FIXME c&p from linux-boot.scm
(define (find-long-option option arguments)
  "Find OPTION among ARGUMENTS, where OPTION is something like \"--load\".
Return the value associated with OPTION, or #f on failure."
  (let ((opt (string-append option "=")))
    (and=> (find (cut string-prefix? opt <>)
                 arguments)
           (lambda (arg)
             (substring arg (+ 1 (string-index arg #\=)))))))

;; XXX FIXME c&p from guix/utils.scm
(define (readlink* file)
  "Call 'readlink' until the result is not a symlink."
  (define %max-symlink-depth 50)

  (let loop ((file  file)
             (depth 0))
    (define (absolute target)
      (if (absolute-file-name? target)
          target
          (string-append (dirname file) "/" target)))

    (if (>= depth %max-symlink-depth)
        file
        (call-with-values
            (lambda ()
              (catch 'system-error
                (lambda ()
                  (values #t (readlink file)))
                (lambda args
                  (let ((errno (system-error-errno args)))
                    (if (or (= errno EINVAL))
                        (values #f file)
                        (apply throw args))))))
          (lambda (success? target)
            (if success?
                (loop (absolute target) (+ depth 1))
                file))))))

(define* (make-hurd-device-nodes #:optional (root "/"))
  "Make some of the nodes needed on GNU/Hurd."
  (define (scope dir)
    (string-append root (if (string-suffix? "/" root) "" "/") dir))

  (mkdir (scope "dev"))
  ;; Don't create /dev/null etc just yet; the store
  ;; messes-up the permission bits.
  ;; Don't create /dev/console, /dev/vcs, etc.: they are created by
  ;; console-run on first boot.

  (mkdir (scope "servers"))
  (for-each (lambda (file)
              (call-with-output-file (scope (string-append "servers/" file))
                (lambda (port)
                  (display file port)   ;avoid hard-linking
                  (chmod port #o444))))
            '("startup"
              "exec"
              "proc"
              "password"
              "default-pager"
              "crash-dump-core"
              "kill"
              "suspend"))

  (mkdir (scope "servers/socket"))
  ;; Don't create /servers/socket/1 & co: runsystem does that on first boot.

  ;; TODO: Set the 'gnu.translator' extended attribute for passive translator
  ;; settings?
  )

(define (passive-translator-xattr? file-name)
  "Return true if FILE-NAME has an extended @code{gnu.translator} attribute
set."
  (catch 'system-error
    (lambda _ (not (string-null? (getxattr file-name "gnu.translator"))))
    (lambda args
      (if (= ENODATA (system-error-errno args))
          #f
          (apply throw args)))))

(define (passive-translator-installed? file-name)
  "Return true if @file{showtrans} finds a translator installed on FILE-NAME."
  (with-output-to-port (%make-void-port "w")
    (lambda _
      (with-error-to-port (%make-void-port "w")
        (lambda _
          (zero? (system* "showtrans" "--silent" file-name)))))))

(define (translated? file-name)
  "Return true if a translator is installed on FILE-NAME."
  (if (string-contains %host-type "linux-gnu")
      (passive-translator-xattr? file-name)
      (passive-translator-installed? file-name)))

(define* (set-translator file-name command #:optional (mode #o600))
  "Setup translator COMMAND on FILE-NAME."
  (unless (translated? file-name)
    (let ((dir (dirname file-name)))
      (unless (directory-exists? dir)
        (mkdir-p dir))
      (unless (file-exists? file-name)
        (call-with-output-file file-name
          (lambda (port)
            (display file-name port)  ;avoid hard-linking
            (chmod port mode)))))
    (catch 'system-error
      (lambda _
        (setxattr file-name "gnu.translator" (string-join command "\0" 'suffix)))
      (lambda (key . args)
        (let ((errno (system-error-errno (cons key args))))
          (format (current-error-port) "~a: ~a\n"
                  (strerror errno) file-name)
          (format (current-error-port) "Ignoring...Good Luck!\n"))))))

(define-syntax-rule (false-if-EEXIST exp)
  "Evaluate EXP but return #f if it raises to 'system-error with EEXIST."
  (catch 'system-error
    (lambda () exp)
    (lambda args
      (if (= EEXIST (system-error-errno args))
          #f
          (apply throw args)))))

(define* (set-hurd-device-translators #:optional (root "/"))
  "Make some of the device nodes needed on GNU/Hurd."

  (define (scope dir)
    (string-append root (if (string-suffix? "/" root) "" "/") dir))

  (define scope-set-translator
    (match-lambda
      ((file-name command)
       (scope-set-translator (list file-name command #o600)))
      ((file-name command mode)
       (let ((mount-point (scope file-name)))
         (set-translator mount-point command mode)))))

  (define (mkdir* dir)
    (let ((dir (scope dir)))
     (unless (file-exists? dir)
       (mkdir-p dir))))

  (define servers
    '(("servers/crash-dump-core" ("/hurd/crash" "--dump-core"))
      ("servers/crash-kill"      ("/hurd/crash" "--kill"))
      ("servers/crash-suspend"   ("/hurd/crash" "--suspend"))
      ("servers/password"        ("/hurd/password"))
      ("servers/socket/1"        ("/hurd/pflocal"))
      ("servers/socket/2"        ("/hurd/pfinet"
                                  "--interface" "eth0"
                                  "--address"
                                  "10.0.2.15" ;the default QEMU guest IP
                                  "--netmask" "255.255.255.0"
                                  "--gateway" "10.0.2.2"
                                  "--ipv6" "/servers/socket/16"))
      ("proc"                    ("/hurd/procfs" "--stat-mode=444"))))

  (define devices
    '(("dev/full"    ("/hurd/null"     "--full")            #o666)
      ("dev/null"    ("/hurd/null")                         #o666)
      ("dev/random"  ("/hurd/random"   "--seed-file" "/var/lib/random-seed")
                                                            #o644)
      ("dev/zero"    ("/hurd/storeio"  "--store-type=zero") #o666)

      ("dev/console" ("/hurd/term"     "/dev/console" "device" "console"))

      ("dev/klog"    ("/hurd/streamio" "kmsg"))
      ("dev/mem"     ("/hurd/storeio"  "--no-cache" "mem")  #o660)
      ("dev/shm"     ("/hurd/tmpfs"    "--mode=1777" "50%") #o644)
      ("dev/time"    ("/hurd/storeio"  "--no-cache" "time") #o644)

      ("dev/vcs"     ("/hurd/console"))
      ("dev/tty"     ("/hurd/magic"    "tty")               #o666)

      ("dev/tty1"    ("/hurd/term"     "/dev/tty1" "hurdio" "/dev/vcs/1/console")
                                                            #o666)
      ("dev/tty2"    ("/hurd/term"     "/dev/tty2" "hurdio" "/dev/vcs/2/console")
                                                            #o666)
      ("dev/tty3"    ("/hurd/term"     "/dev/tty3" "hurdio" "/dev/vcs/3/console")
                                                            #o666)

      ("dev/ptyp0"   ("/hurd/term"     "/dev/ptyp0" "pty-master" "/dev/ttyp0")
                                                            #o666)
      ("dev/ptyp1"   ("/hurd/term"     "/dev/ptyp1" "pty-master" "/dev/ttyp1")
                                                            #o666)
      ("dev/ptyp2"   ("/hurd/term"     "/dev/ptyp2" "pty-master" "/dev/ttyp2")
                                                            #o666)

      ("dev/ttyp0"   ("/hurd/term"     "/dev/ttyp0" "pty-slave" "/dev/ptyp0")
                                                            #o666)
      ("dev/ttyp1"   ("/hurd/term"     "/dev/ttyp1" "pty-slave" "/dev/ptyp1")
                                                            #o666)
      ("dev/ttyp2"   ("/hurd/term"     "/dev/ttyp2" "pty-slave" "/dev/ptyp2")
                                                            #o666)))

  (for-each scope-set-translator servers)
  (mkdir* "dev/vcs/1")
  (mkdir* "dev/vcs/2")
  (mkdir* "dev/vcs/2")
  (rename-file (scope "dev/console") (scope "dev/console-"))
  (for-each scope-set-translator devices)

  (false-if-EEXIST (symlink "/dev/random" (scope "dev/urandom")))
  (mkdir* "dev/fd")
  (false-if-EEXIST (symlink "/dev/fd/0" (scope "dev/stdin")))
  (false-if-EEXIST (symlink "/dev/fd/1" (scope "dev/stdout")))
  (false-if-EEXIST (symlink "/dev/fd/2" (scope "dev/stderr")))

  ;; Make sure /etc/mtab is a symlink to /proc/mounts.
  (false-if-exception (delete-file (scope "etc/mtab")))
  (mkdir* (scope "etc"))
  (symlink "/proc/mounts" (scope "etc/mtab")))

(define* (boot-hurd-system #:key (on-error 'debug))
  "This procedure is meant to be called from an early RC script.

Install the relevant passive translators on the first boot.  Then, run system
activation by using the kernel command-line options '--system' and '--load';
starting the Shepherd.

XXX TODO: see linux-boot.scm:boot-system.
XXX TODO: add proper file-system checking, mounting
XXX TODO: move bits to (new?) (hurd?) (activation?) services
XXX TODO: use Linux xattr/setxattr to remove (settrans in) /libexec/RUNSYSTEM

"

  (display "Welcome, this is GNU's early boot Guile.\n")
  (display "Use '--repl' for an initrd REPL.\n\n")

  (call-with-error-handling
   (lambda ()

     (let* ((args    (command-line))
            (system  (find-long-option "--system" args))
            (to-load (find-long-option "--load" args)))

       (format #t "Setting-up essential translators...\n")
       (setenv "PATH" (string-append system "/profile/bin"))
       (set-hurd-device-translators)

       (false-if-exception (delete-file "/hurd"))
       (let ((hurd/hurd (readlink* (string-append system "/profile/hurd"))))
         (symlink hurd/hurd "/hurd"))

       (format #t "Starting pager...\n")
       (unless (zero? (system* "/hurd/mach-defpager"))
         (format #t "FAILED...Good luck!\n"))

       (cond ((member "--repl" args)
              (format #t "Starting repl...\n")
              (start-repl))
             (to-load
              (format #t "loading '~a'...\n" to-load)
              (primitive-load to-load)
              (format (current-error-port)
                      "boot program '~a' terminated, rebooting~%"
                      to-load)
              (sleep 2)
              (reboot))
             (else
              (display "no boot file passed via '--load'\n")
              (display "entering a warm and cozy REPL\n")
              (start-repl)))))
   #:on-error on-error))

;;; hurd-boot.scm ends here

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2016 Christopher Allan Webber <cwebber@dustycloud.org>
;;; Copyright © 2016, 2017 Leo Famulari <leo@famulari.name>
;;; Copyright © 2017 Marius Bakke <mbakke@fastmail.com>
;;; Copyright © 2020 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2020 Mathieu Othacehe <m.othacehe@gmail.com>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu build image)
  #:use-module (guix build store-copy)
  #:use-module (guix build syscalls)
  #:use-module (guix build utils)
  #:use-module (guix store database)
  #:use-module (gnu build bootloader)
  #:use-module (gnu build install)
  #:use-module (gnu build linux-boot)
  #:use-module (gnu image)
  #:use-module (gnu system uuid)
  #:use-module (ice-9 ftw)
  #:use-module (ice-9 match)
  #:use-module (srfi srfi-19)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:export (make-partition-image
            genimage
            initialize-efi-partition
            initialize-root-partition

            make-iso9660-image))

(define (sexp->partition sexp)
  "Take SEXP, a tuple as returned by 'partition->gexp', and turn it into a
<partition> record."
  (match sexp
    ((size file-system file-system-options label uuid)
     (partition (size size)
                (file-system file-system)
                (file-system-options file-system-options)
                (label label)
                (uuid uuid)))))

(define (size-in-kib size)
  "Convert SIZE expressed in bytes, to kilobytes and return it as a string."
  (number->string
   (inexact->exact (ceiling (/ size 1024)))))

(define (estimate-partition-size root)
  "Given the ROOT directory, evalute and return its size.  As this doesn't
take the partition metadata size into account, take a 25% margin."
  (* 1.25 (file-size root)))

(define* (make-ext-image partition target root
                         #:key
                         (owner-uid 0)
                         (owner-gid 0))
  "Handle the creation of EXT2/3/4 partition images. See
'make-partition-image'."
  (let ((size (partition-size partition))
        (fs (partition-file-system partition))
        (fs-options (partition-file-system-options partition))
        (label (partition-label partition))
        (uuid (partition-uuid partition))
        (journal-options "lazy_itable_init=1,lazy_journal_init=1"))
    (apply invoke
           `("fakeroot" "mke2fs" "-t" ,fs "-d" ,root
             "-L" ,label "-U" ,(uuid->string uuid)
             "-E" ,(format #f "root_owner=~a:~a,~a"
                           owner-uid owner-gid journal-options)
             ,@fs-options
             ,target
             ,(format #f "~ak"
                      (size-in-kib
                       (if (eq? size 'guess)
                           (estimate-partition-size root)
                           size)))))))

(define* (make-vfat-image partition target root)
  "Handle the creation of VFAT partition images.  See 'make-partition-image'."
  (let ((size (partition-size partition))
        (label (partition-label partition)))
    (invoke "fakeroot" "mkdosfs" "-n" label "-C" target
            "-F" "16" "-S" "1024"
            (size-in-kib
             (if (eq? size 'guess)
                 (estimate-partition-size root)
                 size)))
    (for-each (lambda (file)
                (unless (member file '("." ".."))
                  (invoke "mcopy" "-bsp" "-i" target
                          (string-append root "/" file)
                          (string-append "::" file))))
              (scandir root))))

(define* (make-partition-image partition-sexp target root)
  "Create and return the image of PARTITION-SEXP as TARGET.  Use the given
ROOT directory to populate the image."
  (let* ((partition (sexp->partition partition-sexp))
         (type (partition-file-system partition)))
    (cond
     ((string-prefix? "ext" type)
      (make-ext-image partition target root))
     ((string=? type "vfat")
      (make-vfat-image partition target root))
     (else
      (format (current-error-port)
              "Unsupported partition type~%.")))))

(define* (genimage config target)
  "Use genimage to generate in TARGET directory, the image described in the
given CONFIG file."
  ;; genimage needs a 'root' directory.
  (mkdir "root")
  (invoke "genimage" "--config" config
          "--outputpath" target))

(define* (register-closure prefix closure
                           #:key
                           (deduplicate? #t) (reset-timestamps? #t)
                           (schema (sql-schema))
                           (wal-mode? #t))
  "Register CLOSURE in PREFIX, where PREFIX is the directory name of the
target store and CLOSURE is the name of a file containing a reference graph as
produced by #:references-graphs..  As a side effect, if RESET-TIMESTAMPS? is
true, reset timestamps on store files and, if DEDUPLICATE? is true,
deduplicates files common to CLOSURE and the rest of PREFIX.  Pass WAL-MODE?
to call-with-database."
  (let ((items (call-with-input-file closure read-reference-graph)))
    (parameterize ((sql-schema schema))
      (with-database (store-database-file #:prefix prefix) db
       #:wal-mode? wal-mode?
       (register-items db items
                       #:prefix prefix
                       #:deduplicate? deduplicate?
                       #:reset-timestamps? reset-timestamps?
                       #:registration-time %epoch)))))

(define* (initialize-efi-partition root
                                   #:key
                                   grub-efi
                                   #:allow-other-keys)
  "Install in ROOT directory, an EFI loader using GRUB-EFI."
  (install-efi-loader grub-efi root))

(define* (initialize-root-partition root
                                    #:key
                                    bootcfg
                                    bootcfg-location
                                    bootloader-package
                                    bootloader-installer
                                    (deduplicate? #t)
                                    references-graphs
                                    (register-closures? #t)
                                    system-directory
                                    make-device-nodes
                                    (wal-mode? #t)
                                    #:allow-other-keys)
  "Initialize the given ROOT directory. Use BOOTCFG and BOOTCFG-LOCATION to
install the bootloader configuration.

If REGISTER-CLOSURES? is true, register REFERENCES-GRAPHS in the store.  If
DEDUPLICATE? is true, then also deduplicate files common to CLOSURES and the
rest of the store when registering the closures.  SYSTEM-DIRECTORY is the name
of the directory of the 'system' derivation.  Pass WAL-MODE? to
register-closure."
  (populate-root-file-system system-directory root)
  (populate-store references-graphs root)

  ;; Populate /dev.
  (when make-device-nodes
    (make-device-nodes root))

  (when register-closures?
    (for-each (lambda (closure)
                (register-closure root
                                  closure
                                  #:reset-timestamps? #t
                                  #:deduplicate? deduplicate?
                                  #:wal-mode? wal-mode?))
              references-graphs))

  (when bootloader-installer
    (display "installing bootloader...\n")
    (bootloader-installer bootloader-package #f root))
  (when bootcfg
    (install-boot-config bootcfg bootcfg-location root)))

(define* (make-iso9660-image xorriso grub-mkrescue-environment
                             grub bootcfg system-directory root target
                             #:key (volume-id "Guix_image") (volume-uuid #f)
                             register-closures? (references-graphs '())
                             (compression? #t))
  "Given a GRUB package, creates an iso image as TARGET, using BOOTCFG as
GRUB configuration and OS-DRV as the stuff in it."
  (define grub-mkrescue
    (string-append grub "/bin/grub-mkrescue"))

  (define grub-mkrescue-sed.sh
    (string-append (getcwd) "/" "grub-mkrescue-sed.sh"))

  ;; Use a modified version of grub-mkrescue-sed.sh, see below.
  (copy-file (string-append xorriso
                            "/bin/grub-mkrescue-sed.sh")
             grub-mkrescue-sed.sh)

  ;; Force grub-mkrescue-sed.sh to use the build directory instead of /tmp
  ;; that is read-only inside the build container.
  (substitute* grub-mkrescue-sed.sh
    (("/tmp/") (string-append (getcwd) "/"))
    (("MKRESCUE_SED_XORRISO_ARGS \\$x")
     (format #f "MKRESCUE_SED_XORRISO_ARGS $(echo $x | sed \"s|/tmp|~a|\")"
             (getcwd))))

  ;; 'grub-mkrescue' calls out to mtools programs to create 'efi.img', a FAT
  ;; file system image, and mtools honors SOURCE_DATE_EPOCH for the mtime of
  ;; those files.  The epoch for FAT is Jan. 1st 1980, not 1970, so choose
  ;; that.
  (setenv "SOURCE_DATE_EPOCH"
          (number->string
           (time-second
            (date->time-utc (make-date 0 0 0 0 1 1 1980 0)))))

  ;; Our patched 'grub-mkrescue' honors this environment variable and passes
  ;; it to 'mformat', which makes it the serial number of 'efi.img'.  This
  ;; allows for deterministic builds.
  (setenv "GRUB_FAT_SERIAL_NUMBER"
          (number->string (if volume-uuid

                              ;; On 32-bit systems the 2nd argument must be
                              ;; lower than 2^32.
                              (string-hash (iso9660-uuid->string volume-uuid)
                                           (- (expt 2 32) 1))

                              #x77777777)
                          16))

  (setenv "MKRESCUE_SED_MODE" "original")
  (setenv "MKRESCUE_SED_XORRISO" (string-append xorriso "/bin/xorriso"))
  (setenv "MKRESCUE_SED_IN_EFI_NO_PT" "yes")

  (for-each (match-lambda
              ((name . value) (setenv name value)))
            grub-mkrescue-environment)

  (apply invoke grub-mkrescue
         (string-append "--xorriso=" grub-mkrescue-sed.sh)
         "-o" target
         (string-append "boot/grub/grub.cfg=" bootcfg)
         root
         "--"
         ;; Set all timestamps to 1.
         "-volume_date" "all_file_dates" "=1"

         `(,@(if compression?
                 '(;; ‘zisofs’ compression reduces the total image size by
                   ;; ~60%.
                   "-zisofs" "level=9:block_size=128k" ; highest compression
                   ;; It's transparent to our Linux-Libre kernel but not to
                   ;; GRUB.  Don't compress the kernel, initrd, and other
                   ;; files read by grub.cfg, as well as common
                   ;; already-compressed file names.
                   "-find" "/" "-type" "f"
                   ;; XXX Even after "--" above, and despite documentation
                   ;; claiming otherwise, "-or" is stolen by grub-mkrescue
                   ;; which then chokes on it (as ‘-o …’) and dies.  Don't use
                   ;; "-or".
                   "-not" "-wholename" "/boot/*"
                   "-not" "-wholename" "/System/*"
                   "-not" "-name" "unicode.pf2"
                   "-not" "-name" "bzImage"
                   "-not" "-name" "*.gz"   ; initrd & all man pages
                   "-not" "-name" "*.png"  ; includes grub-image.png
                   "-exec" "set_filter" "--zisofs"
                   "--")
                 '())
           "-volid" ,(string-upcase volume-id)
           ,@(if volume-uuid
             `("-volume_date" "uuid"
               ,(string-filter (lambda (value)
                                 (not (char=? #\- value)))
                               (iso9660-uuid->string
                                volume-uuid)))
             '()))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2016 Chris Marusich <cmmarusich@gmail.com>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu build install)
  #:use-module (guix build syscalls)
  #:use-module (guix build utils)
  #:use-module (guix build store-copy)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 match)
  #:export (install-boot-config
            evaluate-populate-directive
            populate-root-file-system
            install-database-and-gc-roots
            populate-single-profile-directory
            mount-cow-store
            unmount-cow-store))

;;; Commentary:
;;;
;;; This module supports the installation of the GNU system on a hard disk.
;;; It is meant to be used both in a build environment (in derivations that
;;; build VM images), and on the bare metal (when really installing the
;;; system.)
;;;
;;; Code:

(define (install-boot-config bootcfg bootcfg-location mount-point)
  "Atomically copy BOOTCFG into BOOTCFG-LOCATION on the MOUNT-POINT.  Note
that the caller must make sure that BOOTCFG is registered as a GC root so
that the fonts, background images, etc. referred to by BOOTCFG are not GC'd."
  (let* ((target (string-append mount-point bootcfg-location))
         (pivot  (string-append target ".new")))
    (mkdir-p (dirname target))

    ;; Copy BOOTCFG instead of just symlinking it, because symlinks won't
    ;; work when /boot is on a separate partition.  Do that atomically.
    (copy-file bootcfg pivot)
    (rename-file pivot target)))

(define* (evaluate-populate-directive directive target
                                      #:key
                                      (default-gid 0)
                                      (default-uid 0))
  "Evaluate DIRECTIVE, an sexp describing a file or directory to create under
directory TARGET.  DEFAULT-UID and DEFAULT-GID are the default UID and GID in
the context of the caller.  If the directive matches those defaults then,
'chown' won't be run."
  (let loop ((directive directive))
    (catch 'system-error
      (lambda ()
        (match directive
          (('directory name)
           (mkdir-p (string-append target name)))
          (('directory name uid gid)
           (let ((dir (string-append target name)))
             (mkdir-p dir)
             ;; If called from a context without "root" permissions, "chown"
             ;; to root will fail.  In that case, do not try to run "chown"
             ;; and assume that the file will be chowned elsewhere (when
             ;; interned in the store for instance).
             (or (and (= uid default-uid) (= gid default-gid))
                 (chown dir uid gid))))
          (('directory name uid gid mode)
           (loop `(directory ,name ,uid ,gid))
           (chmod (string-append target name) mode))
          (('file name)
           (call-with-output-file (string-append target name)
             (const #t)))
          (('file name (? string? content))
           (call-with-output-file (string-append target name)
             (lambda (port)
               (display content port))))
          ((new '-> old)
           (let try ()
             (catch 'system-error
               (lambda ()
                 (symlink old (string-append target new)))
               (lambda args
                 ;; When doing 'guix system init' on the current '/', some
                 ;; symlinks may already exists.  Override them.
                 (if (= EEXIST (system-error-errno args))
                     (begin
                       (delete-file (string-append target new))
                       (try))
                     (apply throw args))))))))
      (lambda args
        ;; Usually we can only get here when installing to an existing root,
        ;; as with 'guix system init foo.scm /'.
        (format (current-error-port)
                "error: failed to evaluate directive: ~s~%"
                directive)
        (apply throw args)))))

(define (directives store)
  "Return a list of directives to populate the root file system that will host
STORE."
  `((directory ,store 0 0 #o1775)

    (directory "/etc")
    (directory "/var/log")                          ; for shepherd
    (directory "/var/guix/gcroots")
    (directory "/var/empty")                        ; for no-login accounts
    (directory "/var/db")                           ; for dhclient, etc.
    (directory "/var/run")
    (directory "/run")
    (directory "/mnt")
    (directory "/var/guix/profiles/per-user/root" 0 0)

    ;; Link to the initial system generation.
    ("/var/guix/profiles/system" -> "system-1-link")

    ("/var/guix/gcroots/booted-system" -> "/run/booted-system")
    ("/var/guix/gcroots/current-system" -> "/run/current-system")
    ("/var/guix/gcroots/profiles" -> "/var/guix/profiles")

    (directory "/bin")
    (directory "/tmp" 0 0 #o1777)                 ; sticky bit
    (directory "/var/tmp" 0 0 #o1777)
    (directory "/var/lock" 0 0 #o1777)

    (directory "/home" 0 0)))

(define* (populate-root-file-system system target
                                    #:key (extras '()))
  "Make the essential non-store files and directories on TARGET.  This
includes /etc, /var, /run, /bin/sh, etc., and all the symlinks to SYSTEM.
EXTRAS is a list of directives appended to the built-in directives to populate
TARGET."
  (for-each (cut evaluate-populate-directive <> target)
            (append (directives (%store-directory)) extras))

  ;; Add system generation 1.
  (let ((generation-1 (string-append target
                                     "/var/guix/profiles/system-1-link")))
    (let try ()
      (catch 'system-error
        (lambda ()
          (symlink system generation-1))
        (lambda args
          ;; If GENERATION-1 already exists, overwrite it.
          (if (= EEXIST (system-error-errno args))
              (begin
                (delete-file generation-1)
                (try))
              (apply throw args)))))))

(define %root-profile
  "/var/guix/profiles/per-user/root")

(define* (install-database-and-gc-roots root database profile
                                        #:key (profile-name "guix-profile"))
  "Install DATABASE, the store database, under directory ROOT.  Create
PROFILE-NAME and have it link to PROFILE, a store item."
  (define (scope file)
    (string-append root "/" file))

  (define (mkdir-p* dir)
    (mkdir-p (scope dir)))

  (define (symlink* old new)
    (symlink old (scope new)))

  (install-file database (scope "/var/guix/db/"))
  (chmod (scope "/var/guix/db/db.sqlite") #o644)
  (mkdir-p* "/var/guix/profiles")
  (mkdir-p* "/var/guix/gcroots")
  (symlink* "/var/guix/profiles" "/var/guix/gcroots/profiles")

  ;; Make root's profile, which makes it a GC root.
  (mkdir-p* %root-profile)
  (symlink* profile
            (string-append %root-profile "/" profile-name "-1-link"))
  (symlink* (string-append profile-name "-1-link")
            (string-append %root-profile "/" profile-name)))

(define* (populate-single-profile-directory directory
                                            #:key profile closure
                                            (profile-name "guix-profile")
                                            database)
  "Populate DIRECTORY with a store containing PROFILE, whose closure is given
in the file called CLOSURE (as generated by #:references-graphs.)  DIRECTORY
is initialized to contain a single profile under /root pointing to PROFILE.

When DATABASE is true, copy it to DIRECTORY/var/guix/db and create
DIRECTORY/var/guix/gcroots and friends.

PROFILE-NAME is the name of the profile being created under
/var/guix/profiles, typically either \"guix-profile\" or \"current-guix\".

This is used to create the self-contained tarballs with 'guix pack'."
  (define (scope file)
    (string-append directory "/" file))

  (define (mkdir-p* dir)
    (mkdir-p (scope dir)))

  (define (symlink* old new)
    (symlink old (scope new)))

  ;; Populate the store.
  (populate-store (list closure) directory)

  (when database
    (install-database-and-gc-roots directory database profile
                                   #:profile-name profile-name))

  (match profile-name
    ("guix-profile"
     (mkdir-p* "/root")
     (symlink* (string-append %root-profile "/guix-profile")
               "/root/.guix-profile"))
    ("current-guix"
     (mkdir-p* "/root/.config/guix")
     (symlink* (string-append %root-profile "/current-guix")
               "/root/.config/guix/current"))
    (_
     #t)))

(define (mount-cow-store target backing-directory)
  "Make the store copy-on-write, using TARGET as the backing store.  This is
useful when TARGET is on a hard disk, whereas the current store is on a RAM
disk."
  (define (set-store-permissions directory)
    "Set the right perms on DIRECTORY to use it as the store."
    (chown directory 0 30000)      ;use the fixed 'guixbuild' GID
    (chmod directory #o1775))

  (let ((tmpdir (string-append target "/tmp")))
    (mkdir-p tmpdir)
    (mount tmpdir "/tmp" "none" MS_BIND))

  (let* ((rw-dir (string-append target backing-directory))
         (work-dir (string-append rw-dir "/../.overlayfs-workdir")))
    (mkdir-p rw-dir)
    (mkdir-p work-dir)
    (mkdir-p "/.rw-store")
    (set-store-permissions rw-dir)
    (set-store-permissions "/.rw-store")

    ;; Mount the overlay, then atomically make it the store.
    (mount "none" "/.rw-store" "overlay" 0
           (string-append "lowerdir=" (%store-directory) ","
                          "upperdir=" rw-dir ","
                          "workdir=" work-dir))
    (mount "/.rw-store" (%store-directory) "" MS_MOVE)
    (rmdir "/.rw-store")))

(define (unmount-cow-store target backing-directory)
  "Unmount copy-on-write store."
  (let ((tmp-dir "/remove"))
    (mkdir-p tmp-dir)
    (mount (%store-directory) tmp-dir "" MS_MOVE)
    (umount tmp-dir)
    (rmdir tmp-dir)
    (delete-file-recursively
     (string-append target backing-directory))))

;;; install.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2019 Guillaume Le Vaillant <glv@posteo.net>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu build linux-boot)
  #:use-module (rnrs io ports)
  #:use-module (system repl error-handling)
  #:autoload   (system repl repl) (start-repl)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 match)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 ftw)
  #:use-module (guix build utils)
  #:use-module ((guix build syscalls)
                #:hide (file-system-type))
  #:use-module (gnu build linux-modules)
  #:use-module (gnu build file-systems)
  #:use-module (gnu system file-systems)
  #:export (mount-essential-file-systems
            linux-command-line
            find-long-option
            find-long-options
            make-essential-device-nodes
            make-static-device-nodes
            configure-qemu-networking

            device-number
            boot-system))

;;; Commentary:
;;;
;;; Utility procedures useful in a Linux initial RAM disk (initrd).  Note that
;;; many of these use procedures not yet available in vanilla Guile (`mount',
;;; `load-linux-module', etc.); these are provided by a Guile patch used in
;;; the GNU distribution.
;;;
;;; Code:

(define* (mount-essential-file-systems #:key (root "/"))
  "Mount /dev, /proc, and /sys under ROOT."
  (define (scope dir)
    (string-append root
                   (if (string-suffix? "/" root)
                       ""
                       "/")
                   dir))

  (unless (file-exists? (scope "proc"))
    (mkdir (scope "proc")))
  (mount "none" (scope "proc") "proc")

  (unless (file-exists? (scope "dev"))
    (mkdir (scope "dev")))
  (mount "none" (scope "dev") "devtmpfs")

  (unless (file-exists? (scope "sys"))
    (mkdir (scope "sys")))
  (mount "none" (scope "sys") "sysfs"))

(define (move-essential-file-systems root)
  "Move currently mounted essential file systems to ROOT."
  (for-each (lambda (dir)
              (let ((target (string-append root dir)))
                (unless (file-exists? target)
                  (mkdir target))
                (mount dir target "" MS_MOVE)))
            '("/dev" "/proc" "/sys")))

(define (linux-command-line)
  "Return the Linux kernel command line as a list of strings."
  (string-tokenize
   (call-with-input-file "/proc/cmdline"
     get-string-all)))

(define (find-long-option option arguments)
  "Find OPTION among ARGUMENTS, where OPTION is something like \"--load\".
Return the value associated with OPTION, or #f on failure."
  (let ((opt (string-append option "=")))
    (and=> (find (cut string-prefix? opt <>)
                 arguments)
           (lambda (arg)
             (substring arg (+ 1 (string-index arg #\=)))))))

(define (find-long-options option arguments)
  "Find OPTIONs among ARGUMENTS, where OPTION is something like \"console\".
Return the values associated with OPTIONs as a list, or the empty list if
OPTION doesn't appear in ARGUMENTS."
  (let ((opt (string-append option "=")))
    (filter-map (lambda (arg)
                  (and (string-prefix? opt arg)
                       (substring arg (+ 1 (string-index arg #\=)))))
                arguments)))

(define* (make-disk-device-nodes base major #:optional (minor 0))
  "Make the block device nodes around BASE (something like \"/root/dev/sda\")
with the given MAJOR number, starting with MINOR."
  (mknod base 'block-special #o644 (device-number major minor))
  (let loop ((i 1))
    (when (< i 16)
      (mknod (string-append base (number->string i))
             'block-special #o644 (device-number major (+ minor i)))
      (loop (+ i 1)))))

;; Representation of a /dev node.
(define-record-type <device-node>
  (device-node name type major minor module)
  device-node?
  (name device-node-name)
  (type device-node-type)
  (major device-node-major)
  (minor device-node-minor)
  (module device-node-module))

(define (read-static-device-nodes port)
  "Read from PORT a list of <device-node> written in the format used by
/lib/modules/*/*.devname files."
  (let loop ((line (read-line port)))
    (if (eof-object? line)
      '()
      (match (string-split line #\space)
       (((? (cut string-prefix? "#" <>)) _ ...)
        (loop (read-line port)))
       ((module-name device-name device-spec)
        (let* ((device-parts
               (string-match "([bc])([0-9][0-9]*):([0-9][0-9]*)"
                             device-spec))
               (type-string (match:substring device-parts 1))
               (type (match type-string
                      ("c" 'char-special)
                      ("b" 'block-special)))
               (major-string (match:substring device-parts 2))
               (major (string->number major-string 10))
               (minor-string (match:substring device-parts 3))
               (minor (string->number minor-string 10)))
          (cons (device-node device-name type major minor module-name)
                (loop (read-line port)))))
       (_
        (begin
          (format (current-error-port)
                  "read-static-device-nodes: ignored devname line '~a'~%" line)
          (loop (read-line port))))))))

(define* (mkdir-p* dir #:optional (mode #o755))
  "This is a variant of 'mkdir-p' that works around
<http://bugs.gnu.org/24659> by passing MODE explicitly in each 'mkdir' call."
  (define absolute?
    (string-prefix? "/" dir))

  (define not-slash
    (char-set-complement (char-set #\/)))

  (let loop ((components (string-tokenize dir not-slash))
             (root       (if absolute?
                             ""
                             ".")))
    (match components
      ((head tail ...)
       (let ((path (string-append root "/" head)))
         (catch 'system-error
           (lambda ()
             (mkdir path mode)
             (loop tail path))
           (lambda args
             (if (= EEXIST (system-error-errno args))
                 (loop tail path)
                 (apply throw args))))))
      (() #t))))

(define (report-system-error name . args)
  "Report a system error for the file NAME."
  (let ((errno (system-error-errno args)))
    (format (current-error-port) "could not create '~a': ~a~%" name
            (strerror errno))))

;; Catch a system-error, log it and don't die from it.
(define-syntax-rule (catch-system-error name exp)
  (catch 'system-error
    (lambda ()
      exp)
    (lambda args
      (apply report-system-error name args))))

;; Create a device node like the <device-node> passed here on the file system.
(define create-device-node
  (match-lambda
    (($ <device-node> xname type major minor module)
     (let ((name (string-append "/dev/" xname)))
       (mkdir-p* (dirname name))
       (catch-system-error name
         (mknod name type #o600 (device-number major minor)))))))

(define* (make-static-device-nodes linux-release-module-directory)
  "Create static device nodes required by the given Linux release.
This is required in order to solve a chicken-or-egg problem:
The Linux kernel has a feature to autoload modules when a device is first
accessed.
And udev has a feature to set the permissions of static nodes correctly
when it is starting up and also to automatically create nodes when hardware
is hotplugged. That leaves universal device files which are not linked to
one specific hardware device. These we have to create."
  (let ((devname-name (string-append linux-release-module-directory "/"
                                     "modules.devname")))
    (for-each create-device-node
              (call-with-input-file devname-name
                                    read-static-device-nodes))))

(define* (make-essential-device-nodes #:optional (root "/"))
  "Make essential device nodes under ROOT/dev."
  ;; The hand-made devtmpfs/udev!

  (define (scope dir)
    (string-append root
                   (if (string-suffix? "/" root)
                       ""
                       "/")
                   dir))

  (unless (file-exists? (scope "dev"))
    (mkdir (scope "dev")))

  ;; Make the device nodes for SCSI disks.
  (make-disk-device-nodes (scope "dev/sda") 8)
  (make-disk-device-nodes (scope "dev/sdb") 8 16)
  (make-disk-device-nodes (scope "dev/sdc") 8 32)
  (make-disk-device-nodes (scope "dev/sdd") 8 48)

  ;; SCSI CD-ROM devices (aka. "/dev/sr0" etc.).
  (mknod (scope "dev/scd0") 'block-special #o644 (device-number 11 0))
  (mknod (scope "dev/scd1") 'block-special #o644 (device-number 11 1))

  ;; The virtio (para-virtualized) block devices, as supported by QEMU/KVM.
  (make-disk-device-nodes (scope "dev/vda") 252)

  ;; Memory (used by Xorg's VESA driver.)
  (mknod (scope "dev/mem") 'char-special #o640 (device-number 1 1))
  (mknod (scope "dev/kmem") 'char-special #o640 (device-number 1 2))

  ;; Inputs (used by Xorg.)
  (unless (file-exists? (scope "dev/input"))
    (mkdir (scope "dev/input")))
  (mknod (scope "dev/input/mice") 'char-special #o640 (device-number 13 63))
  (mknod (scope "dev/input/mouse0") 'char-special #o640 (device-number 13 32))
  (mknod (scope "dev/input/event0") 'char-special #o640 (device-number 13 64))

  ;; System console.  This node is magically created by the kernel on the
  ;; initrd's root, so don't try to create it in that case.
  (unless (string=? root "/")
    (mknod (scope "dev/console") 'char-special #o600
           (device-number 5 1)))

  ;; TTYs.
  (mknod (scope "dev/tty") 'char-special #o600
         (device-number 5 0))
  (chmod (scope "dev/tty") #o666)
  (let loop ((n 0))
    (and (< n 50)
         (let ((name (format #f "dev/tty~a" n)))
           (mknod (scope name) 'char-special #o600
                  (device-number 4 n))
           (loop (+ 1 n)))))

  ;; Serial line.
  (mknod (scope "dev/ttyS0") 'char-special #o660
         (device-number 4 64))

  ;; Pseudo ttys.
  (mknod (scope "dev/ptmx") 'char-special #o666
         (device-number 5 2))
  (chmod (scope "dev/ptmx") #o666)

  ;; Create /dev/pts; it will be mounted later, at boot time.
  (unless (file-exists? (scope "dev/pts"))
    (mkdir (scope "dev/pts")))

  ;; Rendez-vous point for syslogd.
  (mknod (scope "dev/log") 'socket #o666 0)
  (mknod (scope "dev/kmsg") 'char-special #o600 (device-number 1 11))

  ;; Other useful nodes, notably relied on by guix-daemon.
  (for-each (match-lambda
             ((file major minor)
              (mknod (scope file) 'char-special #o666
                     (device-number major minor))
              (chmod (scope file) #o666)))
            '(("dev/null" 1 3)
              ("dev/zero" 1 5)
              ("dev/full" 1 7)
              ("dev/random" 1 8)
              ("dev/urandom" 1 9)))

  (symlink "/proc/self/fd" (scope "dev/fd"))
  (symlink "/proc/self/fd/0" (scope "dev/stdin"))
  (symlink "/proc/self/fd/1" (scope "dev/stdout"))
  (symlink "/proc/self/fd/2" (scope "dev/stderr"))

  ;; Loopback devices.
  (let loop ((i 0))
    (when (< i 8)
      (mknod (scope (string-append "dev/loop" (number->string i)))
             'block-special #o660
             (device-number 7 i))
      (loop (+ 1 i))))

  ;; File systems in user space (FUSE).
  (mknod (scope "dev/fuse") 'char-special #o666 (device-number 10 229)))

(define %host-qemu-ipv4-address
  (inet-pton AF_INET "10.0.2.10"))

(define* (configure-qemu-networking #:optional (interface "eth0"))
  "Setup the INTERFACE network interface and /etc/resolv.conf according to
QEMU's default networking settings (see net/slirp.c in QEMU for default
networking values.)  Return #t if INTERFACE is up, #f otherwise."
  (display "configuring QEMU networking...\n")
  (let* ((sock    (socket AF_INET SOCK_STREAM 0))
         (address (make-socket-address AF_INET %host-qemu-ipv4-address 0))
         (flags   (network-interface-flags sock interface)))
    (set-network-interface-address sock interface address)
    (set-network-interface-flags sock interface (logior flags IFF_UP))

    ;; Hello!  We used to create /etc/resolv.conf here, with "nameserver
    ;; 10.0.2.3\n".  However, with Linux-libre 3.16, we're getting ENOSPC.
    ;; And since it's actually unnecessary, it's gone.

    (logand (network-interface-flags sock interface) IFF_UP)))

(define (device-number major minor)
  "Return the device number for the device with MAJOR and MINOR, for use as
the last argument of `mknod'."
  (+ (* major 256) minor))

(define (pidof program)
  "Return the PID of the first presumed instance of PROGRAM."
  (let ((program (basename program)))
    (find (lambda (pid)
            (let ((exe (format #f "/proc/~a/exe" pid)))
              (and=> (false-if-exception (readlink exe))
                     (compose (cut string=? program <>) basename))))
          (filter-map string->number (scandir "/proc")))))

(define* (mount-root-file-system root type
                                 #:key volatile-root? (flags 0) options)
  "Mount the root file system of type TYPE at device ROOT. If VOLATILE-ROOT? is
true, mount ROOT read-only and make it an overlay with a writable tmpfs using
the kernel built-in overlayfs. FLAGS and OPTIONS indicates the options to use
to mount ROOT, and behave the same as for the `mount' procedure."

  (if volatile-root?
      (begin
        (mkdir-p "/real-root")
        (mount root "/real-root" type (logior MS_RDONLY flags) options)
        (mkdir-p "/rw-root")
        (mount "none" "/rw-root" "tmpfs")

        ;; Create the upperdir and the workdir of the overlayfs
        (mkdir-p "/rw-root/upper")
        (mkdir-p "/rw-root/work")

        ;; We want read-write /dev nodes.
        (mkdir-p "/rw-root/upper/dev")
        (mount "none" "/rw-root/upper/dev" "devtmpfs")

        ;; Make /root an overlay of the tmpfs and the actual root.
        (mount "none" "/root" "overlay" 0
               "lowerdir=/real-root,upperdir=/rw-root/upper,workdir=/rw-root/work"))
      (begin
        (check-file-system root type)
        (mount root "/root" type flags options)))

  ;; Make sure /root/etc/mtab is a symlink to /proc/self/mounts.
  (false-if-exception
    (delete-file "/root/etc/mtab"))
  (mkdir-p "/root/etc")
  (symlink "/proc/self/mounts" "/root/etc/mtab"))

(define (switch-root root)
  "Switch to ROOT as the root file system, in a way similar to what
util-linux' switch_root(8) does."
  (move-essential-file-systems root)
  (chdir root)

  ;; Since we're about to 'rm -rf /', try to make sure we're on an initrd.
  ;; TODO: Use 'statfs' to check the fs type, like klibc does.
  (when (or (not (file-exists? "/init")) (directory-exists? "/home"))
    (format (current-error-port)
            "The root file system is probably not an initrd; \
bailing out.~%root contents: ~s~%" (scandir "/"))
    (force-output (current-error-port))
    (exit 1))

  ;; Delete files from the old root, without crossing mount points (assuming
  ;; there are no mount points in sub-directories.)  That means we're leaving
  ;; the empty ROOT directory behind us, but that's OK.
  (let ((root-device (stat:dev (stat "/"))))
    (for-each (lambda (file)
                (unless (member file '("." ".."))
                  (let* ((file   (string-append "/" file))
                         (device (stat:dev (lstat file))))
                    (when (= device root-device)
                      (delete-file-recursively file)))))
              (scandir "/")))

  ;; Make ROOT the new root.
  (mount root "/" "" MS_MOVE)
  (chroot ".")
  (chdir "/")

  (when (file-exists? "/dev/console")
    ;; Close the standard file descriptors since they refer to the old
    ;; /dev/console, and reopen them.
    (let ((console (open-file "/dev/console" "r+b0")))
      (for-each close-fdes '(0 1 2))

      (dup2 (fileno console) 0)
      (dup2 (fileno console) 1)
      (dup2 (fileno console) 2)

      (close-port console))))

(define* (boot-system #:key
                      (linux-modules '())
                      linux-module-directory
                      keymap-file
                      qemu-guest-networking?
                      volatile-root?
                      pre-mount
                      (mounts '())
                      (on-error 'debug))
  "This procedure is meant to be called from an initrd.  Boot a system by
first loading LINUX-MODULES (a list of module names) from
LINUX-MODULE-DIRECTORY, then installing KEYMAP-FILE with 'loadkeys' (if
KEYMAP-FILE is true), then setting up QEMU guest networking if
QEMU-GUEST-NETWORKING? is true, calling PRE-MOUNT, mounting the file systems
specified in MOUNTS, and finally booting into the new root if any.  The initrd
supports kernel command-line options '--load', '--root', and '--repl'.

Mount the root file system, specified by the '--root' command-line argument,
if any.

MOUNTS must be a list of <file-system> objects.

When VOLATILE-ROOT? is true, the root file system is writable but any changes
to it are lost.

ON-ERROR is passed to 'call-with-error-handling'; it determines what happens
upon error."
  (define (root-mount-point? fs)
    (string=? (file-system-mount-point fs) "/"))

  (define (device-string->file-system-device device-string)
    ;; The "--root=SPEC" kernel command-line option always provides a
    ;; string, but the string can represent a device, an nfs-root, a UUID, or a
    ;; label.  So check for all four.
    (cond ((string-prefix? "/" device-string) device-string)
          ((string-contains device-string ":/") device-string) ; nfs-root
          ((uuid device-string) => identity)
          (else (file-system-label device-string))))

  (display "Welcome, this is GNU's early boot Guile.\n")
  (display "Use '--repl' for an initrd REPL.\n\n")

  (call-with-error-handling
    (lambda ()
      (mount-essential-file-systems)
      (let* ((args    (linux-command-line))
             (to-load (find-long-option "--load" args))
             (root-fs (find root-mount-point? mounts))
             (root-fs-type (or (and=> root-fs file-system-type)
                               "ext4"))
             (root-fs-device (and=> root-fs file-system-device))
             (root-fs-flags (mount-flags->bit-mask
                             (or (and=> root-fs file-system-flags)
                                 '())))
             (root-options (if root-fs
                               (file-system-options root-fs)
                               #f))
             ;; --root takes precedence over the 'device' field of the root
             ;; <file-system> record.
             (root-device (or (and=> (find-long-option "--root" args)
                                     device-string->file-system-device)
                              root-fs-device)))

        (when (member "--repl" args)
          (start-repl))

        (display "loading kernel modules...\n")
        (load-linux-modules-from-directory linux-modules
                                           linux-module-directory)

        (when keymap-file
          (let ((status (system* "loadkeys" keymap-file)))
            (unless (zero? status)
              ;; Emit a warning rather than abort when we cannot load
              ;; KEYMAP-FILE.
              (format (current-error-port)
                      "warning: 'loadkeys' exited with status ~a~%"
                      status))))

        (when qemu-guest-networking?
          (unless (configure-qemu-networking)
            (display "network interface is DOWN\n")))

        ;; Prepare the real root file system under /root.
        (unless (file-exists? "/root")
          (mkdir "/root"))

        (when (procedure? pre-mount)
          ;; Do whatever actions are needed before mounting the root file
          ;; system--e.g., installing device mappings.  Error out when the
          ;; return value is false.
          (unless (pre-mount)
            (error "pre-mount actions failed")))

        (setenv "EXT2FS_NO_MTAB_OK" "1")

        (if root-device
            (mount-root-file-system (canonicalize-device-spec root-device)
                                    root-fs-type
                                    #:volatile-root? volatile-root?
                                    #:flags root-fs-flags
                                    #:options root-options)
            (mount "none" "/root" "tmpfs"))

        ;; Mount the specified file systems.
        (for-each mount-file-system
                  (remove root-mount-point? mounts))

        (setenv "EXT2FS_NO_MTAB_OK" #f)

        (if to-load
            (begin
              (switch-root "/root")
              (format #t "loading '~a'...\n" to-load)

              (primitive-load to-load)

              (format (current-error-port)
                      "boot program '~a' terminated, rebooting~%"
                      to-load)
              (sleep 2)
              (reboot))
            (begin
              (display "no boot file passed via '--load'\n")
              (display "entering a warm and cozy REPL\n")
              (start-repl)))))
    #:on-error on-error))

;;; linux-boot.scm ends here