1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
4 ;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
5 ;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
6 ;;; Copyright © 2019 Guillaume Le Vaillant <glv@posteo.net>
7 ;;; Copyright © 2020 Julien Lepiller <julien@lepiller.eu>
8 ;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
10 ;;; This file is part of GNU Guix.
12 ;;; GNU Guix is free software; you can redistribute it and/or modify it
13 ;;; under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 3 of the License, or (at
15 ;;; your option) any later version.
17 ;;; GNU Guix is distributed in the hope that it will be useful, but
18 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
25 (define-module (guix build syscalls)
26 #:use-module (system foreign)
27 #:use-module (system base target)
28 #:use-module (rnrs bytevectors)
29 #:autoload (ice-9 binary-ports) (get-bytevector-n)
30 #:use-module (srfi srfi-1)
31 #:use-module (srfi srfi-9)
32 #:use-module (srfi srfi-9 gnu)
33 #:use-module (srfi srfi-11)
34 #:use-module (srfi srfi-19)
35 #:use-module (srfi srfi-26)
36 #:use-module (ice-9 rdelim)
37 #:use-module (ice-9 regex)
38 #:use-module (ice-9 match)
39 #:use-module (ice-9 ftw)
62 file-system-block-size
63 file-system-block-count
64 file-system-blocks-free
65 file-system-blocks-available
66 file-system-file-count
67 file-system-free-file-nodes
68 file-system-identifier
69 file-system-maximum-name-length
70 file-system-fragment-size
71 file-system-mount-flags
89 with-file-lock/no-wait
107 all-network-interface-names
108 network-interface-names
109 network-interface-netmask
110 network-interface-running?
111 loopback-network-interface?
112 arp-network-interface?
113 network-interface-address
114 set-network-interface-netmask
115 set-network-interface-up
116 configure-network-interface
117 add-network-route/gateway
125 interface-broadcast-address
131 termios-control-flags
133 termios-line-discipline
134 termios-control-chars
159 utmpx-termination-status
166 (read-utmpx-from-port . read-utmpx)))
170 ;;; This module provides bindings to libc's syscall wrappers. It uses the
171 ;;; FFI, and thus requires a dynamically-linked Guile.
173 ;;; Some syscalls are already defined in statically-linked Guile by applying
174 ;;; 'guile-linux-syscalls.patch'.
176 ;;; Visibility of syscall's symbols shared between this module and static Guile
177 ;;; is a bit delicate. It is handled by 'define-as-needed' macro.
179 ;;; This macro is used to export symbols in dynamic Guile context, and to
180 ;;; re-export them in static Guile context.
182 ;;; This way, even if they don't appear in #:export list, it is safe to use
183 ;;; syscalls from this module in static or dynamic Guile context.
189 ;;; Packed structures.
192 (define-syntax sizeof*
193 ;; XXX: This duplicates 'compile-time-value'.
194 (syntax-rules (int128 array)
198 (* (sizeof* type) n))
200 (let-syntax ((v (lambda (s)
201 ;; When compiling natively, call 'sizeof' at expansion
202 ;; time; otherwise, emit code to call it at run time.
205 (if (= (target-word-size)
206 (with-target %host-type target-word-size))
208 #'(sizeof type)))))))
211 (define-syntax alignof*
212 ;; XXX: This duplicates 'compile-time-value'.
213 (syntax-rules (int128 array)
219 (let-syntax ((v (lambda (s)
220 ;; When compiling natively, call 'sizeof' at expansion
221 ;; time; otherwise, emit code to call it at run time.
224 (if (= (target-word-size)
225 (with-target %host-type target-word-size))
227 #'(alignof type)))))))
230 (define-syntax align ;as found in (system foreign)
232 "Add to OFFSET whatever it takes to get proper alignment for TYPE."
233 ((_ offset (type ~ endianness))
236 (1+ (logior (1- offset) (1- (alignof* type)))))))
238 (define-syntax type-size
245 (define-syntax struct-alignment
247 "Compute the alignment for the aggregate made of TYPES at OFFSET. The
248 result is the alignment of the \"most strictly aligned component\"."
249 ((_ offset types ...)
250 (max (align offset types) ...))))
252 (define-syntax struct-size
254 "Return the size in bytes of the structure made of TYPES."
255 ((_ offset (types-processed ...))
256 ;; The SysV ABI P.S. says: "Aggregates (structures and arrays) and unions
257 ;; assume the alignment of their most strictly aligned component." As an
258 ;; example, a struct such as "int32, int16" has size 8, not 6.
259 (1+ (logior (1- offset)
260 (1- (struct-alignment offset types-processed ...)))))
261 ((_ offset (types-processed ...) type0 types ...)
262 (struct-size (+ (type-size type0) (align offset type0))
263 (type0 types-processed ...)
266 (define-syntax write-type
267 (syntax-rules (~ array *)
268 ((_ bv offset (type ~ order) value)
269 (bytevector-uint-set! bv offset value
270 (endianness order) (sizeof* type)))
271 ((_ bv offset (array type n) value)
278 (write-type bv o type head)
279 (loop (+ 1 i) tail (+ o (sizeof* type))))))))
280 ((_ bv offset '* value)
281 (bytevector-uint-set! bv offset (pointer-address value)
282 (native-endianness) (sizeof* '*)))
283 ((_ bv offset type value)
284 (bytevector-uint-set! bv offset value
285 (native-endianness) (sizeof* type)))))
287 (define-syntax write-types
291 ((_ bv offset (type0 types ...) (field0 fields ...))
293 (write-type bv (align offset type0) type0 field0)
295 (+ (align offset type0) (type-size type0))
296 (types ...) (fields ...))))))
298 (define-syntax read-type
299 (syntax-rules (~ array quote *)
301 (make-pointer (bytevector-uint-ref bv offset
304 ((_ bv offset (type ~ order))
305 (bytevector-uint-ref bv offset
306 (endianness order) (sizeof* type)))
307 ((_ bv offset (array type n))
308 (unfold (lambda (i) (= i n))
310 (read-type bv (+ offset (* i (sizeof* type))) type))
314 (bytevector-uint-ref bv offset
315 (native-endianness) (sizeof* type)))))
317 (define-syntax read-types
319 ((_ return bv offset () (values ...))
321 ((_ return bv offset (type0 types ...) (values ...))
324 (+ (align offset type0) (type-size type0))
326 (values ... (read-type bv
330 (define-syntax define-c-struct-macro
332 "Define NAME as a macro that can be queried to get information about the C
333 struct it represents. In particular:
335 (NAME field-offset FIELD)
337 returns the offset in bytes of FIELD within the C struct represented by NAME."
338 ((_ name ((fields types) ...))
339 (define-c-struct-macro name
341 ((fields types) ...)))
342 ((_ name (fields ...) offset (clauses ...) ((field type) rest ...))
343 (define-c-struct-macro name
345 (+ (align offset type) (type-size type))
346 (clauses ... ((_ field-offset field) (align offset type)))
348 ((_ name (fields ...) offset (clauses ...) ())
350 (syntax-rules (field-offset fields ...)
353 (define-syntax define-c-struct
355 "Define SIZE as the size in bytes of the C structure made of FIELDS. READ
356 as a deserializer and WRITE! as a serializer for the C structure with the
357 given TYPES. READ uses WRAP-FIELDS to return its value."
358 ((_ name size wrap-fields read write! (fields types) ...)
360 (define-c-struct-macro name
361 ((fields types) ...))
363 (struct-size 0 () types ...))
364 (define (write! bv offset fields ...)
365 (write-types bv offset (types ...) (fields ...)))
366 (define* (read bv #:optional (offset 0))
367 (read-types wrap-fields bv offset (types ...) ()))))))
369 (define-syntax-rule (c-struct-field-offset type field)
370 "Return the offset in BYTES of FIELD within TYPE, where TYPE is a C struct
371 defined with 'define-c-struct' and FIELD is a field identifier. An
372 expansion-time error is raised if FIELD does not exist in TYPE."
373 (type field-offset field))
380 (define (call-with-restart-on-EINTR thunk)
385 (if (= (system-error-errno args) EINTR)
387 (apply throw args))))))
389 (define-syntax-rule (restart-on-EINTR expr)
390 "Evaluate EXPR and restart upon EINTR. Return the value of EXPR."
391 (call-with-restart-on-EINTR (lambda () expr)))
393 (define (syscall->procedure return-type name argument-types)
394 "Return a procedure that wraps the C function NAME using the dynamic FFI,
395 and that returns two values: NAME's return value, and errno.
397 If an error occurs while creating the binding, defer the error report until
398 the returned procedure is called."
401 (let ((ptr (dynamic-func name (dynamic-link))))
402 ;; The #:return-errno? facility was introduced in Guile 2.0.12.
403 (pointer->procedure return-type ptr argument-types
404 #:return-errno? #t)))
407 (throw 'system-error name "~A" (list (strerror ENOSYS))
410 (define-syntax define-as-needed
412 "Define VARIABLE. If VARIABLE already exists in (guile) then re-export it,
413 otherwise export the newly-defined VARIABLE."
414 ((_ (proc args ...) body ...)
415 (define-as-needed proc (lambda* (args ...) body ...)))
417 (if (module-defined? the-scm-module 'variable)
418 (module-re-export! (current-module) '(variable))
420 (module-define! (current-module) 'variable value)
421 (module-export! (current-module) '(variable)))))))
428 (define (augment-mtab source target type options)
429 "Augment /etc/mtab with information about the given mount point."
430 (let ((port (open-file "/etc/mtab" "a")))
431 (format port "~a ~a ~a ~a 0 0~%"
432 source target type (or options "rw"))
435 (define (read-mtab port)
436 "Read an mtab-formatted file from PORT, returning a list of tuples."
437 (let loop ((result '()))
438 (let ((line (read-line port)))
439 (if (eof-object? line)
441 (loop (cons (string-tokenize line) result))))))
443 (define (remove-from-mtab target)
444 "Remove mount point TARGET from /etc/mtab."
446 (remove (match-lambda
447 ((device mount-point type options freq passno)
448 (string=? target mount-point))
450 (call-with-input-file "/etc/mtab" read-mtab)))
452 (call-with-output-file "/etc/mtab"
454 (for-each (match-lambda
455 ((device mount-point type options freq passno)
456 (format port "~a ~a ~a ~a ~a ~a~%"
457 device mount-point type options freq passno)))
460 ;; Linux mount flags, from libc's <sys/mount.h>.
465 (define MS_REMOUNT 32)
466 (define MS_NOATIME 1024)
467 (define MS_BIND 4096)
468 (define MS_MOVE 8192)
469 (define MS_STRICTATIME 16777216)
470 (define MS_LAZYTIME 33554432)
473 (define MNT_DETACH 2)
474 (define MNT_EXPIRE 4)
475 (define UMOUNT_NOFOLLOW 8)
477 (define-as-needed (mount source target type
478 #:optional (flags 0) options
479 #:key (update-mtab? #f))
480 "Mount device SOURCE on TARGET as a file system TYPE.
481 Optionally, FLAGS may be a bitwise-or of the MS_* <sys/mount.h>
482 constants, and OPTIONS may be a string. When FLAGS contains
483 MS_REMOUNT, SOURCE and TYPE are ignored. When UPDATE-MTAB? is true,
484 update /etc/mtab. Raise a 'system-error' exception on error."
485 ;; XXX: '#:update-mtab?' is not implemented by core 'mount'.
486 (let ((proc (syscall->procedure int "mount" `(* * * ,unsigned-long *))))
487 (let-values (((ret err)
489 (string->pointer source)
491 (string->pointer target)
493 (string->pointer type)
497 (string->pointer options)
500 (throw 'system-error "mount" "mount ~S on ~S: ~A"
501 (list source target (strerror err))
504 (augment-mtab source target type options)))))
506 (define-as-needed (umount target
508 #:key (update-mtab? #f))
509 "Unmount TARGET. Optionally FLAGS may be one of the MNT_* or UMOUNT_*
510 constants from <sys/mount.h>."
511 ;; XXX: '#:update-mtab?' is not implemented by core 'umount'.
512 (let ((proc (syscall->procedure int "umount2" `(* ,int))))
513 (let-values (((ret err)
514 (proc (string->pointer target) flags)))
516 (throw 'system-error "umount" "~S: ~A"
517 (list target (strerror err))
520 (remove-from-mtab target)))))
522 (define (mount-points)
523 "Return the mounts points for currently mounted file systems."
524 (call-with-input-file "/proc/mounts"
526 (let loop ((result '()))
527 (let ((line (read-line port)))
528 (if (eof-object? line)
530 (match (string-tokenize line)
531 ((source mount-point _ ...)
532 (loop (cons mount-point result))))))))))
535 (let ((proc (syscall->procedure int "swapon" (list '* int))))
536 (lambda* (device #:optional (flags 0))
537 "Use the block special device at DEVICE for swapping."
538 (let-values (((ret err)
539 (proc (string->pointer device) flags)))
541 (throw 'system-error "swapon" "~S: ~A"
542 (list device (strerror err))
546 (let ((proc (syscall->procedure int "swapoff" '(*))))
548 "Stop using block special device DEVICE for swapping."
549 (let-values (((ret err) (proc (string->pointer device))))
551 (throw 'system-error "swapoff" "~S: ~A"
552 (list device (strerror err))
555 (define-as-needed RB_AUTOBOOT #x01234567)
556 (define-as-needed RB_HALT_SYSTEM #xcdef0123)
557 (define-as-needed RB_ENABLED_CAD #x89abcdef)
558 (define-as-needed RB_DISABLE_CAD 0)
559 (define-as-needed RB_POWER_OFF #x4321fedc)
560 (define-as-needed RB_SW_SUSPEND #xd000fce2)
561 (define-as-needed RB_KEXEC #x45584543)
563 (define-as-needed (reboot #:optional (cmd RB_AUTOBOOT))
564 (let ((proc (syscall->procedure int "reboot" (list int))))
565 (let-values (((ret err) (proc cmd)))
567 (throw 'system-error "reboot" "~S: ~A"
568 (list cmd (strerror err))
571 (define-as-needed (load-linux-module data #:optional (options ""))
572 (let ((proc (syscall->procedure int "init_module"
573 (list '* unsigned-long '*))))
574 (let-values (((ret err)
575 (proc (bytevector->pointer data)
576 (bytevector-length data)
577 (string->pointer options))))
579 (throw 'system-error "load-linux-module" "~A"
580 (list (strerror err))
583 (define (kernel? pid)
584 "Return #t if PID designates a \"kernel thread\" rather than a normal
586 (let ((stat (call-with-input-file (format #f "/proc/~a/stat" pid)
587 (compose string-tokenize read-string))))
588 ;; See proc.txt in Linux's documentation for the list of fields.
590 ((pid tcomm state ppid pgrp sid tty_nr tty_pgrp flags min_flt
591 cmin_flt maj_flt cmaj_flt utime stime cutime cstime
592 priority nice num_thread it_real_value start_time
594 (= string->number start_code) (= string->number end_code) _ ...)
595 ;; Got this obscure trick from sysvinit's 'killall5' program.
596 (and (zero? start_code) (zero? end_code))))))
599 "Return the list of live processes."
600 (sort (filter-map (lambda (file)
601 (let ((pid (string->number file)))
609 (let ((proc (syscall->procedure '* "mkdtemp" '(*))))
611 "Create a new unique directory in the file system using the template
612 string TMPL and return its file name. TMPL must end with 'XXXXXX'."
613 (let-values (((result err) (proc (string->pointer tmpl))))
614 (when (null-pointer? result)
615 (throw 'system-error "mkdtemp!" "~S: ~A"
616 (list tmpl (strerror err))
618 (pointer->string result)))))
621 (let ((proc (syscall->procedure int "fdatasync" (list int))))
623 "Flush buffered output of PORT, an output file port, and then call
624 fdatasync(2) on the underlying file descriptor."
626 (let*-values (((fd) (fileno port))
627 ((ret err) (proc fd)))
629 (throw 'system-error "fdatasync" "~S: ~A"
630 (list fd (strerror err))
634 (define-record-type <file-system>
635 (file-system type block-size blocks blocks-free
636 blocks-available files free-files identifier
637 name-length fragment-size mount-flags spare)
639 (type file-system-type)
640 (block-size file-system-block-size)
641 (blocks file-system-block-count)
642 (blocks-free file-system-blocks-free)
643 (blocks-available file-system-blocks-available)
644 (files file-system-file-count)
645 (free-files file-system-free-file-nodes)
646 (identifier file-system-identifier)
647 (name-length file-system-maximum-name-length)
648 (fragment-size file-system-fragment-size)
649 (mount-flags file-system-mount-flags)
650 (spare file-system--spare))
652 (define-syntax fsword ;fsword_t
653 (identifier-syntax long))
655 (define-c-struct %statfs ;<bits/statfs.h>
656 sizeof-statfs ;slightly overestimated
664 (blocks-available uint64)
667 (identifier (array int 2))
669 (fragment-size fsword)
671 (spare (array fsword 4)))
674 (let ((proc (syscall->procedure int "statfs64" '(* *))))
676 "Return a <file-system> data structure describing the file system
678 (let*-values (((stat) (make-bytevector sizeof-statfs))
679 ((ret err) (proc (string->pointer file)
680 (bytevector->pointer stat))))
683 (throw 'system-error "statfs" "~A: ~A"
684 (list file (strerror err))
687 (define (free-disk-space file)
688 "Return the free disk space, in bytes, on the file system that hosts FILE."
689 (let ((fs (statfs file)))
690 (* (file-system-block-size fs)
691 (file-system-blocks-available fs))))
693 ;; Flags for the *at command, notably the 'utime' procedure of libguile.
695 (define-as-needed AT_FDCWD -100)
696 (define-as-needed AT_SYMLINK_NOFOLLOW #x100)
697 (define-as-needed AT_REMOVEDIR #x200)
698 (define-as-needed AT_SYMLINK_FOLLOW #x400)
699 (define-as-needed AT_NO_AUTOMOUNT #x800)
700 (define-as-needed AT_EMPTY_PATH #x1000)
702 (define-syntax BLKRRPART ;<sys/mount.h>
703 (identifier-syntax #x125F))
705 (define* (device-in-use? device)
706 "Return #t if the block DEVICE is in use, #f otherwise. This is inspired
707 from fdisk_device_is_used function of util-linux. This is particularly useful
708 for devices that do not appear in /proc/self/mounts like overlayfs lowerdir
710 (let*-values (((fd) (open-fdes device O_RDONLY))
711 ((ret err) (%ioctl fd BLKRRPART %null-pointer)))
719 ;; We get EINVAL for devices that have the GENHD_FL_NO_PART_SCAN flag
720 ;; set in the kernel, in particular loopback devices, though we do seem
721 ;; to get it for SCSI storage (/dev/sr0) on QEMU.
724 (throw 'system-error "ioctl" "~A"
725 (list (strerror err))
729 (let ((proc (syscall->procedure ssize_t "getxattr"
732 "Get the extended attribute value for KEY on FILE."
733 (let-values (((size err)
734 ;; Get size of VALUE for buffer.
735 (proc (string->pointer/utf-8 file)
736 (string->pointer key)
739 (cond ((< size 0) #f)
741 ;; Get VALUE in buffer of SIZE. XXX actual size can race.
742 (else (let*-values (((buf) (make-bytevector size))
744 (proc (string->pointer/utf-8 file)
745 (string->pointer key)
746 (bytevector->pointer buf)
750 (throw 'system-error "getxattr" "~S: ~A"
751 (list file key (strerror err))
755 (let ((proc (syscall->procedure int "setxattr"
756 `(* * * ,size_t ,int))))
757 (lambda* (file key value #:optional (flags 0))
758 "Set extended attribute KEY to VALUE on FILE."
759 (let*-values (((bv) (string->utf8 value))
761 (proc (string->pointer/utf-8 file)
762 (string->pointer key)
763 (bytevector->pointer bv)
764 (bytevector-length bv)
767 (throw 'system-error "setxattr" "~S: ~A"
768 (list file key value (strerror err))
776 ;; From <uapi/linux/random.h>.
777 (define RNDADDTOENTCNT #x40045201)
779 (define (add-to-entropy-count port-or-fd n)
780 "Add N to the kernel's entropy count (the value that can be read from
781 /proc/sys/kernel/random/entropy_avail). PORT-OR-FD must correspond to
782 /dev/urandom or /dev/random. Raise to 'system-error with EPERM when the
783 caller lacks root privileges."
784 (let ((fd (if (port? port-or-fd)
787 (box (make-bytevector (sizeof int))))
788 (bytevector-sint-set! box 0 n (native-endianness)
790 (let-values (((ret err)
791 (%ioctl fd RNDADDTOENTCNT
792 (bytevector->pointer box))))
794 (throw 'system-error "add-to-entropy-count" "~A"
795 (list (strerror err))
803 ;; Linux clone flags, from linux/sched.h
804 (define CLONE_CHILD_CLEARTID #x00200000)
805 (define CLONE_CHILD_SETTID #x01000000)
806 (define CLONE_NEWNS #x00020000)
807 (define CLONE_NEWUTS #x04000000)
808 (define CLONE_NEWIPC #x08000000)
809 (define CLONE_NEWUSER #x10000000)
810 (define CLONE_NEWPID #x20000000)
811 (define CLONE_NEWNET #x40000000)
813 (define %set-automatic-finalization-enabled?!
814 ;; When using a statically-linked Guile, for instance in the initrd, we
815 ;; cannot resolve this symbol, but most of the time we don't need it
816 ;; anyway. Thus, delay it.
818 (pointer->procedure int
820 "scm_set_automatic_finalization_enabled"
824 "Switch on or off automatic finalization in a separate thread.
825 Turning finalization off shuts down the finalization thread as a side effect."
826 (->bool ((force proc) (if enabled? 1 0))))))
828 (define-syntax-rule (without-automatic-finalization exp)
829 "Turn off automatic finalization within the dynamic extent of EXP."
833 (set! enabled? (%set-automatic-finalization-enabled?! #f)))
837 (%set-automatic-finalization-enabled?! enabled?)))))
839 ;; The libc interface to sys_clone is not useful for Scheme programs, so the
840 ;; low-level system call is wrapped instead. The 'syscall' function is
841 ;; declared in <unistd.h> as a variadic function; in practice, it expects 6
842 ;; pointer-sized arguments, as shown in, e.g., x86_64/syscall.S.
844 (let* ((proc (syscall->procedure int "syscall"
849 ;; TODO: Don't do this.
850 (syscall-id (match (utsname:machine (uname))
858 "Create a new child process by duplicating the current parent process.
859 Unlike the fork system call, clone accepts FLAGS that specify which resources
860 are shared between the parent and child processes."
861 (let-values (((ret err)
862 ;; Guile 2.2 runs a finalization thread. 'primitive-fork'
863 ;; takes care of shutting it down before forking, and we
864 ;; must do the same here. Failing to do that, if the
865 ;; child process calls 'primitive-fork', it will hang
866 ;; while trying to pthread_join the finalization thread
867 ;; since that thread does not exist.
868 (without-automatic-finalization
869 (proc syscall-id flags
870 %null-pointer ;child stack
871 %null-pointer %null-pointer ;ptid & ctid
872 %null-pointer)))) ;unused
874 (throw 'system-error "clone" "~d: ~A"
875 (list flags (strerror err))
880 ;; Some systems may be using an old (pre-2.14) version of glibc where there
881 ;; is no 'setns' function available.
883 (let ((proc (syscall->procedure int "setns" (list int int))))
884 (lambda (fdes nstype)
885 "Reassociate the current process with the namespace specified by FDES, a
886 file descriptor obtained by opening a /proc/PID/ns/* file. NSTYPE specifies
887 which type of namespace the current process may be reassociated with, or 0 if
888 there is no such limitation."
889 (let-values (((ret err) (proc fdes nstype)))
891 (throw 'system-error "setns" "~d ~d: ~A"
892 (list fdes nstype (strerror err))
896 (let ((proc (syscall->procedure int "pivot_root" (list '* '*))))
897 (lambda (new-root put-old)
898 "Change the root file system to NEW-ROOT and move the current root file
900 (let-values (((ret err)
901 (proc (string->pointer new-root)
902 (string->pointer put-old))))
904 (throw 'system-error "pivot_root" "~S ~S: ~A"
905 (list new-root put-old (strerror err))
913 (define (file-type->symbol type)
914 ;; Convert TYPE to symbols like 'stat:type' does.
915 (cond ((= type DT_REG) 'regular)
916 ((= type DT_LNK) 'symlink)
917 ((= type DT_DIR) 'directory)
918 ((= type DT_FIFO) 'fifo)
919 ((= type DT_CHR) 'char-special)
920 ((= type DT_BLK) 'block-special)
921 ((= type DT_SOCK) 'socket)
924 ;; 'struct dirent64' for GNU/Linux.
925 (define-c-struct %struct-dirent-header/linux
926 sizeof-dirent-header/linux
927 (lambda (inode offset length type name)
928 `((type . ,(file-type->symbol type))
930 read-dirent-header/linux
931 write-dirent-header!/linux
934 (length unsigned-short)
936 (name uint8)) ;first byte of 'd_name'
938 ;; 'struct dirent64' for GNU/Hurd.
939 (define-c-struct %struct-dirent-header/hurd
940 sizeof-dirent-header/hurd
941 (lambda (inode length type name-length name)
942 `((type . ,(file-type->symbol type))
944 read-dirent-header/hurd
945 write-dirent-header!/hurd
947 (length unsigned-short)
952 ;; Constants for the 'type' field, from <dirent.h>.
953 (define DT_UNKNOWN 0)
963 (define string->pointer/utf-8
964 (cut string->pointer <> "UTF-8"))
966 (define pointer->string/utf-8
967 (cut pointer->string <> <> "UTF-8"))
970 (let ((proc (syscall->procedure '* "opendir" '(*))))
971 (lambda* (name #:optional (string->pointer string->pointer/utf-8))
972 (let-values (((ptr err)
973 (proc (string->pointer name))))
974 (if (null-pointer? ptr)
975 (throw 'system-error "opendir*"
976 "~A: ~A" (list name (strerror err))
981 (let ((proc (syscall->procedure int "closedir" '(*))))
983 (let-values (((ret err)
986 (throw 'system-error "closedir"
987 "closedir: ~A" (list (strerror err))
990 (define (readdir-procedure name-field-offset sizeof-dirent-header
992 (let ((proc (syscall->procedure '* "readdir64" '(*))))
993 (lambda* (directory #:optional (pointer->string pointer->string/utf-8))
994 (let ((ptr (proc directory)))
995 (and (not (null-pointer? ptr))
996 (cons (pointer->string
997 (make-pointer (+ (pointer-address ptr) name-field-offset))
1000 (pointer->bytevector ptr sizeof-dirent-header))))))))
1003 ;; Decide at run time which one must be used.
1004 (if (string-contains %host-type "linux-gnu")
1005 (readdir-procedure (c-struct-field-offset %struct-dirent-header/linux
1007 sizeof-dirent-header/linux
1008 read-dirent-header/linux)
1009 (readdir-procedure (c-struct-field-offset %struct-dirent-header/hurd
1011 sizeof-dirent-header/hurd
1012 read-dirent-header/hurd)))
1014 (define* (scandir* name #:optional
1015 (select? (const #t))
1016 (entry<? (lambda (entry1 entry2)
1021 (string<? name1 name2)))))))
1023 (string->pointer string->pointer/utf-8)
1024 (pointer->string pointer->string/utf-8))
1025 "This procedure improves on Guile's 'scandir' procedure in several ways:
1027 1. Systematically encode decode file names using STRING->POINTER and
1028 POINTER->STRING (UTF-8 by default; this works around a defect in Guile 2.0/2.2
1029 where 'scandir' decodes file names according to the current locale, which is
1030 not always desirable.
1032 2. Each entry that is returned has the form (NAME . PROPERTIES).
1033 PROPERTIES is an alist showing additional properties about the entry, as
1034 found in 'struct dirent'. An entry may look like this:
1036 (\"foo.scm\" (type . regular) (inode . 123456))
1038 Callers must be prepared to deal with the case where 'type' is 'unknown'
1039 since some file systems do not provide that information.
1041 3. Raise to 'system-error' when NAME cannot be opened."
1042 (let ((directory (opendir* name string->pointer)))
1046 (let loop ((result '()))
1047 (match (readdir* directory pointer->string)
1049 (sort result entry<?))
1051 (loop (if (select? entry)
1055 (closedir* directory)))))
1059 ;;; Advisory file locking.
1062 (define-c-struct %struct-flock ;<fcntl.h>
1074 ;; On Linux-based systems, this is usually 7, but not always
1075 ;; (exceptions include SPARC.) On GNU/Hurd, it's 9.
1076 (cond ((string-contains %host-type "sparc") 9) ; sparc-*-linux-gnu
1077 ((string-contains %host-type "linux") 7) ; *-linux-gnu
1081 ;; Likewise: GNU/Hurd and SPARC use 8, while the others typically use 6.
1082 (cond ((string-contains %host-type "sparc") 8) ; sparc-*-linux-gnu
1083 ((string-contains %host-type "linux") 6) ; *-linux-gnu
1087 ;; The F_RDLCK, F_WRLCK, and F_UNLCK constants.
1088 (cond ((string-contains %host-type "sparc") #(1 2 3)) ; sparc-*-linux-gnu
1089 ((string-contains %host-type "hppa") #(1 2 3)) ; hppa-*-linux-gnu
1090 ((string-contains %host-type "linux") #(0 1 2)) ; *-linux-gnu
1091 (else #(1 2 3)))) ; *-gnu*
1094 (let ((proc (syscall->procedure int "fcntl" `(,int ,int *))))
1095 (lambda* (fd-or-port operation #:key (wait? #t))
1096 "Perform locking OPERATION on the file beneath FD-OR-PORT. OPERATION
1097 must be a symbol, one of 'read-lock, 'write-lock, or 'unlock. When WAIT? is
1098 true, block until the lock is acquired; otherwise, thrown an 'flock-error'
1099 exception if it's already taken."
1100 (define (operation->int op)
1102 ((read-lock) (vector-ref F_xxLCK 0))
1103 ((write-lock) (vector-ref F_xxLCK 1))
1104 ((unlock) (vector-ref F_xxLCK 2))
1105 (else (error "invalid fcntl-flock operation" op))))
1108 (if (port? fd-or-port)
1113 (make-bytevector sizeof-flock))
1116 (operation->int operation) SEEK_SET
1120 ;; XXX: 'fcntl' is a vararg function, but here we happily use the
1121 ;; standard ABI; crossing fingers.
1122 (let-values (((ret err)
1125 F_SETLKW ;lock & wait
1126 F_SETLK) ;non-blocking attempt
1127 (bytevector->pointer bv))))
1129 ;; Presumably we got EAGAIN or so.
1130 (throw 'flock-error err))))))
1132 (define* (lock-file file #:key (wait? #t))
1133 "Wait and acquire an exclusive lock on FILE. Return an open port."
1134 (let ((port (open-file file "w0")))
1135 (fcntl-flock port 'write-lock #:wait? wait?)
1138 (define (unlock-file port)
1139 "Unlock PORT, a port returned by 'lock-file'."
1140 (fcntl-flock port 'unlock)
1144 (define (call-with-file-lock file thunk)
1149 (catch 'system-error
1153 ;; When using the statically-linked Guile in the initrd,
1154 ;; 'fcntl-flock' returns ENOSYS unconditionally. Ignore
1155 ;; that error since we're typically the only process running
1157 (if (= ENOSYS (system-error-errno args))
1159 (apply throw args))))))
1163 (unlock-file port))))))
1165 (define (call-with-file-lock/no-wait file thunk handler)
1172 (lock-file file #:wait? #f))
1173 (lambda (key . args)
1176 (apply handler args)
1177 ;; No open port to the lock, so return #f.
1180 ;; When using the statically-linked Guile in the initrd,
1181 ;; 'fcntl-flock' returns ENOSYS unconditionally. Ignore
1182 ;; that error since we're typically the only process running
1184 (if (= ENOSYS (system-error-errno (cons key args)))
1186 (apply throw key args)))
1187 (_ (apply throw key args)))))))
1191 (unlock-file port))))))
1193 (define-syntax-rule (with-file-lock file exp ...)
1194 "Wait to acquire a lock on FILE and evaluate EXP in that context."
1195 (call-with-file-lock file (lambda () exp ...)))
1197 (define-syntax-rule (with-file-lock/no-wait file handler exp ...)
1198 "Try to acquire a lock on FILE and evaluate EXP in that context. Execute
1199 handler if the lock is already held by another process."
1200 (call-with-file-lock/no-wait file (lambda () exp ...) handler))
1204 ;;; Miscellaneous, aka. 'prctl'.
1208 ;; Should it win the API contest against 'ioctl'? You tell us!
1209 (syscall->procedure int "prctl"
1210 (list int unsigned-long unsigned-long
1211 unsigned-long unsigned-long)))
1213 (define PR_SET_NAME 15) ;<linux/prctl.h>
1214 (define PR_GET_NAME 16)
1216 (define %max-thread-name-length
1217 ;; Maximum length in bytes of the process name, including the terminating
1221 (define (set-thread-name name)
1222 "Set the name of the calling thread to NAME. NAME is truncated to 15
1224 (let ((ptr (string->pointer name)))
1225 (let-values (((ret err)
1227 (pointer-address ptr) 0 0 0)))
1229 (throw 'set-process-name "set-process-name"
1230 "set-process-name: ~A"
1231 (list (strerror err))
1234 (define (thread-name)
1235 "Return the name of the calling thread as a string."
1236 (let ((buf (make-bytevector %max-thread-name-length)))
1237 (let-values (((ret err)
1239 (pointer-address (bytevector->pointer buf))
1242 (bytes->string (bytevector->u8-list buf))
1243 (throw 'process-name "process-name"
1245 (list (strerror err))
1250 ;;; Network interfaces.
1253 (define SIOCGIFCONF ;from <bits/ioctls.h>
1256 (if (string-contains %host-type "linux")
1258 #xf00801a4)) ;GNU/Hurd
1259 (define SIOCGIFFLAGS
1260 (if (string-contains %host-type "linux")
1262 #xc4804191)) ;GNU/Hurd
1263 (define SIOCSIFFLAGS
1264 (if (string-contains %host-type "linux")
1266 #x84804190)) ;GNU/Hurd
1268 (if (string-contains %host-type "linux")
1270 #xc08401a1)) ;GNU/Hurd
1272 (if (string-contains %host-type "linux")
1274 #x8084018c)) ;GNU/Hurd
1275 (define SIOCGIFNETMASK
1276 (if (string-contains %host-type "linux")
1278 #xc08401a5)) ;GNU/Hurd
1279 (define SIOCSIFNETMASK
1280 (if (string-contains %host-type "linux")
1282 #x80840196)) ;GNU/Hurd
1284 (if (string-contains %host-type "linux")
1286 -1)) ;FIXME: GNU/Hurd?
1288 (if (string-contains %host-type "linux")
1290 -1)) ;FIXME: GNU/Hurd?
1292 ;; Flags and constants from <net/if.h>.
1294 (define-as-needed IFF_UP #x1) ;Interface is up
1295 (define-as-needed IFF_BROADCAST #x2) ;Broadcast address valid.
1296 (define-as-needed IFF_LOOPBACK #x8) ;Is a loopback net.
1297 (define-as-needed IFF_RUNNING #x40) ;interface RFC2863 OPER_UP
1298 (define-as-needed IFF_NOARP #x80) ;ARP disabled or unsupported
1300 (define IF_NAMESIZE 16) ;maximum interface name size
1302 (define-c-struct %ifconf-struct
1307 (length int) ;int ifc_len
1308 (request '*)) ;struct ifreq *ifc_ifcu
1310 (define ifreq-struct-size
1311 ;; 'struct ifreq' begins with an array of IF_NAMESIZE bytes containing the
1312 ;; interface name (nul-terminated), followed by a bunch of stuff. This is
1313 ;; its size in bytes.
1314 (if (= 8 (sizeof '*))
1318 (define-c-struct sockaddr-in ;<linux/in.h>
1320 (lambda (family port address)
1321 (make-socket-address family address port))
1324 (family unsigned-short)
1325 (port (int16 ~ big))
1326 (address (int32 ~ big)))
1328 (define-c-struct sockaddr-in6 ;<linux/in6.h>
1330 (lambda (family port flowinfo address scopeid)
1331 (make-socket-address family address port flowinfo scopeid))
1334 (family unsigned-short)
1335 (port (int16 ~ big))
1336 (flowinfo (int32 ~ big))
1337 (address (int128 ~ big))
1340 (define (write-socket-address! sockaddr bv index)
1341 "Write SOCKADDR, a socket address as returned by 'make-socket-address', to
1342 bytevector BV at INDEX."
1343 (let ((family (sockaddr:fam sockaddr)))
1344 (cond ((= family AF_INET)
1345 (write-sockaddr-in! bv index
1347 (sockaddr:port sockaddr)
1348 (sockaddr:addr sockaddr)))
1349 ((= family AF_INET6)
1350 (write-sockaddr-in6! bv index
1352 (sockaddr:port sockaddr)
1353 (sockaddr:flowinfo sockaddr)
1354 (sockaddr:addr sockaddr)
1355 (sockaddr:scopeid sockaddr)))
1357 (error "unsupported socket address" sockaddr)))))
1359 (define PF_PACKET 17) ;<bits/socket.h>
1360 (define AF_PACKET PF_PACKET)
1362 (define* (read-socket-address bv #:optional (index 0))
1363 "Read a socket address from bytevector BV at INDEX."
1364 (let ((family (bytevector-u16-native-ref bv index)))
1365 (cond ((= family AF_INET)
1366 (read-sockaddr-in bv index))
1367 ((= family AF_INET6)
1368 (read-sockaddr-in6 bv index))
1370 ;; XXX: Unsupported address family, such as AF_PACKET. Return a
1371 ;; vector such that the vector can at least call 'sockaddr:fam'.
1375 ;; The most terrible interface, live from Scheme.
1376 (syscall->procedure int "ioctl" (list int unsigned-long '*)))
1378 (define (bytes->string bytes)
1379 "Read BYTES, a list of bytes, and return the null-terminated string decoded
1380 from there, or #f if that would be an empty string."
1381 (match (take-while (negate zero?) bytes)
1385 (list->string (map integer->char non-zero)))))
1387 (define (bytevector->string-list bv stride len)
1388 "Return the null-terminated strings found in BV every STRIDE bytes. Read at
1389 most LEN bytes from BV."
1390 (let loop ((bytes (take (bytevector->u8-list bv)
1391 (min len (bytevector-length bv))))
1397 (loop (drop bytes stride)
1398 (cons (bytes->string bytes) result))))))
1400 (define* (network-interface-names #:optional sock)
1401 "Return the names of existing network interfaces. This is typically limited
1402 to interfaces that are currently up."
1403 (let* ((close? (not sock))
1404 (sock (or sock (socket SOCK_STREAM AF_INET 0)))
1405 (len (* ifreq-struct-size 10))
1406 (reqs (make-bytevector len))
1407 (conf (make-bytevector sizeof-ifconf)))
1408 (write-ifconf! conf 0
1409 len (bytevector->pointer reqs))
1411 (let-values (((ret err)
1412 (%ioctl (fileno sock) SIOCGIFCONF
1413 (bytevector->pointer conf))))
1417 (bytevector->string-list reqs ifreq-struct-size
1418 (match (read-ifconf conf)
1420 (throw 'system-error "network-interface-list"
1421 "network-interface-list: ~A"
1422 (list (strerror err))
1425 (define %interface-line
1426 ;; Regexp matching an interface line in Linux's /proc/net/dev.
1427 (make-regexp "^[[:blank:]]*([[:graph:]]+):.*$"))
1429 (define (all-network-interface-names)
1430 "Return all the names of the registered network interfaces, including those
1432 (call-with-input-file "/proc/net/dev" ;XXX: Linux-specific
1434 (let loop ((interfaces '()))
1435 (let ((line (read-line port)))
1436 (cond ((eof-object? line)
1437 (reverse interfaces))
1438 ((regexp-exec %interface-line line)
1441 (loop (cons (match:substring match 1) interfaces))))
1443 (loop interfaces))))))))
1445 (define-as-needed (network-interface-flags socket name)
1446 "Return a number that is the bit-wise or of 'IFF*' flags for network
1448 (let ((req (make-bytevector ifreq-struct-size)))
1449 (bytevector-copy! (string->utf8 name) 0 req 0
1450 (min (string-length name) (- IF_NAMESIZE 1)))
1451 (let-values (((ret err)
1452 (%ioctl (fileno socket) SIOCGIFFLAGS
1453 (bytevector->pointer req))))
1456 ;; The 'ifr_flags' field is IF_NAMESIZE bytes after the
1457 ;; beginning of 'struct ifreq', and it's a short int.
1458 (bytevector-sint-ref req IF_NAMESIZE (native-endianness)
1461 (throw 'system-error "network-interface-flags"
1462 "network-interface-flags on ~A: ~A"
1463 (list name (strerror err))
1466 (define (loopback-network-interface? name)
1467 "Return true if NAME designates a loopback network interface."
1468 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1469 (flags (network-interface-flags sock name)))
1471 (not (zero? (logand flags IFF_LOOPBACK)))))
1473 (define (network-interface-running? name)
1474 "Return true if NAME designates a running network interface."
1475 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1476 (flags (network-interface-flags sock name)))
1478 (not (zero? (logand flags IFF_RUNNING)))))
1480 (define (arp-network-interface? name)
1481 "Return true if NAME supports the Address Resolution Protocol."
1482 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1483 (flags (network-interface-flags sock name)))
1485 (zero? (logand flags IFF_NOARP))))
1487 (define-as-needed (set-network-interface-flags socket name flags)
1488 "Set the flag of network interface NAME to FLAGS."
1489 (let ((req (make-bytevector ifreq-struct-size)))
1490 (bytevector-copy! (string->utf8 name) 0 req 0
1491 (min (string-length name) (- IF_NAMESIZE 1)))
1492 ;; Set the 'ifr_flags' field.
1493 (bytevector-uint-set! req IF_NAMESIZE flags (native-endianness)
1495 (let-values (((ret err)
1496 (%ioctl (fileno socket) SIOCSIFFLAGS
1497 (bytevector->pointer req))))
1499 (throw 'system-error "set-network-interface-flags"
1500 "set-network-interface-flags on ~A: ~A"
1501 (list name (strerror err))
1504 (define-as-needed (set-network-interface-address socket name sockaddr)
1505 "Set the address of network interface NAME to SOCKADDR."
1506 (let ((req (make-bytevector ifreq-struct-size)))
1507 (bytevector-copy! (string->utf8 name) 0 req 0
1508 (min (string-length name) (- IF_NAMESIZE 1)))
1509 ;; Set the 'ifr_addr' field.
1510 (write-socket-address! sockaddr req IF_NAMESIZE)
1511 (let-values (((ret err)
1512 (%ioctl (fileno socket) SIOCSIFADDR
1513 (bytevector->pointer req))))
1515 (throw 'system-error "set-network-interface-address"
1516 "set-network-interface-address on ~A: ~A"
1517 (list name (strerror err))
1520 (define (set-network-interface-netmask socket name sockaddr)
1521 "Set the network mask of interface NAME to SOCKADDR."
1522 (let ((req (make-bytevector ifreq-struct-size)))
1523 (bytevector-copy! (string->utf8 name) 0 req 0
1524 (min (string-length name) (- IF_NAMESIZE 1)))
1525 ;; Set the 'ifr_addr' field.
1526 (write-socket-address! sockaddr req IF_NAMESIZE)
1527 (let-values (((ret err)
1528 (%ioctl (fileno socket) SIOCSIFNETMASK
1529 (bytevector->pointer req))))
1531 (throw 'system-error "set-network-interface-netmask"
1532 "set-network-interface-netmask on ~A: ~A"
1533 (list name (strerror err))
1536 (define (network-interface-address socket name)
1537 "Return the address of network interface NAME. The result is an object of
1538 the same type as that returned by 'make-socket-address'."
1539 (let ((req (make-bytevector ifreq-struct-size)))
1540 (bytevector-copy! (string->utf8 name) 0 req 0
1541 (min (string-length name) (- IF_NAMESIZE 1)))
1542 (let-values (((ret err)
1543 (%ioctl (fileno socket) SIOCGIFADDR
1544 (bytevector->pointer req))))
1546 (read-socket-address req IF_NAMESIZE)
1547 (throw 'system-error "network-interface-address"
1548 "network-interface-address on ~A: ~A"
1549 (list name (strerror err))
1552 (define (network-interface-netmask socket name)
1553 "Return the netmask of network interface NAME. The result is an object of
1554 the same type as that returned by 'make-socket-address'."
1555 (let ((req (make-bytevector ifreq-struct-size)))
1556 (bytevector-copy! (string->utf8 name) 0 req 0
1557 (min (string-length name) (- IF_NAMESIZE 1)))
1558 (let-values (((ret err)
1559 (%ioctl (fileno socket) SIOCGIFNETMASK
1560 (bytevector->pointer req))))
1562 (read-socket-address req IF_NAMESIZE)
1563 (throw 'system-error "network-interface-netmask"
1564 "network-interface-netmask on ~A: ~A"
1565 (list name (strerror err))
1568 (define* (configure-network-interface name sockaddr flags
1570 "Configure network interface NAME to use SOCKADDR, an address as returned by
1571 'make-socket-address', and FLAGS, a bitwise-or of IFF_* constants. If NETMASK
1572 is true, it must be a socket address to use as the network mask."
1573 (let ((sock (socket (sockaddr:fam sockaddr) SOCK_STREAM 0)))
1577 (set-network-interface-address sock name sockaddr)
1578 (set-network-interface-flags sock name flags)
1580 (set-network-interface-netmask sock name netmask)))
1582 (close-port sock)))))
1584 (define* (set-network-interface-up name
1585 #:key (family AF_INET))
1586 "Turn up the interface NAME."
1587 (let ((sock (socket family SOCK_STREAM 0)))
1591 (let ((flags (network-interface-flags sock name)))
1592 (set-network-interface-flags sock name
1593 (logior flags IFF_UP))))
1595 (close-port sock)))))
1602 (define-c-struct %rtentry ;'struct rtentry' from <net/route.h>
1607 (pad1 unsigned-long)
1608 (destination (array uint8 16)) ;struct sockaddr
1609 (gateway (array uint8 16)) ;struct sockaddr
1610 (genmask (array uint8 16)) ;struct sockaddr
1611 (flags unsigned-short)
1616 (pad4 (array uint8 (if (= 8 (sizeof* '*)) 3 1)))
1620 (window unsigned-long)
1621 (initial-rtt unsigned-short))
1623 (define RTF_UP #x0001) ;'rtentry' flags from <net/route.h>
1624 (define RTF_GATEWAY #x0002)
1626 (define %sockaddr-any
1627 (make-socket-address AF_INET INADDR_ANY 0))
1629 (define add-network-route/gateway
1630 ;; To allow field names to be matched as literals, we need to move them out
1631 ;; of the lambda's body since the parameters have the same name. A lot of
1632 ;; fuss for very little.
1633 (let-syntax ((gateway-offset (identifier-syntax
1634 (c-struct-field-offset %rtentry gateway)))
1635 (destination-offset (identifier-syntax
1636 (c-struct-field-offset %rtentry destination)))
1637 (genmask-offset (identifier-syntax
1638 (c-struct-field-offset %rtentry genmask))))
1639 (lambda* (socket gateway
1640 #:key (destination %sockaddr-any) (genmask %sockaddr-any))
1641 "Add a network route for DESTINATION (a socket address as returned by
1642 'make-socket-address') that goes through GATEWAY (a socket address). For
1645 (add-network-route/gateway sock
1646 (make-socket-address
1648 (inet-pton AF_INET \"192.168.0.1\")
1651 is equivalent to this 'net-tools' command:
1653 route add -net default gw 192.168.0.1
1655 because the default value of DESTINATION is \"0.0.0.0\"."
1656 (let ((route (make-bytevector sizeof-rtentry 0)))
1657 (write-socket-address! gateway route gateway-offset)
1658 (write-socket-address! destination route destination-offset)
1659 (write-socket-address! genmask route genmask-offset)
1660 (bytevector-u16-native-set! route
1661 (c-struct-field-offset %rtentry flags)
1662 (logior RTF_UP RTF_GATEWAY))
1663 (let-values (((ret err)
1664 (%ioctl (fileno socket) SIOCADDRT
1665 (bytevector->pointer route))))
1667 (throw 'system-error "add-network-route/gateway"
1668 "add-network-route/gateway: ~A"
1669 (list (strerror err))
1672 (define delete-network-route
1673 (let-syntax ((destination-offset (identifier-syntax
1674 (c-struct-field-offset %rtentry destination))))
1675 (lambda* (socket destination)
1676 "Delete the network route for DESTINATION. For instance, the call:
1678 (delete-network-route sock
1679 (make-socket-address AF_INET INADDR_ANY 0))
1681 is equivalent to the 'net-tools' command:
1683 route del -net default
1686 (let ((route (make-bytevector sizeof-rtentry 0)))
1687 (write-socket-address! destination route destination-offset)
1688 (let-values (((ret err)
1689 (%ioctl (fileno socket) SIOCDELRT
1690 (bytevector->pointer route))))
1692 (throw 'system-error "delete-network-route"
1693 "delete-network-route: ~A"
1694 (list (strerror err))
1699 ;;; Details about network interfaces---aka. 'getifaddrs'.
1702 ;; Network interfaces. XXX: We would call it <network-interface> but that
1703 ;; would collide with the ioctl wrappers above.
1704 (define-record-type <interface>
1705 (make-interface name flags address netmask broadcast-address)
1707 (name interface-name) ;string
1708 (flags interface-flags) ;or'd IFF_* values
1709 (address interface-address) ;sockaddr | #f
1710 (netmask interface-netmask) ;sockaddr | #f
1711 (broadcast-address interface-broadcast-address)) ;sockaddr | #f
1713 (define (write-interface interface port)
1715 (($ <interface> name flags address)
1716 (format port "#<interface ~s " name)
1717 (unless (zero? (logand IFF_UP flags))
1718 (display "up " port))
1720 ;; Check whether ADDRESS really is a sockaddr.
1722 (if (member (sockaddr:fam address) (list AF_INET AF_INET6))
1723 (format port "~a " (inet-ntop (sockaddr:fam address)
1724 (sockaddr:addr address)))
1725 (format port "family:~a " (sockaddr:fam address))))
1727 (format port "~a>" (number->string (object-address interface) 16)))))
1729 (set-record-type-printer! <interface> write-interface)
1731 (define (values->interface next name flags address netmask
1732 broadcast-address data)
1733 "Given the raw field values passed as arguments, return a pair whose car is
1734 an <interface> object, and whose cdr is the pointer NEXT."
1735 (define (maybe-socket-address pointer)
1736 (if (null-pointer? pointer)
1738 (read-socket-address (pointer->bytevector pointer 50)))) ;XXX: size
1740 (cons (make-interface (if (null-pointer? name)
1742 (pointer->string name))
1744 (maybe-socket-address address)
1745 (maybe-socket-address netmask)
1746 (maybe-socket-address broadcast-address)
1751 (define-c-struct ifaddrs ;<ifaddrs.h>
1758 (flags unsigned-int)
1764 (define (unfold-interface-list ptr)
1765 "Call 'read-ifaddrs' on PTR and all its 'next' fields, recursively, and
1766 return the list of resulting <interface> objects."
1767 (let loop ((ptr ptr)
1769 (if (null-pointer? ptr)
1771 (match (read-ifaddrs (pointer->bytevector ptr %sizeof-ifaddrs))
1773 (loop ptr (cons ifaddr result)))))))
1775 (define network-interfaces
1776 (let ((proc (syscall->procedure int "getifaddrs" (list '*))))
1778 "Return a list of <interface> objects, each denoting a configured
1779 network interface. This is implemented using the 'getifaddrs' libc function."
1780 (let*-values (((ptr)
1781 (bytevector->pointer (make-bytevector (sizeof* '*))))
1785 (let* ((ptr (dereference-pointer ptr))
1786 (result (unfold-interface-list ptr)))
1789 (throw 'system-error "network-interfaces" "~A"
1790 (list (strerror err))
1793 (define free-ifaddrs
1794 (syscall->procedure void "freeifaddrs" '(*)))
1801 (define-syntax bits->symbols-body
1805 ((_ bits (name names ...) (value values ...))
1806 (let ((result (bits->symbols-body bits (names ...) (values ...))))
1807 (if (zero? (logand bits value))
1809 (cons 'name result))))))
1811 (define-syntax define-bits
1812 (syntax-rules (define)
1813 "Define the given numerical constants under CONSTRUCTOR, such that
1814 (CONSTRUCTOR NAME) returns VALUE. Define BITS->SYMBOLS as a procedure that,
1815 given an integer, returns the list of names of the constants that are or'd."
1816 ((_ constructor bits->symbols (define names values) ...)
1818 (define-syntax constructor
1819 (syntax-rules (names ...)
1821 ((_ names) values) ...
1822 ((_ first rest (... ...))
1823 (logior (constructor first) rest (... ...)))))
1824 (define (bits->symbols bits)
1825 (bits->symbols-body bits (names ...) (values ...)))))))
1827 ;; 'local-flags' bits from <bits/termios.h>
1828 (define-bits local-flags
1829 local-flags->symbols
1830 (define ISIG #o0000001)
1831 (define ICANON #o0000002)
1832 (define XCASE #o0000004)
1833 (define ECHO #o0000010)
1834 (define ECHOE #o0000020)
1835 (define ECHOK #o0000040)
1836 (define ECHONL #o0000100)
1837 (define NOFLSH #o0000200)
1838 (define TOSTOP #o0000400)
1839 (define ECHOCTL #o0001000)
1840 (define ECHOPRT #o0002000)
1841 (define ECHOKE #o0004000)
1842 (define FLUSHO #o0010000)
1843 (define PENDIN #o0040000)
1844 (define IEXTEN #o0100000)
1845 (define EXTPROC #o0200000))
1847 (define-bits input-flags
1848 input-flags->symbols
1849 (define IGNBRK #o0000001)
1850 (define BRKINT #o0000002)
1851 (define IGNPAR #o0000004)
1852 (define PARMRK #o0000010)
1853 (define INPCK #o0000020)
1854 (define ISTRIP #o0000040)
1855 (define INLCR #o0000100)
1856 (define IGNCR #o0000200)
1857 (define ICRNL #o0000400)
1858 (define IUCLC #o0001000)
1859 (define IXON #o0002000)
1860 (define IXANY #o0004000)
1861 (define IXOFF #o0010000)
1862 (define IMAXBEL #o0020000)
1863 (define IUTF8 #o0040000))
1865 ;; "Actions" values for 'tcsetattr'.
1866 (define-bits tcsetattr-action
1867 %unused-tcsetattr-action->symbols
1869 (define TCSADRAIN 1)
1870 (define TCSAFLUSH 2))
1872 (define-record-type <termios>
1873 (termios input-flags output-flags control-flags local-flags
1874 line-discipline control-chars
1875 input-speed output-speed)
1877 (input-flags termios-input-flags)
1878 (output-flags termios-output-flags)
1879 (control-flags termios-control-flags)
1880 (local-flags termios-local-flags)
1881 (line-discipline termios-line-discipline)
1882 (control-chars termios-control-chars)
1883 (input-speed termios-input-speed)
1884 (output-speed termios-output-speed))
1886 (define-c-struct %termios ;<bits/termios.h>
1891 (input-flags unsigned-int)
1892 (output-flags unsigned-int)
1893 (control-flags unsigned-int)
1894 (local-flags unsigned-int)
1895 (line-discipline uint8)
1896 (control-chars (array uint8 32))
1897 (input-speed unsigned-int)
1898 (output-speed unsigned-int))
1901 (let ((proc (syscall->procedure int "tcgetattr" (list int '*))))
1903 "Return the <termios> structure for the tty at FD."
1904 (let*-values (((bv) (make-bytevector sizeof-termios))
1905 ((ret err) (proc fd (bytevector->pointer bv))))
1908 (throw 'system-error "tcgetattr" "~A"
1909 (list (strerror err))
1913 (let ((proc (syscall->procedure int "tcsetattr" (list int int '*))))
1914 (lambda (fd actions termios)
1915 "Use TERMIOS for the tty at FD. ACTIONS is one of of the values
1916 produced by 'tcsetattr-action'; see tcsetattr(3) for details."
1918 (make-bytevector sizeof-termios))
1920 (let-syntax ((match/write (syntax-rules ()
1923 (($ <termios> fields ...)
1924 (write-termios! bv 0 fields ...)))))))
1925 (match/write input-flags output-flags control-flags local-flags
1926 line-discipline control-chars input-speed output-speed))
1928 (let-values (((ret err) (proc fd actions (bytevector->pointer bv))))
1930 (throw 'system-error "tcgetattr" "~A"
1931 (list (strerror err))
1934 (define-syntax TIOCGWINSZ ;<asm-generic/ioctls.h>
1935 (identifier-syntax #x5413))
1937 (define-record-type <window-size>
1938 (window-size rows columns x-pixels y-pixels)
1940 (rows window-size-rows)
1941 (columns window-size-columns)
1942 (x-pixels window-size-x-pixels)
1943 (y-pixels window-size-y-pixels))
1945 (define-c-struct winsize ;<bits/ioctl-types.h>
1950 (rows unsigned-short)
1951 (columns unsigned-short)
1952 (x-pixels unsigned-short)
1953 (y-pixels unsigned-short))
1955 (define* (terminal-window-size #:optional (port (current-output-port)))
1956 "Return a <window-size> structure describing the terminal at PORT, or raise
1957 a 'system-error' if PORT is not backed by a terminal. This procedure
1958 corresponds to the TIOCGWINSZ ioctl."
1959 (let*-values (((size) (make-bytevector sizeof-winsize))
1960 ((ret err) (%ioctl (fileno port) TIOCGWINSZ
1961 (bytevector->pointer size))))
1964 (throw 'system-error "terminal-window-size" "~A"
1965 (list (strerror err))
1968 (define (terminal-dimension window-dimension port fall-back)
1969 "Return the terminal dimension defined by WINDOW-DIMENSION, one of
1970 'window-size-columns' or 'window-size-rows' for PORT. If PORT does not
1971 correspond to a terminal, return the value returned by FALL-BACK."
1972 (catch 'system-error
1974 (if (file-port? port)
1975 (match (window-dimension (terminal-window-size port))
1976 ;; Things like Emacs shell-mode return 0, which is unreasonable.
1981 (let ((errno (system-error-errno args)))
1982 ;; ENOTTY is what we're after but 2012-and-earlier Linux versions
1983 ;; would return EINVAL instead in some cases:
1984 ;; <https://bugs.ruby-lang.org/issues/10494>.
1985 ;; Furthermore, some FUSE file systems like unionfs return ENOSYS for
1987 (if (memv errno (list ENOTTY EINVAL ENOSYS))
1989 (apply throw args))))))
1991 (define* (terminal-columns #:optional (port (current-output-port)))
1992 "Return the best approximation of the number of columns of the terminal at
1993 PORT, trying to guess a reasonable value if all else fails. The result is
1994 always a positive integer."
1996 (match (and=> (getenv "COLUMNS") string->number)
1998 ((? number? columns)
1999 (if (> columns 0) columns 80))))
2001 (terminal-dimension window-size-columns port fall-back))
2003 (define* (terminal-rows #:optional (port (current-output-port)))
2004 "Return the best approximation of the number of rows of the terminal at
2005 PORT, trying to guess a reasonable value if all else fails. The result is
2006 always a positive integer."
2007 (terminal-dimension window-size-rows port (const 25)))
2014 (define-record-type <utmpx-entry>
2015 (utmpx type pid line id user host termination exit
2016 session time address)
2018 (type utmpx-login-type) ;login-type
2020 (line utmpx-line) ;device name
2022 (user utmpx-user) ;user name
2023 (host utmpx-host) ;host name | #f
2024 (termination utmpx-termination-status)
2025 (exit utmpx-exit-status)
2026 (session utmpx-session-id) ;session ID, for windowing
2027 (time utmpx-time) ;entry time
2028 (address utmpx-address))
2030 (define-c-struct %utmpx ;<utmpx.h>
2032 (lambda (type pid line id user host termination exit session
2033 seconds useconds address %reserved)
2035 (bytes->string line) id
2036 (bytes->string user)
2037 (bytes->string host) termination exit
2039 (make-time time-utc (* 1000 useconds) seconds)
2045 (line (array uint8 32))
2046 (id (array uint8 4))
2047 (user (array uint8 32))
2048 (host (array uint8 256))
2052 (time-seconds int32)
2053 (time-useconds int32)
2054 (address-v6 (array int32 4))
2055 (%reserved (array uint8 20)))
2057 (define-bits login-type
2058 %unused-login-type->symbols
2059 (define EMPTY 0) ;No valid user accounting information.
2060 (define RUN_LVL 1) ;The system's runlevel.
2061 (define BOOT_TIME 2) ;Time of system boot.
2062 (define NEW_TIME 3) ;Time after system clock changed.
2063 (define OLD_TIME 4) ;Time when system clock changed.
2065 (define INIT_PROCESS 5) ;Process spawned by the init process.
2066 (define LOGIN_PROCESS 6) ;Session leader of a logged in user.
2067 (define USER_PROCESS 7) ;Normal process.
2068 (define DEAD_PROCESS 8) ;Terminated process.
2070 (define ACCOUNTING 9)) ;System accounting.
2073 (let ((proc (syscall->procedure void "setutxent" '())))
2075 "Open the user accounting database."
2079 (let ((proc (syscall->procedure void "endutxent" '())))
2081 "Close the user accounting database."
2085 (let ((proc (syscall->procedure '* "getutxent" '())))
2087 "Return the next entry from the user accounting database."
2089 (if (null-pointer? ptr)
2091 (read-utmpx (pointer->bytevector ptr sizeof-utmpx)))))))
2093 (define (utmpx-entries)
2094 "Return the list of entries read from the user accounting database."
2096 (let loop ((entries '()))
2102 (loop (cons entry entries))))))
2104 (define (read-utmpx-from-port port)
2105 "Read a utmpx entry from PORT. Return either the EOF object or a utmpx
2107 (match (get-bytevector-n port sizeof-utmpx)
2108 ((? eof-object? eof)
2113 ;;; syscalls.scm ends here