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
87 with-file-lock/no-wait
105 all-network-interface-names
106 network-interface-names
107 network-interface-netmask
108 network-interface-running?
109 loopback-network-interface?
110 arp-network-interface?
111 network-interface-address
112 set-network-interface-netmask
113 set-network-interface-up
114 configure-network-interface
115 add-network-route/gateway
123 interface-broadcast-address
129 termios-control-flags
131 termios-line-discipline
132 termios-control-chars
157 utmpx-termination-status
164 (read-utmpx-from-port . read-utmpx)))
168 ;;; This module provides bindings to libc's syscall wrappers. It uses the
169 ;;; FFI, and thus requires a dynamically-linked Guile.
171 ;;; Some syscalls are already defined in statically-linked Guile by applying
172 ;;; 'guile-linux-syscalls.patch'.
174 ;;; Visibility of syscall's symbols shared between this module and static Guile
175 ;;; is a bit delicate. It is handled by 'define-as-needed' macro.
177 ;;; This macro is used to export symbols in dynamic Guile context, and to
178 ;;; re-export them in static Guile context.
180 ;;; This way, even if they don't appear in #:export list, it is safe to use
181 ;;; syscalls from this module in static or dynamic Guile context.
187 ;;; Packed structures.
190 (define-syntax sizeof*
191 ;; XXX: This duplicates 'compile-time-value'.
192 (syntax-rules (int128 array)
196 (* (sizeof* type) n))
198 (let-syntax ((v (lambda (s)
199 ;; When compiling natively, call 'sizeof' at expansion
200 ;; time; otherwise, emit code to call it at run time.
203 (if (= (target-word-size)
204 (with-target %host-type target-word-size))
206 #'(sizeof type)))))))
209 (define-syntax alignof*
210 ;; XXX: This duplicates 'compile-time-value'.
211 (syntax-rules (int128 array)
217 (let-syntax ((v (lambda (s)
218 ;; When compiling natively, call 'sizeof' at expansion
219 ;; time; otherwise, emit code to call it at run time.
222 (if (= (target-word-size)
223 (with-target %host-type target-word-size))
225 #'(alignof type)))))))
228 (define-syntax align ;as found in (system foreign)
230 "Add to OFFSET whatever it takes to get proper alignment for TYPE."
231 ((_ offset (type ~ endianness))
234 (1+ (logior (1- offset) (1- (alignof* type)))))))
236 (define-syntax type-size
243 (define-syntax struct-alignment
245 "Compute the alignment for the aggregate made of TYPES at OFFSET. The
246 result is the alignment of the \"most strictly aligned component\"."
247 ((_ offset types ...)
248 (max (align offset types) ...))))
250 (define-syntax struct-size
252 "Return the size in bytes of the structure made of TYPES."
253 ((_ offset (types-processed ...))
254 ;; The SysV ABI P.S. says: "Aggregates (structures and arrays) and unions
255 ;; assume the alignment of their most strictly aligned component." As an
256 ;; example, a struct such as "int32, int16" has size 8, not 6.
257 (1+ (logior (1- offset)
258 (1- (struct-alignment offset types-processed ...)))))
259 ((_ offset (types-processed ...) type0 types ...)
260 (struct-size (+ (type-size type0) (align offset type0))
261 (type0 types-processed ...)
264 (define-syntax write-type
265 (syntax-rules (~ array *)
266 ((_ bv offset (type ~ order) value)
267 (bytevector-uint-set! bv offset value
268 (endianness order) (sizeof* type)))
269 ((_ bv offset (array type n) value)
276 (write-type bv o type head)
277 (loop (+ 1 i) tail (+ o (sizeof* type))))))))
278 ((_ bv offset '* value)
279 (bytevector-uint-set! bv offset (pointer-address value)
280 (native-endianness) (sizeof* '*)))
281 ((_ bv offset type value)
282 (bytevector-uint-set! bv offset value
283 (native-endianness) (sizeof* type)))))
285 (define-syntax write-types
289 ((_ bv offset (type0 types ...) (field0 fields ...))
291 (write-type bv (align offset type0) type0 field0)
293 (+ (align offset type0) (type-size type0))
294 (types ...) (fields ...))))))
296 (define-syntax read-type
297 (syntax-rules (~ array quote *)
299 (make-pointer (bytevector-uint-ref bv offset
302 ((_ bv offset (type ~ order))
303 (bytevector-uint-ref bv offset
304 (endianness order) (sizeof* type)))
305 ((_ bv offset (array type n))
306 (unfold (lambda (i) (= i n))
308 (read-type bv (+ offset (* i (sizeof* type))) type))
312 (bytevector-uint-ref bv offset
313 (native-endianness) (sizeof* type)))))
315 (define-syntax read-types
317 ((_ return bv offset () (values ...))
319 ((_ return bv offset (type0 types ...) (values ...))
322 (+ (align offset type0) (type-size type0))
324 (values ... (read-type bv
328 (define-syntax define-c-struct-macro
330 "Define NAME as a macro that can be queried to get information about the C
331 struct it represents. In particular:
333 (NAME field-offset FIELD)
335 returns the offset in bytes of FIELD within the C struct represented by NAME."
336 ((_ name ((fields types) ...))
337 (define-c-struct-macro name
339 ((fields types) ...)))
340 ((_ name (fields ...) offset (clauses ...) ((field type) rest ...))
341 (define-c-struct-macro name
343 (+ (align offset type) (type-size type))
344 (clauses ... ((_ field-offset field) (align offset type)))
346 ((_ name (fields ...) offset (clauses ...) ())
348 (syntax-rules (field-offset fields ...)
351 (define-syntax define-c-struct
353 "Define SIZE as the size in bytes of the C structure made of FIELDS. READ
354 as a deserializer and WRITE! as a serializer for the C structure with the
355 given TYPES. READ uses WRAP-FIELDS to return its value."
356 ((_ name size wrap-fields read write! (fields types) ...)
358 (define-c-struct-macro name
359 ((fields types) ...))
361 (struct-size 0 () types ...))
362 (define (write! bv offset fields ...)
363 (write-types bv offset (types ...) (fields ...)))
364 (define* (read bv #:optional (offset 0))
365 (read-types wrap-fields bv offset (types ...) ()))))))
367 (define-syntax-rule (c-struct-field-offset type field)
368 "Return the offset in BYTES of FIELD within TYPE, where TYPE is a C struct
369 defined with 'define-c-struct' and FIELD is a field identifier. An
370 expansion-time error is raised if FIELD does not exist in TYPE."
371 (type field-offset field))
378 (define (call-with-restart-on-EINTR thunk)
383 (if (= (system-error-errno args) EINTR)
385 (apply throw args))))))
387 (define-syntax-rule (restart-on-EINTR expr)
388 "Evaluate EXPR and restart upon EINTR. Return the value of EXPR."
389 (call-with-restart-on-EINTR (lambda () expr)))
391 (define (syscall->procedure return-type name argument-types)
392 "Return a procedure that wraps the C function NAME using the dynamic FFI,
393 and that returns two values: NAME's return value, and errno.
395 If an error occurs while creating the binding, defer the error report until
396 the returned procedure is called."
399 (let ((ptr (dynamic-func name (dynamic-link))))
400 ;; The #:return-errno? facility was introduced in Guile 2.0.12.
401 (pointer->procedure return-type ptr argument-types
402 #:return-errno? #t)))
405 (throw 'system-error name "~A" (list (strerror ENOSYS))
408 (define-syntax define-as-needed
410 "Define VARIABLE. If VARIABLE already exists in (guile) then re-export it,
411 otherwise export the newly-defined VARIABLE."
412 ((_ (proc args ...) body ...)
413 (define-as-needed proc (lambda* (args ...) body ...)))
415 (if (module-defined? the-scm-module 'variable)
416 (module-re-export! (current-module) '(variable))
418 (module-define! (current-module) 'variable value)
419 (module-export! (current-module) '(variable)))))))
426 (define (augment-mtab source target type options)
427 "Augment /etc/mtab with information about the given mount point."
428 (let ((port (open-file "/etc/mtab" "a")))
429 (format port "~a ~a ~a ~a 0 0~%"
430 source target type (or options "rw"))
433 (define (read-mtab port)
434 "Read an mtab-formatted file from PORT, returning a list of tuples."
435 (let loop ((result '()))
436 (let ((line (read-line port)))
437 (if (eof-object? line)
439 (loop (cons (string-tokenize line) result))))))
441 (define (remove-from-mtab target)
442 "Remove mount point TARGET from /etc/mtab."
444 (remove (match-lambda
445 ((device mount-point type options freq passno)
446 (string=? target mount-point))
448 (call-with-input-file "/etc/mtab" read-mtab)))
450 (call-with-output-file "/etc/mtab"
452 (for-each (match-lambda
453 ((device mount-point type options freq passno)
454 (format port "~a ~a ~a ~a ~a ~a~%"
455 device mount-point type options freq passno)))
458 ;; Linux mount flags, from libc's <sys/mount.h>.
463 (define MS_REMOUNT 32)
464 (define MS_NOATIME 1024)
465 (define MS_BIND 4096)
466 (define MS_MOVE 8192)
467 (define MS_STRICTATIME 16777216)
468 (define MS_LAZYTIME 33554432)
471 (define MNT_DETACH 2)
472 (define MNT_EXPIRE 4)
473 (define UMOUNT_NOFOLLOW 8)
475 (define-as-needed (mount source target type
476 #:optional (flags 0) options
477 #:key (update-mtab? #f))
478 "Mount device SOURCE on TARGET as a file system TYPE.
479 Optionally, FLAGS may be a bitwise-or of the MS_* <sys/mount.h>
480 constants, and OPTIONS may be a string. When FLAGS contains
481 MS_REMOUNT, SOURCE and TYPE are ignored. When UPDATE-MTAB? is true,
482 update /etc/mtab. Raise a 'system-error' exception on error."
483 ;; XXX: '#:update-mtab?' is not implemented by core 'mount'.
484 (let ((proc (syscall->procedure int "mount" `(* * * ,unsigned-long *))))
485 (let-values (((ret err)
487 (string->pointer source)
489 (string->pointer target)
491 (string->pointer type)
495 (string->pointer options)
498 (throw 'system-error "mount" "mount ~S on ~S: ~A"
499 (list source target (strerror err))
502 (augment-mtab source target type options)))))
504 (define-as-needed (umount target
506 #:key (update-mtab? #f))
507 "Unmount TARGET. Optionally FLAGS may be one of the MNT_* or UMOUNT_*
508 constants from <sys/mount.h>."
509 ;; XXX: '#:update-mtab?' is not implemented by core 'umount'.
510 (let ((proc (syscall->procedure int "umount2" `(* ,int))))
511 (let-values (((ret err)
512 (proc (string->pointer target) flags)))
514 (throw 'system-error "umount" "~S: ~A"
515 (list target (strerror err))
518 (remove-from-mtab target)))))
520 (define (mount-points)
521 "Return the mounts points for currently mounted file systems."
522 (call-with-input-file "/proc/mounts"
524 (let loop ((result '()))
525 (let ((line (read-line port)))
526 (if (eof-object? line)
528 (match (string-tokenize line)
529 ((source mount-point _ ...)
530 (loop (cons mount-point result))))))))))
533 (let ((proc (syscall->procedure int "swapon" (list '* int))))
534 (lambda* (device #:optional (flags 0))
535 "Use the block special device at DEVICE for swapping."
536 (let-values (((ret err)
537 (proc (string->pointer device) flags)))
539 (throw 'system-error "swapon" "~S: ~A"
540 (list device (strerror err))
544 (let ((proc (syscall->procedure int "swapoff" '(*))))
546 "Stop using block special device DEVICE for swapping."
547 (let-values (((ret err) (proc (string->pointer device))))
549 (throw 'system-error "swapoff" "~S: ~A"
550 (list device (strerror err))
553 (define-as-needed RB_AUTOBOOT #x01234567)
554 (define-as-needed RB_HALT_SYSTEM #xcdef0123)
555 (define-as-needed RB_ENABLED_CAD #x89abcdef)
556 (define-as-needed RB_DISABLE_CAD 0)
557 (define-as-needed RB_POWER_OFF #x4321fedc)
558 (define-as-needed RB_SW_SUSPEND #xd000fce2)
559 (define-as-needed RB_KEXEC #x45584543)
561 (define-as-needed (reboot #:optional (cmd RB_AUTOBOOT))
562 (let ((proc (syscall->procedure int "reboot" (list int))))
563 (let-values (((ret err) (proc cmd)))
565 (throw 'system-error "reboot" "~S: ~A"
566 (list cmd (strerror err))
569 (define-as-needed (load-linux-module data #:optional (options ""))
570 (let ((proc (syscall->procedure int "init_module"
571 (list '* unsigned-long '*))))
572 (let-values (((ret err)
573 (proc (bytevector->pointer data)
574 (bytevector-length data)
575 (string->pointer options))))
577 (throw 'system-error "load-linux-module" "~A"
578 (list (strerror err))
581 (define (kernel? pid)
582 "Return #t if PID designates a \"kernel thread\" rather than a normal
584 (let ((stat (call-with-input-file (format #f "/proc/~a/stat" pid)
585 (compose string-tokenize read-string))))
586 ;; See proc.txt in Linux's documentation for the list of fields.
588 ((pid tcomm state ppid pgrp sid tty_nr tty_pgrp flags min_flt
589 cmin_flt maj_flt cmaj_flt utime stime cutime cstime
590 priority nice num_thread it_real_value start_time
592 (= string->number start_code) (= string->number end_code) _ ...)
593 ;; Got this obscure trick from sysvinit's 'killall5' program.
594 (and (zero? start_code) (zero? end_code))))))
597 "Return the list of live processes."
598 (sort (filter-map (lambda (file)
599 (let ((pid (string->number file)))
607 (let ((proc (syscall->procedure '* "mkdtemp" '(*))))
609 "Create a new unique directory in the file system using the template
610 string TMPL and return its file name. TMPL must end with 'XXXXXX'."
611 (let-values (((result err) (proc (string->pointer tmpl))))
612 (when (null-pointer? result)
613 (throw 'system-error "mkdtemp!" "~S: ~A"
614 (list tmpl (strerror err))
616 (pointer->string result)))))
619 (let ((proc (syscall->procedure int "fdatasync" (list int))))
621 "Flush buffered output of PORT, an output file port, and then call
622 fdatasync(2) on the underlying file descriptor."
624 (let*-values (((fd) (fileno port))
625 ((ret err) (proc fd)))
627 (throw 'system-error "fdatasync" "~S: ~A"
628 (list fd (strerror err))
632 (define-record-type <file-system>
633 (file-system type block-size blocks blocks-free
634 blocks-available files free-files identifier
635 name-length fragment-size mount-flags spare)
637 (type file-system-type)
638 (block-size file-system-block-size)
639 (blocks file-system-block-count)
640 (blocks-free file-system-blocks-free)
641 (blocks-available file-system-blocks-available)
642 (files file-system-file-count)
643 (free-files file-system-free-file-nodes)
644 (identifier file-system-identifier)
645 (name-length file-system-maximum-name-length)
646 (fragment-size file-system-fragment-size)
647 (mount-flags file-system-mount-flags)
648 (spare file-system--spare))
650 (define-syntax fsword ;fsword_t
651 (identifier-syntax long))
653 (define-c-struct %statfs ;<bits/statfs.h>
654 sizeof-statfs ;slightly overestimated
662 (blocks-available uint64)
665 (identifier (array int 2))
667 (fragment-size fsword)
669 (spare (array fsword 4)))
672 (let ((proc (syscall->procedure int "statfs64" '(* *))))
674 "Return a <file-system> data structure describing the file system
676 (let*-values (((stat) (make-bytevector sizeof-statfs))
677 ((ret err) (proc (string->pointer file)
678 (bytevector->pointer stat))))
681 (throw 'system-error "statfs" "~A: ~A"
682 (list file (strerror err))
685 (define (free-disk-space file)
686 "Return the free disk space, in bytes, on the file system that hosts FILE."
687 (let ((fs (statfs file)))
688 (* (file-system-block-size fs)
689 (file-system-blocks-available fs))))
691 ;; Flags for the *at command, notably the 'utime' procedure of libguile.
693 (define-as-needed AT_FDCWD -100)
694 (define-as-needed AT_SYMLINK_NOFOLLOW #x100)
695 (define-as-needed AT_REMOVEDIR #x200)
696 (define-as-needed AT_SYMLINK_FOLLOW #x400)
697 (define-as-needed AT_NO_AUTOMOUNT #x800)
698 (define-as-needed AT_EMPTY_PATH #x1000)
700 (define-syntax BLKRRPART ;<sys/mount.h>
701 (identifier-syntax #x125F))
703 (define* (device-in-use? device)
704 "Return #t if the block DEVICE is in use, #f otherwise. This is inspired
705 from fdisk_device_is_used function of util-linux. This is particularly useful
706 for devices that do not appear in /proc/self/mounts like overlayfs lowerdir
708 (let*-values (((fd) (open-fdes device O_RDONLY))
709 ((ret err) (%ioctl fd BLKRRPART %null-pointer)))
717 ;; We get EINVAL for devices that have the GENHD_FL_NO_PART_SCAN flag
718 ;; set in the kernel, in particular loopback devices, though we do seem
719 ;; to get it for SCSI storage (/dev/sr0) on QEMU.
722 (throw 'system-error "ioctl" "~A"
723 (list (strerror err))
731 ;; From <uapi/linux/random.h>.
732 (define RNDADDTOENTCNT #x40045201)
734 (define (add-to-entropy-count port-or-fd n)
735 "Add N to the kernel's entropy count (the value that can be read from
736 /proc/sys/kernel/random/entropy_avail). PORT-OR-FD must correspond to
737 /dev/urandom or /dev/random. Raise to 'system-error with EPERM when the
738 caller lacks root privileges."
739 (let ((fd (if (port? port-or-fd)
742 (box (make-bytevector (sizeof int))))
743 (bytevector-sint-set! box 0 n (native-endianness)
745 (let-values (((ret err)
746 (%ioctl fd RNDADDTOENTCNT
747 (bytevector->pointer box))))
749 (throw 'system-error "add-to-entropy-count" "~A"
750 (list (strerror err))
758 ;; Linux clone flags, from linux/sched.h
759 (define CLONE_CHILD_CLEARTID #x00200000)
760 (define CLONE_CHILD_SETTID #x01000000)
761 (define CLONE_NEWNS #x00020000)
762 (define CLONE_NEWUTS #x04000000)
763 (define CLONE_NEWIPC #x08000000)
764 (define CLONE_NEWUSER #x10000000)
765 (define CLONE_NEWPID #x20000000)
766 (define CLONE_NEWNET #x40000000)
768 (define %set-automatic-finalization-enabled?!
769 ;; When using a statically-linked Guile, for instance in the initrd, we
770 ;; cannot resolve this symbol, but most of the time we don't need it
771 ;; anyway. Thus, delay it.
773 (pointer->procedure int
775 "scm_set_automatic_finalization_enabled"
779 "Switch on or off automatic finalization in a separate thread.
780 Turning finalization off shuts down the finalization thread as a side effect."
781 (->bool ((force proc) (if enabled? 1 0))))))
783 (define-syntax-rule (without-automatic-finalization exp)
784 "Turn off automatic finalization within the dynamic extent of EXP."
788 (set! enabled? (%set-automatic-finalization-enabled?! #f)))
792 (%set-automatic-finalization-enabled?! enabled?)))))
794 ;; The libc interface to sys_clone is not useful for Scheme programs, so the
795 ;; low-level system call is wrapped instead. The 'syscall' function is
796 ;; declared in <unistd.h> as a variadic function; in practice, it expects 6
797 ;; pointer-sized arguments, as shown in, e.g., x86_64/syscall.S.
799 (let* ((proc (syscall->procedure int "syscall"
804 ;; TODO: Don't do this.
805 (syscall-id (match (utsname:machine (uname))
813 "Create a new child process by duplicating the current parent process.
814 Unlike the fork system call, clone accepts FLAGS that specify which resources
815 are shared between the parent and child processes."
816 (let-values (((ret err)
817 ;; Guile 2.2 runs a finalization thread. 'primitive-fork'
818 ;; takes care of shutting it down before forking, and we
819 ;; must do the same here. Failing to do that, if the
820 ;; child process calls 'primitive-fork', it will hang
821 ;; while trying to pthread_join the finalization thread
822 ;; since that thread does not exist.
823 (without-automatic-finalization
824 (proc syscall-id flags
825 %null-pointer ;child stack
826 %null-pointer %null-pointer ;ptid & ctid
827 %null-pointer)))) ;unused
829 (throw 'system-error "clone" "~d: ~A"
830 (list flags (strerror err))
835 ;; Some systems may be using an old (pre-2.14) version of glibc where there
836 ;; is no 'setns' function available.
838 (let ((proc (syscall->procedure int "setns" (list int int))))
839 (lambda (fdes nstype)
840 "Reassociate the current process with the namespace specified by FDES, a
841 file descriptor obtained by opening a /proc/PID/ns/* file. NSTYPE specifies
842 which type of namespace the current process may be reassociated with, or 0 if
843 there is no such limitation."
844 (let-values (((ret err) (proc fdes nstype)))
846 (throw 'system-error "setns" "~d ~d: ~A"
847 (list fdes nstype (strerror err))
851 (let ((proc (syscall->procedure int "pivot_root" (list '* '*))))
852 (lambda (new-root put-old)
853 "Change the root file system to NEW-ROOT and move the current root file
855 (let-values (((ret err)
856 (proc (string->pointer new-root)
857 (string->pointer put-old))))
859 (throw 'system-error "pivot_root" "~S ~S: ~A"
860 (list new-root put-old (strerror err))
868 (define (file-type->symbol type)
869 ;; Convert TYPE to symbols like 'stat:type' does.
870 (cond ((= type DT_REG) 'regular)
871 ((= type DT_LNK) 'symlink)
872 ((= type DT_DIR) 'directory)
873 ((= type DT_FIFO) 'fifo)
874 ((= type DT_CHR) 'char-special)
875 ((= type DT_BLK) 'block-special)
876 ((= type DT_SOCK) 'socket)
879 ;; 'struct dirent64' for GNU/Linux.
880 (define-c-struct %struct-dirent-header/linux
881 sizeof-dirent-header/linux
882 (lambda (inode offset length type name)
883 `((type . ,(file-type->symbol type))
885 read-dirent-header/linux
886 write-dirent-header!/linux
889 (length unsigned-short)
891 (name uint8)) ;first byte of 'd_name'
893 ;; 'struct dirent64' for GNU/Hurd.
894 (define-c-struct %struct-dirent-header/hurd
895 sizeof-dirent-header/hurd
896 (lambda (inode length type name-length name)
897 `((type . ,(file-type->symbol type))
899 read-dirent-header/hurd
900 write-dirent-header!/hurd
902 (length unsigned-short)
907 ;; Constants for the 'type' field, from <dirent.h>.
908 (define DT_UNKNOWN 0)
918 (define string->pointer/utf-8
919 (cut string->pointer <> "UTF-8"))
921 (define pointer->string/utf-8
922 (cut pointer->string <> <> "UTF-8"))
925 (let ((proc (syscall->procedure '* "opendir" '(*))))
926 (lambda* (name #:optional (string->pointer string->pointer/utf-8))
927 (let-values (((ptr err)
928 (proc (string->pointer name))))
929 (if (null-pointer? ptr)
930 (throw 'system-error "opendir*"
931 "~A: ~A" (list name (strerror err))
936 (let ((proc (syscall->procedure int "closedir" '(*))))
938 (let-values (((ret err)
941 (throw 'system-error "closedir"
942 "closedir: ~A" (list (strerror err))
945 (define (readdir-procedure name-field-offset sizeof-dirent-header
947 (let ((proc (syscall->procedure '* "readdir64" '(*))))
948 (lambda* (directory #:optional (pointer->string pointer->string/utf-8))
949 (let ((ptr (proc directory)))
950 (and (not (null-pointer? ptr))
951 (cons (pointer->string
952 (make-pointer (+ (pointer-address ptr) name-field-offset))
955 (pointer->bytevector ptr sizeof-dirent-header))))))))
958 ;; Decide at run time which one must be used.
959 (if (string-contains %host-type "linux-gnu")
960 (readdir-procedure (c-struct-field-offset %struct-dirent-header/linux
962 sizeof-dirent-header/linux
963 read-dirent-header/linux)
964 (readdir-procedure (c-struct-field-offset %struct-dirent-header/hurd
966 sizeof-dirent-header/hurd
967 read-dirent-header/hurd)))
969 (define* (scandir* name #:optional
971 (entry<? (lambda (entry1 entry2)
976 (string<? name1 name2)))))))
978 (string->pointer string->pointer/utf-8)
979 (pointer->string pointer->string/utf-8))
980 "This procedure improves on Guile's 'scandir' procedure in several ways:
982 1. Systematically encode decode file names using STRING->POINTER and
983 POINTER->STRING (UTF-8 by default; this works around a defect in Guile 2.0/2.2
984 where 'scandir' decodes file names according to the current locale, which is
985 not always desirable.
987 2. Each entry that is returned has the form (NAME . PROPERTIES).
988 PROPERTIES is an alist showing additional properties about the entry, as
989 found in 'struct dirent'. An entry may look like this:
991 (\"foo.scm\" (type . regular) (inode . 123456))
993 Callers must be prepared to deal with the case where 'type' is 'unknown'
994 since some file systems do not provide that information.
996 3. Raise to 'system-error' when NAME cannot be opened."
997 (let ((directory (opendir* name string->pointer)))
1001 (let loop ((result '()))
1002 (match (readdir* directory pointer->string)
1004 (sort result entry<?))
1006 (loop (if (select? entry)
1010 (closedir* directory)))))
1014 ;;; Advisory file locking.
1017 (define-c-struct %struct-flock ;<fcntl.h>
1029 ;; On Linux-based systems, this is usually 7, but not always
1030 ;; (exceptions include SPARC.) On GNU/Hurd, it's 9.
1031 (cond ((string-contains %host-type "sparc") 9) ; sparc-*-linux-gnu
1032 ((string-contains %host-type "linux") 7) ; *-linux-gnu
1036 ;; Likewise: GNU/Hurd and SPARC use 8, while the others typically use 6.
1037 (cond ((string-contains %host-type "sparc") 8) ; sparc-*-linux-gnu
1038 ((string-contains %host-type "linux") 6) ; *-linux-gnu
1042 ;; The F_RDLCK, F_WRLCK, and F_UNLCK constants.
1043 (cond ((string-contains %host-type "sparc") #(1 2 3)) ; sparc-*-linux-gnu
1044 ((string-contains %host-type "hppa") #(1 2 3)) ; hppa-*-linux-gnu
1045 ((string-contains %host-type "linux") #(0 1 2)) ; *-linux-gnu
1046 (else #(1 2 3)))) ; *-gnu*
1049 (let ((proc (syscall->procedure int "fcntl" `(,int ,int *))))
1050 (lambda* (fd-or-port operation #:key (wait? #t))
1051 "Perform locking OPERATION on the file beneath FD-OR-PORT. OPERATION
1052 must be a symbol, one of 'read-lock, 'write-lock, or 'unlock. When WAIT? is
1053 true, block until the lock is acquired; otherwise, thrown an 'flock-error'
1054 exception if it's already taken."
1055 (define (operation->int op)
1057 ((read-lock) (vector-ref F_xxLCK 0))
1058 ((write-lock) (vector-ref F_xxLCK 1))
1059 ((unlock) (vector-ref F_xxLCK 2))
1060 (else (error "invalid fcntl-flock operation" op))))
1063 (if (port? fd-or-port)
1068 (make-bytevector sizeof-flock))
1071 (operation->int operation) SEEK_SET
1075 ;; XXX: 'fcntl' is a vararg function, but here we happily use the
1076 ;; standard ABI; crossing fingers.
1077 (let-values (((ret err)
1080 F_SETLKW ;lock & wait
1081 F_SETLK) ;non-blocking attempt
1082 (bytevector->pointer bv))))
1084 ;; Presumably we got EAGAIN or so.
1085 (throw 'flock-error err))))))
1087 (define* (lock-file file #:key (wait? #t))
1088 "Wait and acquire an exclusive lock on FILE. Return an open port."
1089 (let ((port (open-file file "w0")))
1090 (fcntl-flock port 'write-lock #:wait? wait?)
1093 (define (unlock-file port)
1094 "Unlock PORT, a port returned by 'lock-file'."
1095 (fcntl-flock port 'unlock)
1099 (define (call-with-file-lock file thunk)
1104 (catch 'system-error
1108 ;; When using the statically-linked Guile in the initrd,
1109 ;; 'fcntl-flock' returns ENOSYS unconditionally. Ignore
1110 ;; that error since we're typically the only process running
1112 (if (= ENOSYS (system-error-errno args))
1114 (apply throw args))))))
1118 (unlock-file port))))))
1120 (define (call-with-file-lock/no-wait file thunk handler)
1127 (lock-file file #:wait? #f))
1128 (lambda (key . args)
1131 (apply handler args)
1132 ;; No open port to the lock, so return #f.
1135 ;; When using the statically-linked Guile in the initrd,
1136 ;; 'fcntl-flock' returns ENOSYS unconditionally. Ignore
1137 ;; that error since we're typically the only process running
1139 (if (= ENOSYS (system-error-errno (cons key args)))
1141 (apply throw key args)))
1142 (_ (apply throw key args)))))))
1146 (unlock-file port))))))
1148 (define-syntax-rule (with-file-lock file exp ...)
1149 "Wait to acquire a lock on FILE and evaluate EXP in that context."
1150 (call-with-file-lock file (lambda () exp ...)))
1152 (define-syntax-rule (with-file-lock/no-wait file handler exp ...)
1153 "Try to acquire a lock on FILE and evaluate EXP in that context. Execute
1154 handler if the lock is already held by another process."
1155 (call-with-file-lock/no-wait file (lambda () exp ...) handler))
1159 ;;; Miscellaneous, aka. 'prctl'.
1163 ;; Should it win the API contest against 'ioctl'? You tell us!
1164 (syscall->procedure int "prctl"
1165 (list int unsigned-long unsigned-long
1166 unsigned-long unsigned-long)))
1168 (define PR_SET_NAME 15) ;<linux/prctl.h>
1169 (define PR_GET_NAME 16)
1171 (define %max-thread-name-length
1172 ;; Maximum length in bytes of the process name, including the terminating
1176 (define (set-thread-name name)
1177 "Set the name of the calling thread to NAME. NAME is truncated to 15
1179 (let ((ptr (string->pointer name)))
1180 (let-values (((ret err)
1182 (pointer-address ptr) 0 0 0)))
1184 (throw 'set-process-name "set-process-name"
1185 "set-process-name: ~A"
1186 (list (strerror err))
1189 (define (thread-name)
1190 "Return the name of the calling thread as a string."
1191 (let ((buf (make-bytevector %max-thread-name-length)))
1192 (let-values (((ret err)
1194 (pointer-address (bytevector->pointer buf))
1197 (bytes->string (bytevector->u8-list buf))
1198 (throw 'process-name "process-name"
1200 (list (strerror err))
1205 ;;; Network interfaces.
1208 (define SIOCGIFCONF ;from <bits/ioctls.h>
1211 (if (string-contains %host-type "linux")
1213 #xf00801a4)) ;GNU/Hurd
1214 (define SIOCGIFFLAGS
1215 (if (string-contains %host-type "linux")
1217 #xc4804191)) ;GNU/Hurd
1218 (define SIOCSIFFLAGS
1219 (if (string-contains %host-type "linux")
1221 #x84804190)) ;GNU/Hurd
1223 (if (string-contains %host-type "linux")
1225 #xc08401a1)) ;GNU/Hurd
1227 (if (string-contains %host-type "linux")
1229 #x8084018c)) ;GNU/Hurd
1230 (define SIOCGIFNETMASK
1231 (if (string-contains %host-type "linux")
1233 #xc08401a5)) ;GNU/Hurd
1234 (define SIOCSIFNETMASK
1235 (if (string-contains %host-type "linux")
1237 #x80840196)) ;GNU/Hurd
1239 (if (string-contains %host-type "linux")
1241 -1)) ;FIXME: GNU/Hurd?
1243 (if (string-contains %host-type "linux")
1245 -1)) ;FIXME: GNU/Hurd?
1247 ;; Flags and constants from <net/if.h>.
1249 (define-as-needed IFF_UP #x1) ;Interface is up
1250 (define-as-needed IFF_BROADCAST #x2) ;Broadcast address valid.
1251 (define-as-needed IFF_LOOPBACK #x8) ;Is a loopback net.
1252 (define-as-needed IFF_RUNNING #x40) ;interface RFC2863 OPER_UP
1253 (define-as-needed IFF_NOARP #x80) ;ARP disabled or unsupported
1255 (define IF_NAMESIZE 16) ;maximum interface name size
1257 (define-c-struct %ifconf-struct
1262 (length int) ;int ifc_len
1263 (request '*)) ;struct ifreq *ifc_ifcu
1265 (define ifreq-struct-size
1266 ;; 'struct ifreq' begins with an array of IF_NAMESIZE bytes containing the
1267 ;; interface name (nul-terminated), followed by a bunch of stuff. This is
1268 ;; its size in bytes.
1269 (if (= 8 (sizeof '*))
1273 (define-c-struct sockaddr-in ;<linux/in.h>
1275 (lambda (family port address)
1276 (make-socket-address family address port))
1279 (family unsigned-short)
1280 (port (int16 ~ big))
1281 (address (int32 ~ big)))
1283 (define-c-struct sockaddr-in6 ;<linux/in6.h>
1285 (lambda (family port flowinfo address scopeid)
1286 (make-socket-address family address port flowinfo scopeid))
1289 (family unsigned-short)
1290 (port (int16 ~ big))
1291 (flowinfo (int32 ~ big))
1292 (address (int128 ~ big))
1295 (define (write-socket-address! sockaddr bv index)
1296 "Write SOCKADDR, a socket address as returned by 'make-socket-address', to
1297 bytevector BV at INDEX."
1298 (let ((family (sockaddr:fam sockaddr)))
1299 (cond ((= family AF_INET)
1300 (write-sockaddr-in! bv index
1302 (sockaddr:port sockaddr)
1303 (sockaddr:addr sockaddr)))
1304 ((= family AF_INET6)
1305 (write-sockaddr-in6! bv index
1307 (sockaddr:port sockaddr)
1308 (sockaddr:flowinfo sockaddr)
1309 (sockaddr:addr sockaddr)
1310 (sockaddr:scopeid sockaddr)))
1312 (error "unsupported socket address" sockaddr)))))
1314 (define PF_PACKET 17) ;<bits/socket.h>
1315 (define AF_PACKET PF_PACKET)
1317 (define* (read-socket-address bv #:optional (index 0))
1318 "Read a socket address from bytevector BV at INDEX."
1319 (let ((family (bytevector-u16-native-ref bv index)))
1320 (cond ((= family AF_INET)
1321 (read-sockaddr-in bv index))
1322 ((= family AF_INET6)
1323 (read-sockaddr-in6 bv index))
1325 ;; XXX: Unsupported address family, such as AF_PACKET. Return a
1326 ;; vector such that the vector can at least call 'sockaddr:fam'.
1330 ;; The most terrible interface, live from Scheme.
1331 (syscall->procedure int "ioctl" (list int unsigned-long '*)))
1333 (define (bytes->string bytes)
1334 "Read BYTES, a list of bytes, and return the null-terminated string decoded
1335 from there, or #f if that would be an empty string."
1336 (match (take-while (negate zero?) bytes)
1340 (list->string (map integer->char non-zero)))))
1342 (define (bytevector->string-list bv stride len)
1343 "Return the null-terminated strings found in BV every STRIDE bytes. Read at
1344 most LEN bytes from BV."
1345 (let loop ((bytes (take (bytevector->u8-list bv)
1346 (min len (bytevector-length bv))))
1352 (loop (drop bytes stride)
1353 (cons (bytes->string bytes) result))))))
1355 (define* (network-interface-names #:optional sock)
1356 "Return the names of existing network interfaces. This is typically limited
1357 to interfaces that are currently up."
1358 (let* ((close? (not sock))
1359 (sock (or sock (socket SOCK_STREAM AF_INET 0)))
1360 (len (* ifreq-struct-size 10))
1361 (reqs (make-bytevector len))
1362 (conf (make-bytevector sizeof-ifconf)))
1363 (write-ifconf! conf 0
1364 len (bytevector->pointer reqs))
1366 (let-values (((ret err)
1367 (%ioctl (fileno sock) SIOCGIFCONF
1368 (bytevector->pointer conf))))
1372 (bytevector->string-list reqs ifreq-struct-size
1373 (match (read-ifconf conf)
1375 (throw 'system-error "network-interface-list"
1376 "network-interface-list: ~A"
1377 (list (strerror err))
1380 (define %interface-line
1381 ;; Regexp matching an interface line in Linux's /proc/net/dev.
1382 (make-regexp "^[[:blank:]]*([[:graph:]]+):.*$"))
1384 (define (all-network-interface-names)
1385 "Return all the names of the registered network interfaces, including those
1387 (call-with-input-file "/proc/net/dev" ;XXX: Linux-specific
1389 (let loop ((interfaces '()))
1390 (let ((line (read-line port)))
1391 (cond ((eof-object? line)
1392 (reverse interfaces))
1393 ((regexp-exec %interface-line line)
1396 (loop (cons (match:substring match 1) interfaces))))
1398 (loop interfaces))))))))
1400 (define-as-needed (network-interface-flags socket name)
1401 "Return a number that is the bit-wise or of 'IFF*' flags for network
1403 (let ((req (make-bytevector ifreq-struct-size)))
1404 (bytevector-copy! (string->utf8 name) 0 req 0
1405 (min (string-length name) (- IF_NAMESIZE 1)))
1406 (let-values (((ret err)
1407 (%ioctl (fileno socket) SIOCGIFFLAGS
1408 (bytevector->pointer req))))
1411 ;; The 'ifr_flags' field is IF_NAMESIZE bytes after the
1412 ;; beginning of 'struct ifreq', and it's a short int.
1413 (bytevector-sint-ref req IF_NAMESIZE (native-endianness)
1416 (throw 'system-error "network-interface-flags"
1417 "network-interface-flags on ~A: ~A"
1418 (list name (strerror err))
1421 (define (loopback-network-interface? name)
1422 "Return true if NAME designates a loopback network interface."
1423 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1424 (flags (network-interface-flags sock name)))
1426 (not (zero? (logand flags IFF_LOOPBACK)))))
1428 (define (network-interface-running? name)
1429 "Return true if NAME designates a running network interface."
1430 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1431 (flags (network-interface-flags sock name)))
1433 (not (zero? (logand flags IFF_RUNNING)))))
1435 (define (arp-network-interface? name)
1436 "Return true if NAME supports the Address Resolution Protocol."
1437 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1438 (flags (network-interface-flags sock name)))
1440 (zero? (logand flags IFF_NOARP))))
1442 (define-as-needed (set-network-interface-flags socket name flags)
1443 "Set the flag of network interface NAME to FLAGS."
1444 (let ((req (make-bytevector ifreq-struct-size)))
1445 (bytevector-copy! (string->utf8 name) 0 req 0
1446 (min (string-length name) (- IF_NAMESIZE 1)))
1447 ;; Set the 'ifr_flags' field.
1448 (bytevector-uint-set! req IF_NAMESIZE flags (native-endianness)
1450 (let-values (((ret err)
1451 (%ioctl (fileno socket) SIOCSIFFLAGS
1452 (bytevector->pointer req))))
1454 (throw 'system-error "set-network-interface-flags"
1455 "set-network-interface-flags on ~A: ~A"
1456 (list name (strerror err))
1459 (define-as-needed (set-network-interface-address socket name sockaddr)
1460 "Set the address of network interface NAME to SOCKADDR."
1461 (let ((req (make-bytevector ifreq-struct-size)))
1462 (bytevector-copy! (string->utf8 name) 0 req 0
1463 (min (string-length name) (- IF_NAMESIZE 1)))
1464 ;; Set the 'ifr_addr' field.
1465 (write-socket-address! sockaddr req IF_NAMESIZE)
1466 (let-values (((ret err)
1467 (%ioctl (fileno socket) SIOCSIFADDR
1468 (bytevector->pointer req))))
1470 (throw 'system-error "set-network-interface-address"
1471 "set-network-interface-address on ~A: ~A"
1472 (list name (strerror err))
1475 (define (set-network-interface-netmask socket name sockaddr)
1476 "Set the network mask of interface NAME to SOCKADDR."
1477 (let ((req (make-bytevector ifreq-struct-size)))
1478 (bytevector-copy! (string->utf8 name) 0 req 0
1479 (min (string-length name) (- IF_NAMESIZE 1)))
1480 ;; Set the 'ifr_addr' field.
1481 (write-socket-address! sockaddr req IF_NAMESIZE)
1482 (let-values (((ret err)
1483 (%ioctl (fileno socket) SIOCSIFNETMASK
1484 (bytevector->pointer req))))
1486 (throw 'system-error "set-network-interface-netmask"
1487 "set-network-interface-netmask on ~A: ~A"
1488 (list name (strerror err))
1491 (define (network-interface-address socket name)
1492 "Return the address of network interface NAME. The result is an object of
1493 the same type as that returned by 'make-socket-address'."
1494 (let ((req (make-bytevector ifreq-struct-size)))
1495 (bytevector-copy! (string->utf8 name) 0 req 0
1496 (min (string-length name) (- IF_NAMESIZE 1)))
1497 (let-values (((ret err)
1498 (%ioctl (fileno socket) SIOCGIFADDR
1499 (bytevector->pointer req))))
1501 (read-socket-address req IF_NAMESIZE)
1502 (throw 'system-error "network-interface-address"
1503 "network-interface-address on ~A: ~A"
1504 (list name (strerror err))
1507 (define (network-interface-netmask socket name)
1508 "Return the netmask of network interface NAME. The result is an object of
1509 the same type as that returned by 'make-socket-address'."
1510 (let ((req (make-bytevector ifreq-struct-size)))
1511 (bytevector-copy! (string->utf8 name) 0 req 0
1512 (min (string-length name) (- IF_NAMESIZE 1)))
1513 (let-values (((ret err)
1514 (%ioctl (fileno socket) SIOCGIFNETMASK
1515 (bytevector->pointer req))))
1517 (read-socket-address req IF_NAMESIZE)
1518 (throw 'system-error "network-interface-netmask"
1519 "network-interface-netmask on ~A: ~A"
1520 (list name (strerror err))
1523 (define* (configure-network-interface name sockaddr flags
1525 "Configure network interface NAME to use SOCKADDR, an address as returned by
1526 'make-socket-address', and FLAGS, a bitwise-or of IFF_* constants. If NETMASK
1527 is true, it must be a socket address to use as the network mask."
1528 (let ((sock (socket (sockaddr:fam sockaddr) SOCK_STREAM 0)))
1532 (set-network-interface-address sock name sockaddr)
1533 (set-network-interface-flags sock name flags)
1535 (set-network-interface-netmask sock name netmask)))
1537 (close-port sock)))))
1539 (define* (set-network-interface-up name
1540 #:key (family AF_INET))
1541 "Turn up the interface NAME."
1542 (let ((sock (socket family SOCK_STREAM 0)))
1546 (let ((flags (network-interface-flags sock name)))
1547 (set-network-interface-flags sock name
1548 (logior flags IFF_UP))))
1550 (close-port sock)))))
1557 (define-c-struct %rtentry ;'struct rtentry' from <net/route.h>
1562 (pad1 unsigned-long)
1563 (destination (array uint8 16)) ;struct sockaddr
1564 (gateway (array uint8 16)) ;struct sockaddr
1565 (genmask (array uint8 16)) ;struct sockaddr
1566 (flags unsigned-short)
1571 (pad4 (array uint8 (if (= 8 (sizeof* '*)) 3 1)))
1575 (window unsigned-long)
1576 (initial-rtt unsigned-short))
1578 (define RTF_UP #x0001) ;'rtentry' flags from <net/route.h>
1579 (define RTF_GATEWAY #x0002)
1581 (define %sockaddr-any
1582 (make-socket-address AF_INET INADDR_ANY 0))
1584 (define add-network-route/gateway
1585 ;; To allow field names to be matched as literals, we need to move them out
1586 ;; of the lambda's body since the parameters have the same name. A lot of
1587 ;; fuss for very little.
1588 (let-syntax ((gateway-offset (identifier-syntax
1589 (c-struct-field-offset %rtentry gateway)))
1590 (destination-offset (identifier-syntax
1591 (c-struct-field-offset %rtentry destination)))
1592 (genmask-offset (identifier-syntax
1593 (c-struct-field-offset %rtentry genmask))))
1594 (lambda* (socket gateway
1595 #:key (destination %sockaddr-any) (genmask %sockaddr-any))
1596 "Add a network route for DESTINATION (a socket address as returned by
1597 'make-socket-address') that goes through GATEWAY (a socket address). For
1600 (add-network-route/gateway sock
1601 (make-socket-address
1603 (inet-pton AF_INET \"192.168.0.1\")
1606 is equivalent to this 'net-tools' command:
1608 route add -net default gw 192.168.0.1
1610 because the default value of DESTINATION is \"0.0.0.0\"."
1611 (let ((route (make-bytevector sizeof-rtentry 0)))
1612 (write-socket-address! gateway route gateway-offset)
1613 (write-socket-address! destination route destination-offset)
1614 (write-socket-address! genmask route genmask-offset)
1615 (bytevector-u16-native-set! route
1616 (c-struct-field-offset %rtentry flags)
1617 (logior RTF_UP RTF_GATEWAY))
1618 (let-values (((ret err)
1619 (%ioctl (fileno socket) SIOCADDRT
1620 (bytevector->pointer route))))
1622 (throw 'system-error "add-network-route/gateway"
1623 "add-network-route/gateway: ~A"
1624 (list (strerror err))
1627 (define delete-network-route
1628 (let-syntax ((destination-offset (identifier-syntax
1629 (c-struct-field-offset %rtentry destination))))
1630 (lambda* (socket destination)
1631 "Delete the network route for DESTINATION. For instance, the call:
1633 (delete-network-route sock
1634 (make-socket-address AF_INET INADDR_ANY 0))
1636 is equivalent to the 'net-tools' command:
1638 route del -net default
1641 (let ((route (make-bytevector sizeof-rtentry 0)))
1642 (write-socket-address! destination route destination-offset)
1643 (let-values (((ret err)
1644 (%ioctl (fileno socket) SIOCDELRT
1645 (bytevector->pointer route))))
1647 (throw 'system-error "delete-network-route"
1648 "delete-network-route: ~A"
1649 (list (strerror err))
1654 ;;; Details about network interfaces---aka. 'getifaddrs'.
1657 ;; Network interfaces. XXX: We would call it <network-interface> but that
1658 ;; would collide with the ioctl wrappers above.
1659 (define-record-type <interface>
1660 (make-interface name flags address netmask broadcast-address)
1662 (name interface-name) ;string
1663 (flags interface-flags) ;or'd IFF_* values
1664 (address interface-address) ;sockaddr | #f
1665 (netmask interface-netmask) ;sockaddr | #f
1666 (broadcast-address interface-broadcast-address)) ;sockaddr | #f
1668 (define (write-interface interface port)
1670 (($ <interface> name flags address)
1671 (format port "#<interface ~s " name)
1672 (unless (zero? (logand IFF_UP flags))
1673 (display "up " port))
1675 ;; Check whether ADDRESS really is a sockaddr.
1677 (if (member (sockaddr:fam address) (list AF_INET AF_INET6))
1678 (format port "~a " (inet-ntop (sockaddr:fam address)
1679 (sockaddr:addr address)))
1680 (format port "family:~a " (sockaddr:fam address))))
1682 (format port "~a>" (number->string (object-address interface) 16)))))
1684 (set-record-type-printer! <interface> write-interface)
1686 (define (values->interface next name flags address netmask
1687 broadcast-address data)
1688 "Given the raw field values passed as arguments, return a pair whose car is
1689 an <interface> object, and whose cdr is the pointer NEXT."
1690 (define (maybe-socket-address pointer)
1691 (if (null-pointer? pointer)
1693 (read-socket-address (pointer->bytevector pointer 50)))) ;XXX: size
1695 (cons (make-interface (if (null-pointer? name)
1697 (pointer->string name))
1699 (maybe-socket-address address)
1700 (maybe-socket-address netmask)
1701 (maybe-socket-address broadcast-address)
1706 (define-c-struct ifaddrs ;<ifaddrs.h>
1713 (flags unsigned-int)
1719 (define (unfold-interface-list ptr)
1720 "Call 'read-ifaddrs' on PTR and all its 'next' fields, recursively, and
1721 return the list of resulting <interface> objects."
1722 (let loop ((ptr ptr)
1724 (if (null-pointer? ptr)
1726 (match (read-ifaddrs (pointer->bytevector ptr %sizeof-ifaddrs))
1728 (loop ptr (cons ifaddr result)))))))
1730 (define network-interfaces
1731 (let ((proc (syscall->procedure int "getifaddrs" (list '*))))
1733 "Return a list of <interface> objects, each denoting a configured
1734 network interface. This is implemented using the 'getifaddrs' libc function."
1735 (let*-values (((ptr)
1736 (bytevector->pointer (make-bytevector (sizeof* '*))))
1740 (let* ((ptr (dereference-pointer ptr))
1741 (result (unfold-interface-list ptr)))
1744 (throw 'system-error "network-interfaces" "~A"
1745 (list (strerror err))
1748 (define free-ifaddrs
1749 (syscall->procedure void "freeifaddrs" '(*)))
1756 (define-syntax bits->symbols-body
1760 ((_ bits (name names ...) (value values ...))
1761 (let ((result (bits->symbols-body bits (names ...) (values ...))))
1762 (if (zero? (logand bits value))
1764 (cons 'name result))))))
1766 (define-syntax define-bits
1767 (syntax-rules (define)
1768 "Define the given numerical constants under CONSTRUCTOR, such that
1769 (CONSTRUCTOR NAME) returns VALUE. Define BITS->SYMBOLS as a procedure that,
1770 given an integer, returns the list of names of the constants that are or'd."
1771 ((_ constructor bits->symbols (define names values) ...)
1773 (define-syntax constructor
1774 (syntax-rules (names ...)
1776 ((_ names) values) ...
1777 ((_ first rest (... ...))
1778 (logior (constructor first) rest (... ...)))))
1779 (define (bits->symbols bits)
1780 (bits->symbols-body bits (names ...) (values ...)))))))
1782 ;; 'local-flags' bits from <bits/termios.h>
1783 (define-bits local-flags
1784 local-flags->symbols
1785 (define ISIG #o0000001)
1786 (define ICANON #o0000002)
1787 (define XCASE #o0000004)
1788 (define ECHO #o0000010)
1789 (define ECHOE #o0000020)
1790 (define ECHOK #o0000040)
1791 (define ECHONL #o0000100)
1792 (define NOFLSH #o0000200)
1793 (define TOSTOP #o0000400)
1794 (define ECHOCTL #o0001000)
1795 (define ECHOPRT #o0002000)
1796 (define ECHOKE #o0004000)
1797 (define FLUSHO #o0010000)
1798 (define PENDIN #o0040000)
1799 (define IEXTEN #o0100000)
1800 (define EXTPROC #o0200000))
1802 (define-bits input-flags
1803 input-flags->symbols
1804 (define IGNBRK #o0000001)
1805 (define BRKINT #o0000002)
1806 (define IGNPAR #o0000004)
1807 (define PARMRK #o0000010)
1808 (define INPCK #o0000020)
1809 (define ISTRIP #o0000040)
1810 (define INLCR #o0000100)
1811 (define IGNCR #o0000200)
1812 (define ICRNL #o0000400)
1813 (define IUCLC #o0001000)
1814 (define IXON #o0002000)
1815 (define IXANY #o0004000)
1816 (define IXOFF #o0010000)
1817 (define IMAXBEL #o0020000)
1818 (define IUTF8 #o0040000))
1820 ;; "Actions" values for 'tcsetattr'.
1821 (define-bits tcsetattr-action
1822 %unused-tcsetattr-action->symbols
1824 (define TCSADRAIN 1)
1825 (define TCSAFLUSH 2))
1827 (define-record-type <termios>
1828 (termios input-flags output-flags control-flags local-flags
1829 line-discipline control-chars
1830 input-speed output-speed)
1832 (input-flags termios-input-flags)
1833 (output-flags termios-output-flags)
1834 (control-flags termios-control-flags)
1835 (local-flags termios-local-flags)
1836 (line-discipline termios-line-discipline)
1837 (control-chars termios-control-chars)
1838 (input-speed termios-input-speed)
1839 (output-speed termios-output-speed))
1841 (define-c-struct %termios ;<bits/termios.h>
1846 (input-flags unsigned-int)
1847 (output-flags unsigned-int)
1848 (control-flags unsigned-int)
1849 (local-flags unsigned-int)
1850 (line-discipline uint8)
1851 (control-chars (array uint8 32))
1852 (input-speed unsigned-int)
1853 (output-speed unsigned-int))
1856 (let ((proc (syscall->procedure int "tcgetattr" (list int '*))))
1858 "Return the <termios> structure for the tty at FD."
1859 (let*-values (((bv) (make-bytevector sizeof-termios))
1860 ((ret err) (proc fd (bytevector->pointer bv))))
1863 (throw 'system-error "tcgetattr" "~A"
1864 (list (strerror err))
1868 (let ((proc (syscall->procedure int "tcsetattr" (list int int '*))))
1869 (lambda (fd actions termios)
1870 "Use TERMIOS for the tty at FD. ACTIONS is one of of the values
1871 produced by 'tcsetattr-action'; see tcsetattr(3) for details."
1873 (make-bytevector sizeof-termios))
1875 (let-syntax ((match/write (syntax-rules ()
1878 (($ <termios> fields ...)
1879 (write-termios! bv 0 fields ...)))))))
1880 (match/write input-flags output-flags control-flags local-flags
1881 line-discipline control-chars input-speed output-speed))
1883 (let-values (((ret err) (proc fd actions (bytevector->pointer bv))))
1885 (throw 'system-error "tcgetattr" "~A"
1886 (list (strerror err))
1889 (define-syntax TIOCGWINSZ ;<asm-generic/ioctls.h>
1890 (identifier-syntax #x5413))
1892 (define-record-type <window-size>
1893 (window-size rows columns x-pixels y-pixels)
1895 (rows window-size-rows)
1896 (columns window-size-columns)
1897 (x-pixels window-size-x-pixels)
1898 (y-pixels window-size-y-pixels))
1900 (define-c-struct winsize ;<bits/ioctl-types.h>
1905 (rows unsigned-short)
1906 (columns unsigned-short)
1907 (x-pixels unsigned-short)
1908 (y-pixels unsigned-short))
1910 (define* (terminal-window-size #:optional (port (current-output-port)))
1911 "Return a <window-size> structure describing the terminal at PORT, or raise
1912 a 'system-error' if PORT is not backed by a terminal. This procedure
1913 corresponds to the TIOCGWINSZ ioctl."
1914 (let*-values (((size) (make-bytevector sizeof-winsize))
1915 ((ret err) (%ioctl (fileno port) TIOCGWINSZ
1916 (bytevector->pointer size))))
1919 (throw 'system-error "terminal-window-size" "~A"
1920 (list (strerror err))
1923 (define (terminal-dimension window-dimension port fall-back)
1924 "Return the terminal dimension defined by WINDOW-DIMENSION, one of
1925 'window-size-columns' or 'window-size-rows' for PORT. If PORT does not
1926 correspond to a terminal, return the value returned by FALL-BACK."
1927 (catch 'system-error
1929 (if (file-port? port)
1930 (match (window-dimension (terminal-window-size port))
1931 ;; Things like Emacs shell-mode return 0, which is unreasonable.
1936 (let ((errno (system-error-errno args)))
1937 ;; ENOTTY is what we're after but 2012-and-earlier Linux versions
1938 ;; would return EINVAL instead in some cases:
1939 ;; <https://bugs.ruby-lang.org/issues/10494>.
1940 ;; Furthermore, some FUSE file systems like unionfs return ENOSYS for
1942 (if (memv errno (list ENOTTY EINVAL ENOSYS))
1944 (apply throw args))))))
1946 (define* (terminal-columns #:optional (port (current-output-port)))
1947 "Return the best approximation of the number of columns of the terminal at
1948 PORT, trying to guess a reasonable value if all else fails. The result is
1949 always a positive integer."
1951 (match (and=> (getenv "COLUMNS") string->number)
1953 ((? number? columns)
1954 (if (> columns 0) columns 80))))
1956 (terminal-dimension window-size-columns port fall-back))
1958 (define* (terminal-rows #:optional (port (current-output-port)))
1959 "Return the best approximation of the number of rows of the terminal at
1960 PORT, trying to guess a reasonable value if all else fails. The result is
1961 always a positive integer."
1962 (terminal-dimension window-size-rows port (const 25)))
1969 (define-record-type <utmpx-entry>
1970 (utmpx type pid line id user host termination exit
1971 session time address)
1973 (type utmpx-login-type) ;login-type
1975 (line utmpx-line) ;device name
1977 (user utmpx-user) ;user name
1978 (host utmpx-host) ;host name | #f
1979 (termination utmpx-termination-status)
1980 (exit utmpx-exit-status)
1981 (session utmpx-session-id) ;session ID, for windowing
1982 (time utmpx-time) ;entry time
1983 (address utmpx-address))
1985 (define-c-struct %utmpx ;<utmpx.h>
1987 (lambda (type pid line id user host termination exit session
1988 seconds useconds address %reserved)
1990 (bytes->string line) id
1991 (bytes->string user)
1992 (bytes->string host) termination exit
1994 (make-time time-utc (* 1000 useconds) seconds)
2000 (line (array uint8 32))
2001 (id (array uint8 4))
2002 (user (array uint8 32))
2003 (host (array uint8 256))
2007 (time-seconds int32)
2008 (time-useconds int32)
2009 (address-v6 (array int32 4))
2010 (%reserved (array uint8 20)))
2012 (define-bits login-type
2013 %unused-login-type->symbols
2014 (define EMPTY 0) ;No valid user accounting information.
2015 (define RUN_LVL 1) ;The system's runlevel.
2016 (define BOOT_TIME 2) ;Time of system boot.
2017 (define NEW_TIME 3) ;Time after system clock changed.
2018 (define OLD_TIME 4) ;Time when system clock changed.
2020 (define INIT_PROCESS 5) ;Process spawned by the init process.
2021 (define LOGIN_PROCESS 6) ;Session leader of a logged in user.
2022 (define USER_PROCESS 7) ;Normal process.
2023 (define DEAD_PROCESS 8) ;Terminated process.
2025 (define ACCOUNTING 9)) ;System accounting.
2028 (let ((proc (syscall->procedure void "setutxent" '())))
2030 "Open the user accounting database."
2034 (let ((proc (syscall->procedure void "endutxent" '())))
2036 "Close the user accounting database."
2040 (let ((proc (syscall->procedure '* "getutxent" '())))
2042 "Return the next entry from the user accounting database."
2044 (if (null-pointer? ptr)
2046 (read-utmpx (pointer->bytevector ptr sizeof-utmpx)))))))
2048 (define (utmpx-entries)
2049 "Return the list of entries read from the user accounting database."
2051 (let loop ((entries '()))
2057 (loop (cons entry entries))))))
2059 (define (read-utmpx-from-port port)
2060 "Read a utmpx entry from PORT. Return either the EOF object or a utmpx
2062 (match (get-bytevector-n port sizeof-utmpx)
2063 ((? eof-object? eof)
2068 ;;; syscalls.scm ends here