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>
9 ;;; This file is part of GNU Guix.
11 ;;; GNU Guix is free software; you can redistribute it and/or modify it
12 ;;; under the terms of the GNU General Public License as published by
13 ;;; the Free Software Foundation; either version 3 of the License, or (at
14 ;;; your option) any later version.
16 ;;; GNU Guix is distributed in the hope that it will be useful, but
17 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;;; GNU General Public License for more details.
21 ;;; You should have received a copy of the GNU General Public License
22 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
24 (define-module (guix build syscalls)
25 #:use-module (system foreign)
26 #:use-module (system base target)
27 #:use-module (rnrs bytevectors)
28 #:autoload (ice-9 binary-ports) (get-bytevector-n)
29 #:use-module (srfi srfi-1)
30 #:use-module (srfi srfi-9)
31 #:use-module (srfi srfi-9 gnu)
32 #:use-module (srfi srfi-11)
33 #:use-module (srfi srfi-19)
34 #:use-module (srfi srfi-26)
35 #:use-module (ice-9 rdelim)
36 #:use-module (ice-9 regex)
37 #:use-module (ice-9 match)
38 #:use-module (ice-9 ftw)
61 file-system-block-size
62 file-system-block-count
63 file-system-blocks-free
64 file-system-blocks-available
65 file-system-file-count
66 file-system-free-file-nodes
67 file-system-identifier
68 file-system-maximum-name-length
69 file-system-fragment-size
70 file-system-mount-flags
86 with-file-lock/no-wait
104 all-network-interface-names
105 network-interface-names
106 network-interface-netmask
107 network-interface-running?
108 loopback-network-interface?
109 arp-network-interface?
110 network-interface-address
111 set-network-interface-netmask
112 set-network-interface-up
113 configure-network-interface
114 add-network-route/gateway
122 interface-broadcast-address
128 termios-control-flags
130 termios-line-discipline
131 termios-control-chars
156 utmpx-termination-status
163 (read-utmpx-from-port . read-utmpx)))
167 ;;; This module provides bindings to libc's syscall wrappers. It uses the
168 ;;; FFI, and thus requires a dynamically-linked Guile.
170 ;;; Some syscalls are already defined in statically-linked Guile by applying
171 ;;; 'guile-linux-syscalls.patch'.
173 ;;; Visibility of syscall's symbols shared between this module and static Guile
174 ;;; is a bit delicate. It is handled by 'define-as-needed' macro.
176 ;;; This macro is used to export symbols in dynamic Guile context, and to
177 ;;; re-export them in static Guile context.
179 ;;; This way, even if they don't appear in #:export list, it is safe to use
180 ;;; syscalls from this module in static or dynamic Guile context.
186 ;;; Packed structures.
189 (define-syntax sizeof*
190 ;; XXX: This duplicates 'compile-time-value'.
191 (syntax-rules (int128 array)
195 (* (sizeof* type) n))
197 (let-syntax ((v (lambda (s)
198 ;; When compiling natively, call 'sizeof' at expansion
199 ;; time; otherwise, emit code to call it at run time.
202 (if (= (target-word-size)
203 (with-target %host-type target-word-size))
205 #'(sizeof type)))))))
208 (define-syntax alignof*
209 ;; XXX: This duplicates 'compile-time-value'.
210 (syntax-rules (int128 array)
216 (let-syntax ((v (lambda (s)
217 ;; When compiling natively, call 'sizeof' at expansion
218 ;; time; otherwise, emit code to call it at run time.
221 (if (= (target-word-size)
222 (with-target %host-type target-word-size))
224 #'(alignof type)))))))
227 (define-syntax align ;as found in (system foreign)
229 "Add to OFFSET whatever it takes to get proper alignment for TYPE."
230 ((_ offset (type ~ endianness))
233 (1+ (logior (1- offset) (1- (alignof* type)))))))
235 (define-syntax type-size
242 (define-syntax struct-alignment
244 "Compute the alignment for the aggregate made of TYPES at OFFSET. The
245 result is the alignment of the \"most strictly aligned component\"."
246 ((_ offset types ...)
247 (max (align offset types) ...))))
249 (define-syntax struct-size
251 "Return the size in bytes of the structure made of TYPES."
252 ((_ offset (types-processed ...))
253 ;; The SysV ABI P.S. says: "Aggregates (structures and arrays) and unions
254 ;; assume the alignment of their most strictly aligned component." As an
255 ;; example, a struct such as "int32, int16" has size 8, not 6.
256 (1+ (logior (1- offset)
257 (1- (struct-alignment offset types-processed ...)))))
258 ((_ offset (types-processed ...) type0 types ...)
259 (struct-size (+ (type-size type0) (align offset type0))
260 (type0 types-processed ...)
263 (define-syntax write-type
264 (syntax-rules (~ array *)
265 ((_ bv offset (type ~ order) value)
266 (bytevector-uint-set! bv offset value
267 (endianness order) (sizeof* type)))
268 ((_ bv offset (array type n) value)
275 (write-type bv o type head)
276 (loop (+ 1 i) tail (+ o (sizeof* type))))))))
277 ((_ bv offset '* value)
278 (bytevector-uint-set! bv offset (pointer-address value)
279 (native-endianness) (sizeof* '*)))
280 ((_ bv offset type value)
281 (bytevector-uint-set! bv offset value
282 (native-endianness) (sizeof* type)))))
284 (define-syntax write-types
288 ((_ bv offset (type0 types ...) (field0 fields ...))
290 (write-type bv (align offset type0) type0 field0)
292 (+ (align offset type0) (type-size type0))
293 (types ...) (fields ...))))))
295 (define-syntax read-type
296 (syntax-rules (~ array quote *)
298 (make-pointer (bytevector-uint-ref bv offset
301 ((_ bv offset (type ~ order))
302 (bytevector-uint-ref bv offset
303 (endianness order) (sizeof* type)))
304 ((_ bv offset (array type n))
305 (unfold (lambda (i) (= i n))
307 (read-type bv (+ offset (* i (sizeof* type))) type))
311 (bytevector-uint-ref bv offset
312 (native-endianness) (sizeof* type)))))
314 (define-syntax read-types
316 ((_ return bv offset () (values ...))
318 ((_ return bv offset (type0 types ...) (values ...))
321 (+ (align offset type0) (type-size type0))
323 (values ... (read-type bv
327 (define-syntax define-c-struct-macro
329 "Define NAME as a macro that can be queried to get information about the C
330 struct it represents. In particular:
332 (NAME field-offset FIELD)
334 returns the offset in bytes of FIELD within the C struct represented by NAME."
335 ((_ name ((fields types) ...))
336 (define-c-struct-macro name
338 ((fields types) ...)))
339 ((_ name (fields ...) offset (clauses ...) ((field type) rest ...))
340 (define-c-struct-macro name
342 (+ (align offset type) (type-size type))
343 (clauses ... ((_ field-offset field) (align offset type)))
345 ((_ name (fields ...) offset (clauses ...) ())
347 (syntax-rules (field-offset fields ...)
350 (define-syntax define-c-struct
352 "Define SIZE as the size in bytes of the C structure made of FIELDS. READ
353 as a deserializer and WRITE! as a serializer for the C structure with the
354 given TYPES. READ uses WRAP-FIELDS to return its value."
355 ((_ name size wrap-fields read write! (fields types) ...)
357 (define-c-struct-macro name
358 ((fields types) ...))
360 (struct-size 0 () types ...))
361 (define (write! bv offset fields ...)
362 (write-types bv offset (types ...) (fields ...)))
363 (define* (read bv #:optional (offset 0))
364 (read-types wrap-fields bv offset (types ...) ()))))))
366 (define-syntax-rule (c-struct-field-offset type field)
367 "Return the offset in BYTES of FIELD within TYPE, where TYPE is a C struct
368 defined with 'define-c-struct' and FIELD is a field identifier. An
369 expansion-time error is raised if FIELD does not exist in TYPE."
370 (type field-offset field))
377 (define (call-with-restart-on-EINTR thunk)
382 (if (= (system-error-errno args) EINTR)
384 (apply throw args))))))
386 (define-syntax-rule (restart-on-EINTR expr)
387 "Evaluate EXPR and restart upon EINTR. Return the value of EXPR."
388 (call-with-restart-on-EINTR (lambda () expr)))
390 (define (syscall->procedure return-type name argument-types)
391 "Return a procedure that wraps the C function NAME using the dynamic FFI,
392 and that returns two values: NAME's return value, and errno.
394 If an error occurs while creating the binding, defer the error report until
395 the returned procedure is called."
398 (let ((ptr (dynamic-func name (dynamic-link))))
399 ;; The #:return-errno? facility was introduced in Guile 2.0.12.
400 (pointer->procedure return-type ptr argument-types
401 #:return-errno? #t)))
404 (throw 'system-error name "~A" (list (strerror ENOSYS))
407 (define-syntax define-as-needed
409 "Define VARIABLE. If VARIABLE already exists in (guile) then re-export it,
410 otherwise export the newly-defined VARIABLE."
411 ((_ (proc args ...) body ...)
412 (define-as-needed proc (lambda* (args ...) body ...)))
414 (if (module-defined? the-scm-module 'variable)
415 (module-re-export! (current-module) '(variable))
417 (module-define! (current-module) 'variable value)
418 (module-export! (current-module) '(variable)))))))
425 (define (augment-mtab source target type options)
426 "Augment /etc/mtab with information about the given mount point."
427 (let ((port (open-file "/etc/mtab" "a")))
428 (format port "~a ~a ~a ~a 0 0~%"
429 source target type (or options "rw"))
432 (define (read-mtab port)
433 "Read an mtab-formatted file from PORT, returning a list of tuples."
434 (let loop ((result '()))
435 (let ((line (read-line port)))
436 (if (eof-object? line)
438 (loop (cons (string-tokenize line) result))))))
440 (define (remove-from-mtab target)
441 "Remove mount point TARGET from /etc/mtab."
443 (remove (match-lambda
444 ((device mount-point type options freq passno)
445 (string=? target mount-point))
447 (call-with-input-file "/etc/mtab" read-mtab)))
449 (call-with-output-file "/etc/mtab"
451 (for-each (match-lambda
452 ((device mount-point type options freq passno)
453 (format port "~a ~a ~a ~a ~a ~a~%"
454 device mount-point type options freq passno)))
457 ;; Linux mount flags, from libc's <sys/mount.h>.
462 (define MS_REMOUNT 32)
463 (define MS_NOATIME 1024)
464 (define MS_BIND 4096)
465 (define MS_MOVE 8192)
466 (define MS_STRICTATIME 16777216)
467 (define MS_LAZYTIME 33554432)
470 (define MNT_DETACH 2)
471 (define MNT_EXPIRE 4)
472 (define UMOUNT_NOFOLLOW 8)
474 (define-as-needed (mount source target type
475 #:optional (flags 0) options
476 #:key (update-mtab? #f))
477 "Mount device SOURCE on TARGET as a file system TYPE.
478 Optionally, FLAGS may be a bitwise-or of the MS_* <sys/mount.h>
479 constants, and OPTIONS may be a string. When FLAGS contains
480 MS_REMOUNT, SOURCE and TYPE are ignored. When UPDATE-MTAB? is true,
481 update /etc/mtab. Raise a 'system-error' exception on error."
482 ;; XXX: '#:update-mtab?' is not implemented by core 'mount'.
483 (let ((proc (syscall->procedure int "mount" `(* * * ,unsigned-long *))))
484 (let-values (((ret err)
486 (string->pointer source)
488 (string->pointer target)
490 (string->pointer type)
494 (string->pointer options)
497 (throw 'system-error "mount" "mount ~S on ~S: ~A"
498 (list source target (strerror err))
501 (augment-mtab source target type options)))))
503 (define-as-needed (umount target
505 #:key (update-mtab? #f))
506 "Unmount TARGET. Optionally FLAGS may be one of the MNT_* or UMOUNT_*
507 constants from <sys/mount.h>."
508 ;; XXX: '#:update-mtab?' is not implemented by core 'umount'.
509 (let ((proc (syscall->procedure int "umount2" `(* ,int))))
510 (let-values (((ret err)
511 (proc (string->pointer target) flags)))
513 (throw 'system-error "umount" "~S: ~A"
514 (list target (strerror err))
517 (remove-from-mtab target)))))
519 (define (mount-points)
520 "Return the mounts points for currently mounted file systems."
521 (call-with-input-file "/proc/mounts"
523 (let loop ((result '()))
524 (let ((line (read-line port)))
525 (if (eof-object? line)
527 (match (string-tokenize line)
528 ((source mount-point _ ...)
529 (loop (cons mount-point result))))))))))
532 (let ((proc (syscall->procedure int "swapon" (list '* int))))
533 (lambda* (device #:optional (flags 0))
534 "Use the block special device at DEVICE for swapping."
535 (let-values (((ret err)
536 (proc (string->pointer device) flags)))
538 (throw 'system-error "swapon" "~S: ~A"
539 (list device (strerror err))
543 (let ((proc (syscall->procedure int "swapoff" '(*))))
545 "Stop using block special device DEVICE for swapping."
546 (let-values (((ret err) (proc (string->pointer device))))
548 (throw 'system-error "swapoff" "~S: ~A"
549 (list device (strerror err))
552 (define-as-needed RB_AUTOBOOT #x01234567)
553 (define-as-needed RB_HALT_SYSTEM #xcdef0123)
554 (define-as-needed RB_ENABLED_CAD #x89abcdef)
555 (define-as-needed RB_DISABLE_CAD 0)
556 (define-as-needed RB_POWER_OFF #x4321fedc)
557 (define-as-needed RB_SW_SUSPEND #xd000fce2)
558 (define-as-needed RB_KEXEC #x45584543)
560 (define-as-needed (reboot #:optional (cmd RB_AUTOBOOT))
561 (let ((proc (syscall->procedure int "reboot" (list int))))
562 (let-values (((ret err) (proc cmd)))
564 (throw 'system-error "reboot" "~S: ~A"
565 (list cmd (strerror err))
568 (define-as-needed (load-linux-module data #:optional (options ""))
569 (let ((proc (syscall->procedure int "init_module"
570 (list '* unsigned-long '*))))
571 (let-values (((ret err)
572 (proc (bytevector->pointer data)
573 (bytevector-length data)
574 (string->pointer options))))
576 (throw 'system-error "load-linux-module" "~A"
577 (list (strerror err))
580 (define (kernel? pid)
581 "Return #t if PID designates a \"kernel thread\" rather than a normal
583 (let ((stat (call-with-input-file (format #f "/proc/~a/stat" pid)
584 (compose string-tokenize read-string))))
585 ;; See proc.txt in Linux's documentation for the list of fields.
587 ((pid tcomm state ppid pgrp sid tty_nr tty_pgrp flags min_flt
588 cmin_flt maj_flt cmaj_flt utime stime cutime cstime
589 priority nice num_thread it_real_value start_time
591 (= string->number start_code) (= string->number end_code) _ ...)
592 ;; Got this obscure trick from sysvinit's 'killall5' program.
593 (and (zero? start_code) (zero? end_code))))))
596 "Return the list of live processes."
597 (sort (filter-map (lambda (file)
598 (let ((pid (string->number file)))
606 (let ((proc (syscall->procedure '* "mkdtemp" '(*))))
608 "Create a new unique directory in the file system using the template
609 string TMPL and return its file name. TMPL must end with 'XXXXXX'."
610 (let-values (((result err) (proc (string->pointer tmpl))))
611 (when (null-pointer? result)
612 (throw 'system-error "mkdtemp!" "~S: ~A"
613 (list tmpl (strerror err))
615 (pointer->string result)))))
618 (let ((proc (syscall->procedure int "fdatasync" (list int))))
620 "Flush buffered output of PORT, an output file port, and then call
621 fdatasync(2) on the underlying file descriptor."
623 (let*-values (((fd) (fileno port))
624 ((ret err) (proc fd)))
626 (throw 'system-error "fdatasync" "~S: ~A"
627 (list fd (strerror err))
631 (define-record-type <file-system>
632 (file-system type block-size blocks blocks-free
633 blocks-available files free-files identifier
634 name-length fragment-size mount-flags spare)
636 (type file-system-type)
637 (block-size file-system-block-size)
638 (blocks file-system-block-count)
639 (blocks-free file-system-blocks-free)
640 (blocks-available file-system-blocks-available)
641 (files file-system-file-count)
642 (free-files file-system-free-file-nodes)
643 (identifier file-system-identifier)
644 (name-length file-system-maximum-name-length)
645 (fragment-size file-system-fragment-size)
646 (mount-flags file-system-mount-flags)
647 (spare file-system--spare))
649 (define-syntax fsword ;fsword_t
650 (identifier-syntax long))
652 (define-c-struct %statfs ;<bits/statfs.h>
653 sizeof-statfs ;slightly overestimated
661 (blocks-available uint64)
664 (identifier (array int 2))
666 (fragment-size fsword)
668 (spare (array fsword 4)))
671 (let ((proc (syscall->procedure int "statfs64" '(* *))))
673 "Return a <file-system> data structure describing the file system
675 (let*-values (((stat) (make-bytevector sizeof-statfs))
676 ((ret err) (proc (string->pointer file)
677 (bytevector->pointer stat))))
680 (throw 'system-error "statfs" "~A: ~A"
681 (list file (strerror err))
684 (define (free-disk-space file)
685 "Return the free disk space, in bytes, on the file system that hosts FILE."
686 (let ((fs (statfs file)))
687 (* (file-system-block-size fs)
688 (file-system-blocks-available fs))))
690 ;; Flags for the *at command, notably the 'utime' procedure of libguile.
692 (define-as-needed AT_FDCWD -100)
693 (define-as-needed AT_SYMLINK_NOFOLLOW #x100)
694 (define-as-needed AT_REMOVEDIR #x200)
695 (define-as-needed AT_SYMLINK_FOLLOW #x400)
696 (define-as-needed AT_NO_AUTOMOUNT #x800)
697 (define-as-needed AT_EMPTY_PATH #x1000)
699 (define-syntax BLKRRPART ;<sys/mount.h>
700 (identifier-syntax #x125F))
702 (define* (device-in-use? device)
703 "Return #t if the block DEVICE is in use, #f otherwise. This is inspired
704 from fdisk_device_is_used function of util-linux. This is particularly useful
705 for devices that do not appear in /proc/self/mounts like overlayfs lowerdir
707 (let*-values (((fd) (open-fdes device O_RDONLY))
708 ((ret err) (%ioctl fd BLKRRPART %null-pointer)))
716 ;; We get EINVAL for devices that have the GENHD_FL_NO_PART_SCAN flag
717 ;; set in the kernel, in particular loopback devices, though we do seem
718 ;; to get it for SCSI storage (/dev/sr0) on QEMU.
721 (throw 'system-error "ioctl" "~A"
722 (list (strerror err))
730 ;; From <uapi/linux/random.h>.
731 (define RNDADDTOENTCNT #x40045201)
733 (define (add-to-entropy-count port-or-fd n)
734 "Add N to the kernel's entropy count (the value that can be read from
735 /proc/sys/kernel/random/entropy_avail). PORT-OR-FD must correspond to
736 /dev/urandom or /dev/random. Raise to 'system-error with EPERM when the
737 caller lacks root privileges."
738 (let ((fd (if (port? port-or-fd)
741 (box (make-bytevector (sizeof int))))
742 (bytevector-sint-set! box 0 n (native-endianness)
744 (let-values (((ret err)
745 (%ioctl fd RNDADDTOENTCNT
746 (bytevector->pointer box))))
748 (throw 'system-error "add-to-entropy-count" "~A"
749 (list (strerror err))
757 ;; Linux clone flags, from linux/sched.h
758 (define CLONE_CHILD_CLEARTID #x00200000)
759 (define CLONE_CHILD_SETTID #x01000000)
760 (define CLONE_NEWNS #x00020000)
761 (define CLONE_NEWUTS #x04000000)
762 (define CLONE_NEWIPC #x08000000)
763 (define CLONE_NEWUSER #x10000000)
764 (define CLONE_NEWPID #x20000000)
765 (define CLONE_NEWNET #x40000000)
767 (define %set-automatic-finalization-enabled?!
768 ;; When using a statically-linked Guile, for instance in the initrd, we
769 ;; cannot resolve this symbol, but most of the time we don't need it
770 ;; anyway. Thus, delay it.
772 (pointer->procedure int
774 "scm_set_automatic_finalization_enabled"
778 "Switch on or off automatic finalization in a separate thread.
779 Turning finalization off shuts down the finalization thread as a side effect."
780 (->bool ((force proc) (if enabled? 1 0))))))
782 (define-syntax-rule (without-automatic-finalization exp)
783 "Turn off automatic finalization within the dynamic extent of EXP."
787 (set! enabled? (%set-automatic-finalization-enabled?! #f)))
791 (%set-automatic-finalization-enabled?! enabled?)))))
793 ;; The libc interface to sys_clone is not useful for Scheme programs, so the
794 ;; low-level system call is wrapped instead. The 'syscall' function is
795 ;; declared in <unistd.h> as a variadic function; in practice, it expects 6
796 ;; pointer-sized arguments, as shown in, e.g., x86_64/syscall.S.
798 (let* ((proc (syscall->procedure int "syscall"
803 ;; TODO: Don't do this.
804 (syscall-id (match (utsname:machine (uname))
812 "Create a new child process by duplicating the current parent process.
813 Unlike the fork system call, clone accepts FLAGS that specify which resources
814 are shared between the parent and child processes."
815 (let-values (((ret err)
816 ;; Guile 2.2 runs a finalization thread. 'primitive-fork'
817 ;; takes care of shutting it down before forking, and we
818 ;; must do the same here. Failing to do that, if the
819 ;; child process calls 'primitive-fork', it will hang
820 ;; while trying to pthread_join the finalization thread
821 ;; since that thread does not exist.
822 (without-automatic-finalization
823 (proc syscall-id flags
824 %null-pointer ;child stack
825 %null-pointer %null-pointer ;ptid & ctid
826 %null-pointer)))) ;unused
828 (throw 'system-error "clone" "~d: ~A"
829 (list flags (strerror err))
834 ;; Some systems may be using an old (pre-2.14) version of glibc where there
835 ;; is no 'setns' function available.
837 (let ((proc (syscall->procedure int "setns" (list int int))))
838 (lambda (fdes nstype)
839 "Reassociate the current process with the namespace specified by FDES, a
840 file descriptor obtained by opening a /proc/PID/ns/* file. NSTYPE specifies
841 which type of namespace the current process may be reassociated with, or 0 if
842 there is no such limitation."
843 (let-values (((ret err) (proc fdes nstype)))
845 (throw 'system-error "setns" "~d ~d: ~A"
846 (list fdes nstype (strerror err))
850 (let ((proc (syscall->procedure int "pivot_root" (list '* '*))))
851 (lambda (new-root put-old)
852 "Change the root file system to NEW-ROOT and move the current root file
854 (let-values (((ret err)
855 (proc (string->pointer new-root)
856 (string->pointer put-old))))
858 (throw 'system-error "pivot_root" "~S ~S: ~A"
859 (list new-root put-old (strerror err))
867 (define (file-type->symbol type)
868 ;; Convert TYPE to symbols like 'stat:type' does.
869 (cond ((= type DT_REG) 'regular)
870 ((= type DT_LNK) 'symlink)
871 ((= type DT_DIR) 'directory)
872 ((= type DT_FIFO) 'fifo)
873 ((= type DT_CHR) 'char-special)
874 ((= type DT_BLK) 'block-special)
875 ((= type DT_SOCK) 'socket)
878 ;; 'struct dirent64' for GNU/Linux.
879 (define-c-struct %struct-dirent-header/linux
880 sizeof-dirent-header/linux
881 (lambda (inode offset length type name)
882 `((type . ,(file-type->symbol type))
884 read-dirent-header/linux
885 write-dirent-header!/linux
888 (length unsigned-short)
890 (name uint8)) ;first byte of 'd_name'
892 ;; 'struct dirent64' for GNU/Hurd.
893 (define-c-struct %struct-dirent-header/hurd
894 sizeof-dirent-header/hurd
895 (lambda (inode length type name-length name)
896 `((type . ,(file-type->symbol type))
898 read-dirent-header/hurd
899 write-dirent-header!/hurd
901 (length unsigned-short)
906 ;; Constants for the 'type' field, from <dirent.h>.
907 (define DT_UNKNOWN 0)
917 (define string->pointer/utf-8
918 (cut string->pointer <> "UTF-8"))
920 (define pointer->string/utf-8
921 (cut pointer->string <> <> "UTF-8"))
924 (let ((proc (syscall->procedure '* "opendir" '(*))))
925 (lambda* (name #:optional (string->pointer string->pointer/utf-8))
926 (let-values (((ptr err)
927 (proc (string->pointer name))))
928 (if (null-pointer? ptr)
929 (throw 'system-error "opendir*"
930 "~A: ~A" (list name (strerror err))
935 (let ((proc (syscall->procedure int "closedir" '(*))))
937 (let-values (((ret err)
940 (throw 'system-error "closedir"
941 "closedir: ~A" (list (strerror err))
944 (define (readdir-procedure name-field-offset sizeof-dirent-header
946 (let ((proc (syscall->procedure '* "readdir64" '(*))))
947 (lambda* (directory #:optional (pointer->string pointer->string/utf-8))
948 (let ((ptr (proc directory)))
949 (and (not (null-pointer? ptr))
950 (cons (pointer->string
951 (make-pointer (+ (pointer-address ptr) name-field-offset))
954 (pointer->bytevector ptr sizeof-dirent-header))))))))
957 ;; Decide at run time which one must be used.
958 (if (string-contains %host-type "linux-gnu")
959 (readdir-procedure (c-struct-field-offset %struct-dirent-header/linux
961 sizeof-dirent-header/linux
962 read-dirent-header/linux)
963 (readdir-procedure (c-struct-field-offset %struct-dirent-header/hurd
965 sizeof-dirent-header/hurd
966 read-dirent-header/hurd)))
968 (define* (scandir* name #:optional
970 (entry<? (lambda (entry1 entry2)
975 (string<? name1 name2)))))))
977 (string->pointer string->pointer/utf-8)
978 (pointer->string pointer->string/utf-8))
979 "This procedure improves on Guile's 'scandir' procedure in several ways:
981 1. Systematically encode decode file names using STRING->POINTER and
982 POINTER->STRING (UTF-8 by default; this works around a defect in Guile 2.0/2.2
983 where 'scandir' decodes file names according to the current locale, which is
984 not always desirable.
986 2. Each entry that is returned has the form (NAME . PROPERTIES).
987 PROPERTIES is an alist showing additional properties about the entry, as
988 found in 'struct dirent'. An entry may look like this:
990 (\"foo.scm\" (type . regular) (inode . 123456))
992 Callers must be prepared to deal with the case where 'type' is 'unknown'
993 since some file systems do not provide that information.
995 3. Raise to 'system-error' when NAME cannot be opened."
996 (let ((directory (opendir* name string->pointer)))
1000 (let loop ((result '()))
1001 (match (readdir* directory pointer->string)
1003 (sort result entry<?))
1005 (loop (if (select? entry)
1009 (closedir* directory)))))
1013 ;;; Advisory file locking.
1016 (define-c-struct %struct-flock ;<fcntl.h>
1028 ;; On Linux-based systems, this is usually 7, but not always
1029 ;; (exceptions include SPARC.) On GNU/Hurd, it's 9.
1030 (cond ((string-contains %host-type "sparc") 9) ; sparc-*-linux-gnu
1031 ((string-contains %host-type "linux") 7) ; *-linux-gnu
1035 ;; Likewise: GNU/Hurd and SPARC use 8, while the others typically use 6.
1036 (cond ((string-contains %host-type "sparc") 8) ; sparc-*-linux-gnu
1037 ((string-contains %host-type "linux") 6) ; *-linux-gnu
1041 ;; The F_RDLCK, F_WRLCK, and F_UNLCK constants.
1042 (cond ((string-contains %host-type "sparc") #(1 2 3)) ; sparc-*-linux-gnu
1043 ((string-contains %host-type "hppa") #(1 2 3)) ; hppa-*-linux-gnu
1044 ((string-contains %host-type "linux") #(0 1 2)) ; *-linux-gnu
1045 (else #(1 2 3)))) ; *-gnu*
1048 (let ((proc (syscall->procedure int "fcntl" `(,int ,int *))))
1049 (lambda* (fd-or-port operation #:key (wait? #t))
1050 "Perform locking OPERATION on the file beneath FD-OR-PORT. OPERATION
1051 must be a symbol, one of 'read-lock, 'write-lock, or 'unlock. When WAIT? is
1052 true, block until the lock is acquired; otherwise, thrown an 'flock-error'
1053 exception if it's already taken."
1054 (define (operation->int op)
1056 ((read-lock) (vector-ref F_xxLCK 0))
1057 ((write-lock) (vector-ref F_xxLCK 1))
1058 ((unlock) (vector-ref F_xxLCK 2))
1059 (else (error "invalid fcntl-flock operation" op))))
1062 (if (port? fd-or-port)
1067 (make-bytevector sizeof-flock))
1070 (operation->int operation) SEEK_SET
1074 ;; XXX: 'fcntl' is a vararg function, but here we happily use the
1075 ;; standard ABI; crossing fingers.
1076 (let-values (((ret err)
1079 F_SETLKW ;lock & wait
1080 F_SETLK) ;non-blocking attempt
1081 (bytevector->pointer bv))))
1083 ;; Presumably we got EAGAIN or so.
1084 (throw 'flock-error err))))))
1086 (define* (lock-file file #:key (wait? #t))
1087 "Wait and acquire an exclusive lock on FILE. Return an open port."
1088 (let ((port (open-file file "w0")))
1089 (fcntl-flock port 'write-lock #:wait? wait?)
1092 (define (unlock-file port)
1093 "Unlock PORT, a port returned by 'lock-file'."
1094 (fcntl-flock port 'unlock)
1098 (define (call-with-file-lock file thunk)
1103 (catch 'system-error
1107 ;; When using the statically-linked Guile in the initrd,
1108 ;; 'fcntl-flock' returns ENOSYS unconditionally. Ignore
1109 ;; that error since we're typically the only process running
1111 (if (= ENOSYS (system-error-errno args))
1113 (apply throw args))))))
1117 (unlock-file port))))))
1119 (define (call-with-file-lock/no-wait file thunk handler)
1126 (lock-file file #:wait? #f))
1127 (lambda (key . args)
1130 (apply handler args)
1131 ;; No open port to the lock, so return #f.
1134 ;; When using the statically-linked Guile in the initrd,
1135 ;; 'fcntl-flock' returns ENOSYS unconditionally. Ignore
1136 ;; that error since we're typically the only process running
1138 (if (= ENOSYS (system-error-errno (cons key args)))
1140 (apply throw key args)))
1141 (_ (apply throw key args)))))))
1145 (unlock-file port))))))
1147 (define-syntax-rule (with-file-lock file exp ...)
1148 "Wait to acquire a lock on FILE and evaluate EXP in that context."
1149 (call-with-file-lock file (lambda () exp ...)))
1151 (define-syntax-rule (with-file-lock/no-wait file handler exp ...)
1152 "Try to acquire a lock on FILE and evaluate EXP in that context. Execute
1153 handler if the lock is already held by another process."
1154 (call-with-file-lock/no-wait file (lambda () exp ...) handler))
1158 ;;; Miscellaneous, aka. 'prctl'.
1162 ;; Should it win the API contest against 'ioctl'? You tell us!
1163 (syscall->procedure int "prctl"
1164 (list int unsigned-long unsigned-long
1165 unsigned-long unsigned-long)))
1167 (define PR_SET_NAME 15) ;<linux/prctl.h>
1168 (define PR_GET_NAME 16)
1170 (define %max-thread-name-length
1171 ;; Maximum length in bytes of the process name, including the terminating
1175 (define (set-thread-name name)
1176 "Set the name of the calling thread to NAME. NAME is truncated to 15
1178 (let ((ptr (string->pointer name)))
1179 (let-values (((ret err)
1181 (pointer-address ptr) 0 0 0)))
1183 (throw 'set-process-name "set-process-name"
1184 "set-process-name: ~A"
1185 (list (strerror err))
1188 (define (thread-name)
1189 "Return the name of the calling thread as a string."
1190 (let ((buf (make-bytevector %max-thread-name-length)))
1191 (let-values (((ret err)
1193 (pointer-address (bytevector->pointer buf))
1196 (bytes->string (bytevector->u8-list buf))
1197 (throw 'process-name "process-name"
1199 (list (strerror err))
1204 ;;; Network interfaces.
1207 (define SIOCGIFCONF ;from <bits/ioctls.h>
1208 (if (string-contains %host-type "linux")
1210 #xf00801a4)) ;GNU/Hurd
1211 (define SIOCGIFFLAGS
1212 (if (string-contains %host-type "linux")
1214 #xc4804191)) ;GNU/Hurd
1215 (define SIOCSIFFLAGS
1216 (if (string-contains %host-type "linux")
1218 -1)) ;FIXME: GNU/Hurd?
1220 (if (string-contains %host-type "linux")
1222 -1)) ;FIXME: GNU/Hurd?
1224 (if (string-contains %host-type "linux")
1226 -1)) ;FIXME: GNU/Hurd?
1227 (define SIOCGIFNETMASK
1228 (if (string-contains %host-type "linux")
1230 -1)) ;FIXME: GNU/Hurd?
1231 (define SIOCSIFNETMASK
1232 (if (string-contains %host-type "linux")
1234 -1)) ;FIXME: GNU/Hurd?
1236 (if (string-contains %host-type "linux")
1238 -1)) ;FIXME: GNU/Hurd?
1240 (if (string-contains %host-type "linux")
1242 -1)) ;FIXME: GNU/Hurd?
1244 ;; Flags and constants from <net/if.h>.
1246 (define-as-needed IFF_UP #x1) ;Interface is up
1247 (define-as-needed IFF_BROADCAST #x2) ;Broadcast address valid.
1248 (define-as-needed IFF_LOOPBACK #x8) ;Is a loopback net.
1249 (define-as-needed IFF_RUNNING #x40) ;interface RFC2863 OPER_UP
1250 (define-as-needed IFF_NOARP #x80) ;ARP disabled or unsupported
1252 (define IF_NAMESIZE 16) ;maximum interface name size
1254 (define-c-struct %ifconf-struct
1259 (length int) ;int ifc_len
1260 (request '*)) ;struct ifreq *ifc_ifcu
1262 (define ifreq-struct-size
1263 ;; 'struct ifreq' begins with an array of IF_NAMESIZE bytes containing the
1264 ;; interface name (nul-terminated), followed by a bunch of stuff. This is
1265 ;; its size in bytes.
1266 (if (= 8 (sizeof '*))
1270 (define-c-struct sockaddr-in ;<linux/in.h>
1272 (lambda (family port address)
1273 (make-socket-address family address port))
1276 (family unsigned-short)
1277 (port (int16 ~ big))
1278 (address (int32 ~ big)))
1280 (define-c-struct sockaddr-in6 ;<linux/in6.h>
1282 (lambda (family port flowinfo address scopeid)
1283 (make-socket-address family address port flowinfo scopeid))
1286 (family unsigned-short)
1287 (port (int16 ~ big))
1288 (flowinfo (int32 ~ big))
1289 (address (int128 ~ big))
1292 (define (write-socket-address! sockaddr bv index)
1293 "Write SOCKADDR, a socket address as returned by 'make-socket-address', to
1294 bytevector BV at INDEX."
1295 (let ((family (sockaddr:fam sockaddr)))
1296 (cond ((= family AF_INET)
1297 (write-sockaddr-in! bv index
1299 (sockaddr:port sockaddr)
1300 (sockaddr:addr sockaddr)))
1301 ((= family AF_INET6)
1302 (write-sockaddr-in6! bv index
1304 (sockaddr:port sockaddr)
1305 (sockaddr:flowinfo sockaddr)
1306 (sockaddr:addr sockaddr)
1307 (sockaddr:scopeid sockaddr)))
1309 (error "unsupported socket address" sockaddr)))))
1311 (define PF_PACKET 17) ;<bits/socket.h>
1312 (define AF_PACKET PF_PACKET)
1314 (define* (read-socket-address bv #:optional (index 0))
1315 "Read a socket address from bytevector BV at INDEX."
1316 (let ((family (bytevector-u16-native-ref bv index)))
1317 (cond ((= family AF_INET)
1318 (read-sockaddr-in bv index))
1319 ((= family AF_INET6)
1320 (read-sockaddr-in6 bv index))
1322 ;; XXX: Unsupported address family, such as AF_PACKET. Return a
1323 ;; vector such that the vector can at least call 'sockaddr:fam'.
1327 ;; The most terrible interface, live from Scheme.
1328 (syscall->procedure int "ioctl" (list int unsigned-long '*)))
1330 (define (bytes->string bytes)
1331 "Read BYTES, a list of bytes, and return the null-terminated string decoded
1332 from there, or #f if that would be an empty string."
1333 (match (take-while (negate zero?) bytes)
1337 (list->string (map integer->char non-zero)))))
1339 (define (bytevector->string-list bv stride len)
1340 "Return the null-terminated strings found in BV every STRIDE bytes. Read at
1341 most LEN bytes from BV."
1342 (let loop ((bytes (take (bytevector->u8-list bv)
1343 (min len (bytevector-length bv))))
1349 (loop (drop bytes stride)
1350 (cons (bytes->string bytes) result))))))
1352 (define* (network-interface-names #:optional sock)
1353 "Return the names of existing network interfaces. This is typically limited
1354 to interfaces that are currently up."
1355 (let* ((close? (not sock))
1356 (sock (or sock (socket SOCK_STREAM AF_INET 0)))
1357 (len (* ifreq-struct-size 10))
1358 (reqs (make-bytevector len))
1359 (conf (make-bytevector sizeof-ifconf)))
1360 (write-ifconf! conf 0
1361 len (bytevector->pointer reqs))
1363 (let-values (((ret err)
1364 (%ioctl (fileno sock) SIOCGIFCONF
1365 (bytevector->pointer conf))))
1369 (bytevector->string-list reqs ifreq-struct-size
1370 (match (read-ifconf conf)
1372 (throw 'system-error "network-interface-list"
1373 "network-interface-list: ~A"
1374 (list (strerror err))
1377 (define %interface-line
1378 ;; Regexp matching an interface line in Linux's /proc/net/dev.
1379 (make-regexp "^[[:blank:]]*([[:graph:]]+):.*$"))
1381 (define (all-network-interface-names)
1382 "Return all the names of the registered network interfaces, including those
1384 (call-with-input-file "/proc/net/dev" ;XXX: Linux-specific
1386 (let loop ((interfaces '()))
1387 (let ((line (read-line port)))
1388 (cond ((eof-object? line)
1389 (reverse interfaces))
1390 ((regexp-exec %interface-line line)
1393 (loop (cons (match:substring match 1) interfaces))))
1395 (loop interfaces))))))))
1397 (define-as-needed (network-interface-flags socket name)
1398 "Return a number that is the bit-wise or of 'IFF*' flags for network
1400 (let ((req (make-bytevector ifreq-struct-size)))
1401 (bytevector-copy! (string->utf8 name) 0 req 0
1402 (min (string-length name) (- IF_NAMESIZE 1)))
1403 (let-values (((ret err)
1404 (%ioctl (fileno socket) SIOCGIFFLAGS
1405 (bytevector->pointer req))))
1408 ;; The 'ifr_flags' field is IF_NAMESIZE bytes after the
1409 ;; beginning of 'struct ifreq', and it's a short int.
1410 (bytevector-sint-ref req IF_NAMESIZE (native-endianness)
1413 (throw 'system-error "network-interface-flags"
1414 "network-interface-flags on ~A: ~A"
1415 (list name (strerror err))
1418 (define (loopback-network-interface? name)
1419 "Return true if NAME designates a loopback network interface."
1420 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1421 (flags (network-interface-flags sock name)))
1423 (not (zero? (logand flags IFF_LOOPBACK)))))
1425 (define (network-interface-running? name)
1426 "Return true if NAME designates a running network interface."
1427 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1428 (flags (network-interface-flags sock name)))
1430 (not (zero? (logand flags IFF_RUNNING)))))
1432 (define (arp-network-interface? name)
1433 "Return true if NAME supports the Address Resolution Protocol."
1434 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1435 (flags (network-interface-flags sock name)))
1437 (zero? (logand flags IFF_NOARP))))
1439 (define-as-needed (set-network-interface-flags socket name flags)
1440 "Set the flag of network interface NAME to FLAGS."
1441 (let ((req (make-bytevector ifreq-struct-size)))
1442 (bytevector-copy! (string->utf8 name) 0 req 0
1443 (min (string-length name) (- IF_NAMESIZE 1)))
1444 ;; Set the 'ifr_flags' field.
1445 (bytevector-uint-set! req IF_NAMESIZE flags (native-endianness)
1447 (let-values (((ret err)
1448 (%ioctl (fileno socket) SIOCSIFFLAGS
1449 (bytevector->pointer req))))
1451 (throw 'system-error "set-network-interface-flags"
1452 "set-network-interface-flags on ~A: ~A"
1453 (list name (strerror err))
1456 (define-as-needed (set-network-interface-address socket name sockaddr)
1457 "Set the address of network interface NAME to SOCKADDR."
1458 (let ((req (make-bytevector ifreq-struct-size)))
1459 (bytevector-copy! (string->utf8 name) 0 req 0
1460 (min (string-length name) (- IF_NAMESIZE 1)))
1461 ;; Set the 'ifr_addr' field.
1462 (write-socket-address! sockaddr req IF_NAMESIZE)
1463 (let-values (((ret err)
1464 (%ioctl (fileno socket) SIOCSIFADDR
1465 (bytevector->pointer req))))
1467 (throw 'system-error "set-network-interface-address"
1468 "set-network-interface-address on ~A: ~A"
1469 (list name (strerror err))
1472 (define (set-network-interface-netmask socket name sockaddr)
1473 "Set the network mask of interface NAME to SOCKADDR."
1474 (let ((req (make-bytevector ifreq-struct-size)))
1475 (bytevector-copy! (string->utf8 name) 0 req 0
1476 (min (string-length name) (- IF_NAMESIZE 1)))
1477 ;; Set the 'ifr_addr' field.
1478 (write-socket-address! sockaddr req IF_NAMESIZE)
1479 (let-values (((ret err)
1480 (%ioctl (fileno socket) SIOCSIFNETMASK
1481 (bytevector->pointer req))))
1483 (throw 'system-error "set-network-interface-netmask"
1484 "set-network-interface-netmask on ~A: ~A"
1485 (list name (strerror err))
1488 (define (network-interface-address socket name)
1489 "Return the address of network interface NAME. The result is an object of
1490 the same type as that returned by 'make-socket-address'."
1491 (let ((req (make-bytevector ifreq-struct-size)))
1492 (bytevector-copy! (string->utf8 name) 0 req 0
1493 (min (string-length name) (- IF_NAMESIZE 1)))
1494 (let-values (((ret err)
1495 (%ioctl (fileno socket) SIOCGIFADDR
1496 (bytevector->pointer req))))
1498 (read-socket-address req IF_NAMESIZE)
1499 (throw 'system-error "network-interface-address"
1500 "network-interface-address on ~A: ~A"
1501 (list name (strerror err))
1504 (define (network-interface-netmask socket name)
1505 "Return the netmask of network interface NAME. The result is an object of
1506 the same type as that returned by 'make-socket-address'."
1507 (let ((req (make-bytevector ifreq-struct-size)))
1508 (bytevector-copy! (string->utf8 name) 0 req 0
1509 (min (string-length name) (- IF_NAMESIZE 1)))
1510 (let-values (((ret err)
1511 (%ioctl (fileno socket) SIOCGIFNETMASK
1512 (bytevector->pointer req))))
1514 (read-socket-address req IF_NAMESIZE)
1515 (throw 'system-error "network-interface-netmask"
1516 "network-interface-netmask on ~A: ~A"
1517 (list name (strerror err))
1520 (define* (configure-network-interface name sockaddr flags
1522 "Configure network interface NAME to use SOCKADDR, an address as returned by
1523 'make-socket-address', and FLAGS, a bitwise-or of IFF_* constants. If NETMASK
1524 is true, it must be a socket address to use as the network mask."
1525 (let ((sock (socket (sockaddr:fam sockaddr) SOCK_STREAM 0)))
1529 (set-network-interface-address sock name sockaddr)
1530 (set-network-interface-flags sock name flags)
1532 (set-network-interface-netmask sock name netmask)))
1534 (close-port sock)))))
1536 (define* (set-network-interface-up name
1537 #:key (family AF_INET))
1538 "Turn up the interface NAME."
1539 (let ((sock (socket family SOCK_STREAM 0)))
1543 (let ((flags (network-interface-flags sock name)))
1544 (set-network-interface-flags sock name
1545 (logior flags IFF_UP))))
1547 (close-port sock)))))
1554 (define-c-struct %rtentry ;'struct rtentry' from <net/route.h>
1559 (pad1 unsigned-long)
1560 (destination (array uint8 16)) ;struct sockaddr
1561 (gateway (array uint8 16)) ;struct sockaddr
1562 (genmask (array uint8 16)) ;struct sockaddr
1563 (flags unsigned-short)
1568 (pad4 (array uint8 (if (= 8 (sizeof* '*)) 3 1)))
1572 (window unsigned-long)
1573 (initial-rtt unsigned-short))
1575 (define RTF_UP #x0001) ;'rtentry' flags from <net/route.h>
1576 (define RTF_GATEWAY #x0002)
1578 (define %sockaddr-any
1579 (make-socket-address AF_INET INADDR_ANY 0))
1581 (define add-network-route/gateway
1582 ;; To allow field names to be matched as literals, we need to move them out
1583 ;; of the lambda's body since the parameters have the same name. A lot of
1584 ;; fuss for very little.
1585 (let-syntax ((gateway-offset (identifier-syntax
1586 (c-struct-field-offset %rtentry gateway)))
1587 (destination-offset (identifier-syntax
1588 (c-struct-field-offset %rtentry destination)))
1589 (genmask-offset (identifier-syntax
1590 (c-struct-field-offset %rtentry genmask))))
1591 (lambda* (socket gateway
1592 #:key (destination %sockaddr-any) (genmask %sockaddr-any))
1593 "Add a network route for DESTINATION (a socket address as returned by
1594 'make-socket-address') that goes through GATEWAY (a socket address). For
1597 (add-network-route/gateway sock
1598 (make-socket-address
1600 (inet-pton AF_INET \"192.168.0.1\")
1603 is equivalent to this 'net-tools' command:
1605 route add -net default gw 192.168.0.1
1607 because the default value of DESTINATION is \"0.0.0.0\"."
1608 (let ((route (make-bytevector sizeof-rtentry 0)))
1609 (write-socket-address! gateway route gateway-offset)
1610 (write-socket-address! destination route destination-offset)
1611 (write-socket-address! genmask route genmask-offset)
1612 (bytevector-u16-native-set! route
1613 (c-struct-field-offset %rtentry flags)
1614 (logior RTF_UP RTF_GATEWAY))
1615 (let-values (((ret err)
1616 (%ioctl (fileno socket) SIOCADDRT
1617 (bytevector->pointer route))))
1619 (throw 'system-error "add-network-route/gateway"
1620 "add-network-route/gateway: ~A"
1621 (list (strerror err))
1624 (define delete-network-route
1625 (let-syntax ((destination-offset (identifier-syntax
1626 (c-struct-field-offset %rtentry destination))))
1627 (lambda* (socket destination)
1628 "Delete the network route for DESTINATION. For instance, the call:
1630 (delete-network-route sock
1631 (make-socket-address AF_INET INADDR_ANY 0))
1633 is equivalent to the 'net-tools' command:
1635 route del -net default
1638 (let ((route (make-bytevector sizeof-rtentry 0)))
1639 (write-socket-address! destination route destination-offset)
1640 (let-values (((ret err)
1641 (%ioctl (fileno socket) SIOCDELRT
1642 (bytevector->pointer route))))
1644 (throw 'system-error "delete-network-route"
1645 "delete-network-route: ~A"
1646 (list (strerror err))
1651 ;;; Details about network interfaces---aka. 'getifaddrs'.
1654 ;; Network interfaces. XXX: We would call it <network-interface> but that
1655 ;; would collide with the ioctl wrappers above.
1656 (define-record-type <interface>
1657 (make-interface name flags address netmask broadcast-address)
1659 (name interface-name) ;string
1660 (flags interface-flags) ;or'd IFF_* values
1661 (address interface-address) ;sockaddr | #f
1662 (netmask interface-netmask) ;sockaddr | #f
1663 (broadcast-address interface-broadcast-address)) ;sockaddr | #f
1665 (define (write-interface interface port)
1667 (($ <interface> name flags address)
1668 (format port "#<interface ~s " name)
1669 (unless (zero? (logand IFF_UP flags))
1670 (display "up " port))
1672 ;; Check whether ADDRESS really is a sockaddr.
1674 (if (member (sockaddr:fam address) (list AF_INET AF_INET6))
1675 (format port "~a " (inet-ntop (sockaddr:fam address)
1676 (sockaddr:addr address)))
1677 (format port "family:~a " (sockaddr:fam address))))
1679 (format port "~a>" (number->string (object-address interface) 16)))))
1681 (set-record-type-printer! <interface> write-interface)
1683 (define (values->interface next name flags address netmask
1684 broadcast-address data)
1685 "Given the raw field values passed as arguments, return a pair whose car is
1686 an <interface> object, and whose cdr is the pointer NEXT."
1687 (define (maybe-socket-address pointer)
1688 (if (null-pointer? pointer)
1690 (read-socket-address (pointer->bytevector pointer 50)))) ;XXX: size
1692 (cons (make-interface (if (null-pointer? name)
1694 (pointer->string name))
1696 (maybe-socket-address address)
1697 (maybe-socket-address netmask)
1698 (maybe-socket-address broadcast-address)
1703 (define-c-struct ifaddrs ;<ifaddrs.h>
1710 (flags unsigned-int)
1716 (define (unfold-interface-list ptr)
1717 "Call 'read-ifaddrs' on PTR and all its 'next' fields, recursively, and
1718 return the list of resulting <interface> objects."
1719 (let loop ((ptr ptr)
1721 (if (null-pointer? ptr)
1723 (match (read-ifaddrs (pointer->bytevector ptr %sizeof-ifaddrs))
1725 (loop ptr (cons ifaddr result)))))))
1727 (define network-interfaces
1728 (let ((proc (syscall->procedure int "getifaddrs" (list '*))))
1730 "Return a list of <interface> objects, each denoting a configured
1731 network interface. This is implemented using the 'getifaddrs' libc function."
1732 (let*-values (((ptr)
1733 (bytevector->pointer (make-bytevector (sizeof* '*))))
1737 (let* ((ptr (dereference-pointer ptr))
1738 (result (unfold-interface-list ptr)))
1741 (throw 'system-error "network-interfaces" "~A"
1742 (list (strerror err))
1745 (define free-ifaddrs
1746 (syscall->procedure void "freeifaddrs" '(*)))
1753 (define-syntax bits->symbols-body
1757 ((_ bits (name names ...) (value values ...))
1758 (let ((result (bits->symbols-body bits (names ...) (values ...))))
1759 (if (zero? (logand bits value))
1761 (cons 'name result))))))
1763 (define-syntax define-bits
1764 (syntax-rules (define)
1765 "Define the given numerical constants under CONSTRUCTOR, such that
1766 (CONSTRUCTOR NAME) returns VALUE. Define BITS->SYMBOLS as a procedure that,
1767 given an integer, returns the list of names of the constants that are or'd."
1768 ((_ constructor bits->symbols (define names values) ...)
1770 (define-syntax constructor
1771 (syntax-rules (names ...)
1773 ((_ names) values) ...
1774 ((_ first rest (... ...))
1775 (logior (constructor first) rest (... ...)))))
1776 (define (bits->symbols bits)
1777 (bits->symbols-body bits (names ...) (values ...)))))))
1779 ;; 'local-flags' bits from <bits/termios.h>
1780 (define-bits local-flags
1781 local-flags->symbols
1782 (define ISIG #o0000001)
1783 (define ICANON #o0000002)
1784 (define XCASE #o0000004)
1785 (define ECHO #o0000010)
1786 (define ECHOE #o0000020)
1787 (define ECHOK #o0000040)
1788 (define ECHONL #o0000100)
1789 (define NOFLSH #o0000200)
1790 (define TOSTOP #o0000400)
1791 (define ECHOCTL #o0001000)
1792 (define ECHOPRT #o0002000)
1793 (define ECHOKE #o0004000)
1794 (define FLUSHO #o0010000)
1795 (define PENDIN #o0040000)
1796 (define IEXTEN #o0100000)
1797 (define EXTPROC #o0200000))
1799 (define-bits input-flags
1800 input-flags->symbols
1801 (define IGNBRK #o0000001)
1802 (define BRKINT #o0000002)
1803 (define IGNPAR #o0000004)
1804 (define PARMRK #o0000010)
1805 (define INPCK #o0000020)
1806 (define ISTRIP #o0000040)
1807 (define INLCR #o0000100)
1808 (define IGNCR #o0000200)
1809 (define ICRNL #o0000400)
1810 (define IUCLC #o0001000)
1811 (define IXON #o0002000)
1812 (define IXANY #o0004000)
1813 (define IXOFF #o0010000)
1814 (define IMAXBEL #o0020000)
1815 (define IUTF8 #o0040000))
1817 ;; "Actions" values for 'tcsetattr'.
1818 (define-bits tcsetattr-action
1819 %unused-tcsetattr-action->symbols
1821 (define TCSADRAIN 1)
1822 (define TCSAFLUSH 2))
1824 (define-record-type <termios>
1825 (termios input-flags output-flags control-flags local-flags
1826 line-discipline control-chars
1827 input-speed output-speed)
1829 (input-flags termios-input-flags)
1830 (output-flags termios-output-flags)
1831 (control-flags termios-control-flags)
1832 (local-flags termios-local-flags)
1833 (line-discipline termios-line-discipline)
1834 (control-chars termios-control-chars)
1835 (input-speed termios-input-speed)
1836 (output-speed termios-output-speed))
1838 (define-c-struct %termios ;<bits/termios.h>
1843 (input-flags unsigned-int)
1844 (output-flags unsigned-int)
1845 (control-flags unsigned-int)
1846 (local-flags unsigned-int)
1847 (line-discipline uint8)
1848 (control-chars (array uint8 32))
1849 (input-speed unsigned-int)
1850 (output-speed unsigned-int))
1853 (let ((proc (syscall->procedure int "tcgetattr" (list int '*))))
1855 "Return the <termios> structure for the tty at FD."
1856 (let*-values (((bv) (make-bytevector sizeof-termios))
1857 ((ret err) (proc fd (bytevector->pointer bv))))
1860 (throw 'system-error "tcgetattr" "~A"
1861 (list (strerror err))
1865 (let ((proc (syscall->procedure int "tcsetattr" (list int int '*))))
1866 (lambda (fd actions termios)
1867 "Use TERMIOS for the tty at FD. ACTIONS is one of of the values
1868 produced by 'tcsetattr-action'; see tcsetattr(3) for details."
1870 (make-bytevector sizeof-termios))
1872 (let-syntax ((match/write (syntax-rules ()
1875 (($ <termios> fields ...)
1876 (write-termios! bv 0 fields ...)))))))
1877 (match/write input-flags output-flags control-flags local-flags
1878 line-discipline control-chars input-speed output-speed))
1880 (let-values (((ret err) (proc fd actions (bytevector->pointer bv))))
1882 (throw 'system-error "tcgetattr" "~A"
1883 (list (strerror err))
1886 (define-syntax TIOCGWINSZ ;<asm-generic/ioctls.h>
1887 (identifier-syntax #x5413))
1889 (define-record-type <window-size>
1890 (window-size rows columns x-pixels y-pixels)
1892 (rows window-size-rows)
1893 (columns window-size-columns)
1894 (x-pixels window-size-x-pixels)
1895 (y-pixels window-size-y-pixels))
1897 (define-c-struct winsize ;<bits/ioctl-types.h>
1902 (rows unsigned-short)
1903 (columns unsigned-short)
1904 (x-pixels unsigned-short)
1905 (y-pixels unsigned-short))
1907 (define* (terminal-window-size #:optional (port (current-output-port)))
1908 "Return a <window-size> structure describing the terminal at PORT, or raise
1909 a 'system-error' if PORT is not backed by a terminal. This procedure
1910 corresponds to the TIOCGWINSZ ioctl."
1911 (let*-values (((size) (make-bytevector sizeof-winsize))
1912 ((ret err) (%ioctl (fileno port) TIOCGWINSZ
1913 (bytevector->pointer size))))
1916 (throw 'system-error "terminal-window-size" "~A"
1917 (list (strerror err))
1920 (define (terminal-dimension window-dimension port fall-back)
1921 "Return the terminal dimension defined by WINDOW-DIMENSION, one of
1922 'window-size-columns' or 'window-size-rows' for PORT. If PORT does not
1923 correspond to a terminal, return the value returned by FALL-BACK."
1924 (catch 'system-error
1926 (if (file-port? port)
1927 (match (window-dimension (terminal-window-size port))
1928 ;; Things like Emacs shell-mode return 0, which is unreasonable.
1933 (let ((errno (system-error-errno args)))
1934 ;; ENOTTY is what we're after but 2012-and-earlier Linux versions
1935 ;; would return EINVAL instead in some cases:
1936 ;; <https://bugs.ruby-lang.org/issues/10494>.
1937 ;; Furthermore, some FUSE file systems like unionfs return ENOSYS for
1939 (if (memv errno (list ENOTTY EINVAL ENOSYS))
1941 (apply throw args))))))
1943 (define* (terminal-columns #:optional (port (current-output-port)))
1944 "Return the best approximation of the number of columns of the terminal at
1945 PORT, trying to guess a reasonable value if all else fails. The result is
1946 always a positive integer."
1948 (match (and=> (getenv "COLUMNS") string->number)
1950 ((? number? columns)
1951 (if (> columns 0) columns 80))))
1953 (terminal-dimension window-size-columns port fall-back))
1955 (define* (terminal-rows #:optional (port (current-output-port)))
1956 "Return the best approximation of the number of rows of the terminal at
1957 PORT, trying to guess a reasonable value if all else fails. The result is
1958 always a positive integer."
1959 (terminal-dimension window-size-rows port (const 25)))
1966 (define-record-type <utmpx-entry>
1967 (utmpx type pid line id user host termination exit
1968 session time address)
1970 (type utmpx-login-type) ;login-type
1972 (line utmpx-line) ;device name
1974 (user utmpx-user) ;user name
1975 (host utmpx-host) ;host name | #f
1976 (termination utmpx-termination-status)
1977 (exit utmpx-exit-status)
1978 (session utmpx-session-id) ;session ID, for windowing
1979 (time utmpx-time) ;entry time
1980 (address utmpx-address))
1982 (define-c-struct %utmpx ;<utmpx.h>
1984 (lambda (type pid line id user host termination exit session
1985 seconds useconds address %reserved)
1987 (bytes->string line) id
1988 (bytes->string user)
1989 (bytes->string host) termination exit
1991 (make-time time-utc (* 1000 useconds) seconds)
1997 (line (array uint8 32))
1998 (id (array uint8 4))
1999 (user (array uint8 32))
2000 (host (array uint8 256))
2004 (time-seconds int32)
2005 (time-useconds int32)
2006 (address-v6 (array int32 4))
2007 (%reserved (array uint8 20)))
2009 (define-bits login-type
2010 %unused-login-type->symbols
2011 (define EMPTY 0) ;No valid user accounting information.
2012 (define RUN_LVL 1) ;The system's runlevel.
2013 (define BOOT_TIME 2) ;Time of system boot.
2014 (define NEW_TIME 3) ;Time after system clock changed.
2015 (define OLD_TIME 4) ;Time when system clock changed.
2017 (define INIT_PROCESS 5) ;Process spawned by the init process.
2018 (define LOGIN_PROCESS 6) ;Session leader of a logged in user.
2019 (define USER_PROCESS 7) ;Normal process.
2020 (define DEAD_PROCESS 8) ;Terminated process.
2022 (define ACCOUNTING 9)) ;System accounting.
2025 (let ((proc (syscall->procedure void "setutxent" '())))
2027 "Open the user accounting database."
2031 (let ((proc (syscall->procedure void "endutxent" '())))
2033 "Close the user accounting database."
2037 (let ((proc (syscall->procedure '* "getutxent" '())))
2039 "Return the next entry from the user accounting database."
2041 (if (null-pointer? ptr)
2043 (read-utmpx (pointer->bytevector ptr sizeof-utmpx)))))))
2045 (define (utmpx-entries)
2046 "Return the list of entries read from the user accounting database."
2048 (let loop ((entries '()))
2054 (loop (cons entry entries))))))
2056 (define (read-utmpx-from-port port)
2057 "Read a utmpx entry from PORT. Return either the EOF object or a utmpx
2059 (match (get-bytevector-n port sizeof-utmpx)
2060 ((? eof-object? eof)
2065 ;;; syscalls.scm ends here