1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2014, 2015, 2016, 2017, 2018, 2019 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>
7 ;;; This file is part of GNU Guix.
9 ;;; GNU Guix is free software; you can redistribute it and/or modify it
10 ;;; under the terms of the GNU General Public License as published by
11 ;;; the Free Software Foundation; either version 3 of the License, or (at
12 ;;; your option) any later version.
14 ;;; GNU Guix is distributed in the hope that it will be useful, but
15 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;;; GNU General Public License for more details.
19 ;;; You should have received a copy of the GNU General Public License
20 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
22 (define-module (guix build syscalls)
23 #:use-module (system foreign)
24 #:use-module (system base target) ;for cross-compilation support
25 #:use-module (rnrs bytevectors)
26 #:autoload (ice-9 binary-ports) (get-bytevector-n)
27 #:use-module (srfi srfi-1)
28 #:use-module (srfi srfi-9)
29 #:use-module (srfi srfi-9 gnu)
30 #:use-module (srfi srfi-11)
31 #:use-module (srfi srfi-19)
32 #:use-module (srfi srfi-26)
33 #:use-module (ice-9 rdelim)
34 #:use-module (ice-9 regex)
35 #:use-module (ice-9 match)
36 #:use-module (ice-9 ftw)
65 file-system-block-size
66 file-system-block-count
67 file-system-blocks-free
68 file-system-blocks-available
69 file-system-file-count
70 file-system-free-file-nodes
71 file-system-identifier
72 file-system-maximum-name-length
73 file-system-fragment-size
74 file-system-mount-flags
102 all-network-interface-names
103 network-interface-names
104 network-interface-netmask
105 network-interface-running?
106 loopback-network-interface?
107 network-interface-address
108 set-network-interface-netmask
109 set-network-interface-up
110 configure-network-interface
111 add-network-route/gateway
119 interface-broadcast-address
125 termios-control-flags
127 termios-line-discipline
128 termios-control-chars
152 utmpx-termination-status
159 (read-utmpx-from-port . read-utmpx)))
163 ;;; This module provides bindings to libc's syscall wrappers. It uses the
164 ;;; FFI, and thus requires a dynamically-linked Guile.
166 ;;; Some syscalls are already defined in statically-linked Guile by applying
167 ;;; 'guile-linux-syscalls.patch'.
169 ;;; Visibility of syscall's symbols shared between this module and static Guile
170 ;;; is a bit delicate. It is handled by 'define-as-needed' macro.
172 ;;; This macro is used to export symbols in dynamic Guile context, and to
173 ;;; re-export them in static Guile context.
175 ;;; This way, even if they don't appear in #:export list, it is safe to use
176 ;;; syscalls from this module in static or dynamic Guile context.
182 ;;; Packed structures.
185 (define-syntax sizeof*
186 ;; XXX: This duplicates 'compile-time-value'.
187 (syntax-rules (int128 array)
191 (* (sizeof* type) n))
193 (let-syntax ((v (lambda (s)
194 (let ((val (sizeof type)))
199 (define-syntax alignof*
200 ;; XXX: This duplicates 'compile-time-value'.
201 (syntax-rules (int128 array)
207 (let-syntax ((v (lambda (s)
208 (let ((val (alignof type)))
213 (define-syntax align ;as found in (system foreign)
215 "Add to OFFSET whatever it takes to get proper alignment for TYPE."
216 ((_ offset (type ~ endianness))
219 (1+ (logior (1- offset) (1- (alignof* type)))))))
221 (define-syntax type-size
228 (define-syntax struct-alignment
230 "Compute the alignment for the aggregate made of TYPES at OFFSET. The
231 result is the alignment of the \"most strictly aligned component\"."
232 ((_ offset types ...)
233 (max (align offset types) ...))))
235 (define-syntax struct-size
237 "Return the size in bytes of the structure made of TYPES."
238 ((_ offset (types-processed ...))
239 ;; The SysV ABI P.S. says: "Aggregates (structures and arrays) and unions
240 ;; assume the alignment of their most strictly aligned component." As an
241 ;; example, a struct such as "int32, int16" has size 8, not 6.
242 (1+ (logior (1- offset)
243 (1- (struct-alignment offset types-processed ...)))))
244 ((_ offset (types-processed ...) type0 types ...)
245 (struct-size (+ (type-size type0) (align offset type0))
246 (type0 types-processed ...)
249 (define-syntax write-type
250 (syntax-rules (~ array *)
251 ((_ bv offset (type ~ order) value)
252 (bytevector-uint-set! bv offset value
253 (endianness order) (sizeof* type)))
254 ((_ bv offset (array type n) value)
261 (write-type bv o type head)
262 (loop (+ 1 i) tail (+ o (sizeof* type))))))))
263 ((_ bv offset '* value)
264 (bytevector-uint-set! bv offset (pointer-address value)
265 (native-endianness) (sizeof* '*)))
266 ((_ bv offset type value)
267 (bytevector-uint-set! bv offset value
268 (native-endianness) (sizeof* type)))))
270 (define-syntax write-types
274 ((_ bv offset (type0 types ...) (field0 fields ...))
276 (write-type bv (align offset type0) type0 field0)
278 (+ (align offset type0) (type-size type0))
279 (types ...) (fields ...))))))
281 (define-syntax read-type
282 (syntax-rules (~ array quote *)
284 (make-pointer (bytevector-uint-ref bv offset
287 ((_ bv offset (type ~ order))
288 (bytevector-uint-ref bv offset
289 (endianness order) (sizeof* type)))
290 ((_ bv offset (array type n))
291 (unfold (lambda (i) (= i n))
293 (read-type bv (+ offset (* i (sizeof* type))) type))
297 (bytevector-uint-ref bv offset
298 (native-endianness) (sizeof* type)))))
300 (define-syntax read-types
302 ((_ return bv offset () (values ...))
304 ((_ return bv offset (type0 types ...) (values ...))
307 (+ (align offset type0) (type-size type0))
309 (values ... (read-type bv
313 (define-syntax define-c-struct-macro
315 "Define NAME as a macro that can be queried to get information about the C
316 struct it represents. In particular:
318 (NAME field-offset FIELD)
320 returns the offset in bytes of FIELD within the C struct represented by NAME."
321 ((_ name ((fields types) ...))
322 (define-c-struct-macro name
324 ((fields types) ...)))
325 ((_ name (fields ...) offset (clauses ...) ((field type) rest ...))
326 (define-c-struct-macro name
328 (+ (align offset type) (type-size type))
329 (clauses ... ((_ field-offset field) (align offset type)))
331 ((_ name (fields ...) offset (clauses ...) ())
333 (syntax-rules (field-offset fields ...)
336 (define-syntax define-c-struct
338 "Define SIZE as the size in bytes of the C structure made of FIELDS. READ
339 as a deserializer and WRITE! as a serializer for the C structure with the
340 given TYPES. READ uses WRAP-FIELDS to return its value."
341 ((_ name size wrap-fields read write! (fields types) ...)
343 (define-c-struct-macro name
344 ((fields types) ...))
346 (struct-size 0 () types ...))
347 (define (write! bv offset fields ...)
348 (write-types bv offset (types ...) (fields ...)))
349 (define* (read bv #:optional (offset 0))
350 (read-types wrap-fields bv offset (types ...) ()))))))
352 (define-syntax-rule (c-struct-field-offset type field)
353 "Return the offset in BYTES of FIELD within TYPE, where TYPE is a C struct
354 defined with 'define-c-struct' and FIELD is a field identifier. An
355 expansion-time error is raised if FIELD does not exist in TYPE."
356 (type field-offset field))
363 (define (call-with-restart-on-EINTR thunk)
368 (if (= (system-error-errno args) EINTR)
370 (apply throw args))))))
372 (define-syntax-rule (restart-on-EINTR expr)
373 "Evaluate EXPR and restart upon EINTR. Return the value of EXPR."
374 (call-with-restart-on-EINTR (lambda () expr)))
376 (define (syscall->procedure return-type name argument-types)
377 "Return a procedure that wraps the C function NAME using the dynamic FFI,
378 and that returns two values: NAME's return value, and errno.
380 If an error occurs while creating the binding, defer the error report until
381 the returned procedure is called."
384 (let ((ptr (dynamic-func name (dynamic-link))))
385 ;; The #:return-errno? facility was introduced in Guile 2.0.12.
386 (pointer->procedure return-type ptr argument-types
387 #:return-errno? #t)))
390 (throw 'system-error name "~A" (list (strerror ENOSYS))
393 (define-syntax define-as-needed
395 "Define VARIABLE. If VARIABLE already exists in (guile) then re-export it,
396 otherwise export the newly-defined VARIABLE."
397 ((_ (proc args ...) body ...)
398 (define-as-needed proc (lambda* (args ...) body ...)))
401 (when (module-defined? the-scm-module 'variable)
402 (re-export variable))
405 (if (module-defined? the-scm-module 'variable)
406 (module-ref the-scm-module 'variable)
409 (unless (module-defined? the-scm-module 'variable)
410 (export variable))))))
417 (define (augment-mtab source target type options)
418 "Augment /etc/mtab with information about the given mount point."
419 (let ((port (open-file "/etc/mtab" "a")))
420 (format port "~a ~a ~a ~a 0 0~%"
421 source target type (or options "rw"))
424 (define (read-mtab port)
425 "Read an mtab-formatted file from PORT, returning a list of tuples."
426 (let loop ((result '()))
427 (let ((line (read-line port)))
428 (if (eof-object? line)
430 (loop (cons (string-tokenize line) result))))))
432 (define (remove-from-mtab target)
433 "Remove mount point TARGET from /etc/mtab."
435 (remove (match-lambda
436 ((device mount-point type options freq passno)
437 (string=? target mount-point))
439 (call-with-input-file "/etc/mtab" read-mtab)))
441 (call-with-output-file "/etc/mtab"
443 (for-each (match-lambda
444 ((device mount-point type options freq passno)
445 (format port "~a ~a ~a ~a ~a ~a~%"
446 device mount-point type options freq passno)))
449 ;; Linux mount flags, from libc's <sys/mount.h>.
454 (define MS_REMOUNT 32)
455 (define MS_NOATIME 1024)
456 (define MS_BIND 4096)
457 (define MS_MOVE 8192)
458 (define MS_STRICTATIME 16777216)
461 (define MNT_DETACH 2)
462 (define MNT_EXPIRE 4)
463 (define UMOUNT_NOFOLLOW 8)
465 (define-as-needed (mount source target type
466 #:optional (flags 0) options
467 #:key (update-mtab? #f))
468 "Mount device SOURCE on TARGET as a file system TYPE.
469 Optionally, FLAGS may be a bitwise-or of the MS_* <sys/mount.h>
470 constants, and OPTIONS may be a string. When FLAGS contains
471 MS_REMOUNT, SOURCE and TYPE are ignored. When UPDATE-MTAB? is true,
472 update /etc/mtab. Raise a 'system-error' exception on error."
473 ;; XXX: '#:update-mtab?' is not implemented by core 'mount'.
474 (let ((proc (syscall->procedure int "mount" `(* * * ,unsigned-long *))))
475 (let-values (((ret err)
477 (string->pointer source)
479 (string->pointer target)
481 (string->pointer type)
485 (string->pointer options)
488 (throw 'system-error "mount" "mount ~S on ~S: ~A"
489 (list source target (strerror err))
492 (augment-mtab source target type options)))))
494 (define-as-needed (umount target
496 #:key (update-mtab? #f))
497 "Unmount TARGET. Optionally FLAGS may be one of the MNT_* or UMOUNT_*
498 constants from <sys/mount.h>."
499 ;; XXX: '#:update-mtab?' is not implemented by core 'umount'.
500 (let ((proc (syscall->procedure int "umount2" `(* ,int))))
501 (let-values (((ret err)
502 (proc (string->pointer target) flags)))
504 (throw 'system-error "umount" "~S: ~A"
505 (list target (strerror err))
508 (remove-from-mtab target)))))
510 (define (mount-points)
511 "Return the mounts points for currently mounted file systems."
512 (call-with-input-file "/proc/mounts"
514 (let loop ((result '()))
515 (let ((line (read-line port)))
516 (if (eof-object? line)
518 (match (string-tokenize line)
519 ((source mount-point _ ...)
520 (loop (cons mount-point result))))))))))
523 (let ((proc (syscall->procedure int "swapon" (list '* int))))
524 (lambda* (device #:optional (flags 0))
525 "Use the block special device at DEVICE for swapping."
526 (let-values (((ret err)
527 (proc (string->pointer device) flags)))
529 (throw 'system-error "swapon" "~S: ~A"
530 (list device (strerror err))
534 (let ((proc (syscall->procedure int "swapoff" '(*))))
536 "Stop using block special device DEVICE for swapping."
537 (let-values (((ret err) (proc (string->pointer device))))
539 (throw 'system-error "swapoff" "~S: ~A"
540 (list device (strerror err))
543 (define-as-needed RB_AUTOBOOT #x01234567)
544 (define-as-needed RB_HALT_SYSTEM #xcdef0123)
545 (define-as-needed RB_ENABLED_CAD #x89abcdef)
546 (define-as-needed RB_DISABLE_CAD 0)
547 (define-as-needed RB_POWER_OFF #x4321fedc)
548 (define-as-needed RB_SW_SUSPEND #xd000fce2)
549 (define-as-needed RB_KEXEC #x45584543)
551 (define-as-needed (reboot #:optional (cmd RB_AUTOBOOT))
552 (let ((proc (syscall->procedure int "reboot" (list int))))
553 (let-values (((ret err) (proc cmd)))
555 (throw 'system-error "reboot" "~S: ~A"
556 (list cmd (strerror err))
559 (define-as-needed (load-linux-module data #:optional (options ""))
560 (let ((proc (syscall->procedure int "init_module"
561 (list '* unsigned-long '*))))
562 (let-values (((ret err)
563 (proc (bytevector->pointer data)
564 (bytevector-length data)
565 (string->pointer options))))
567 (throw 'system-error "load-linux-module" "~A"
568 (list (strerror err))
571 (define (kernel? pid)
572 "Return #t if PID designates a \"kernel thread\" rather than a normal
574 (let ((stat (call-with-input-file (format #f "/proc/~a/stat" pid)
575 (compose string-tokenize read-string))))
576 ;; See proc.txt in Linux's documentation for the list of fields.
578 ((pid tcomm state ppid pgrp sid tty_nr tty_pgrp flags min_flt
579 cmin_flt maj_flt cmaj_flt utime stime cutime cstime
580 priority nice num_thread it_real_value start_time
582 (= string->number start_code) (= string->number end_code) _ ...)
583 ;; Got this obscure trick from sysvinit's 'killall5' program.
584 (and (zero? start_code) (zero? end_code))))))
587 "Return the list of live processes."
588 (sort (filter-map (lambda (file)
589 (let ((pid (string->number file)))
597 (let ((proc (syscall->procedure '* "mkdtemp" '(*))))
599 "Create a new unique directory in the file system using the template
600 string TMPL and return its file name. TMPL must end with 'XXXXXX'."
601 (let-values (((result err) (proc (string->pointer tmpl))))
602 (when (null-pointer? result)
603 (throw 'system-error "mkdtemp!" "~S: ~A"
604 (list tmpl (strerror err))
606 (pointer->string result)))))
609 (let ((proc (syscall->procedure int "fdatasync" (list int))))
611 "Flush buffered output of PORT, an output file port, and then call
612 fdatasync(2) on the underlying file descriptor."
614 (let*-values (((fd) (fileno port))
615 ((ret err) (proc fd)))
617 (throw 'system-error "fdatasync" "~S: ~A"
618 (list fd (strerror err))
622 (define-record-type <file-system>
623 (file-system type block-size blocks blocks-free
624 blocks-available files free-files identifier
625 name-length fragment-size mount-flags spare)
627 (type file-system-type)
628 (block-size file-system-block-size)
629 (blocks file-system-block-count)
630 (blocks-free file-system-blocks-free)
631 (blocks-available file-system-blocks-available)
632 (files file-system-file-count)
633 (free-files file-system-free-file-nodes)
634 (identifier file-system-identifier)
635 (name-length file-system-maximum-name-length)
636 (fragment-size file-system-fragment-size)
637 (mount-flags file-system-mount-flags)
638 (spare file-system--spare))
640 (define-syntax fsword ;fsword_t
641 (identifier-syntax long))
643 (define-c-struct %statfs ;<bits/statfs.h>
644 sizeof-statfs ;slightly overestimated
652 (blocks-available uint64)
655 (identifier (array int 2))
657 (fragment-size fsword)
659 (spare (array fsword 4)))
662 (let ((proc (syscall->procedure int "statfs64" '(* *))))
664 "Return a <file-system> data structure describing the file system
666 (let*-values (((stat) (make-bytevector sizeof-statfs))
667 ((ret err) (proc (string->pointer file)
668 (bytevector->pointer stat))))
671 (throw 'system-error "statfs" "~A: ~A"
672 (list file (strerror err))
675 (define (free-disk-space file)
676 "Return the free disk space, in bytes, on the file system that hosts FILE."
677 (let ((fs (statfs file)))
678 (* (file-system-block-size fs)
679 (file-system-blocks-available fs))))
681 ;; Flags for the *at command, notably the 'utime' procedure of libguile.
683 (define AT_FDCWD -100)
684 (define AT_SYMLINK_NOFOLLOW #x100)
685 (define AT_REMOVEDIR #x200)
686 (define AT_SYMLINK_FOLLOW #x400)
687 (define AT_NO_AUTOMOUNT #x800)
688 (define AT_EMPTY_PATH #x1000)
690 (define-syntax BLKRRPART ;<sys/mount.h>
691 (identifier-syntax #x125F))
693 (define* (device-in-use? device)
694 "Return #t if the block DEVICE is in use, #f otherwise. This is inspired
695 from fdisk_device_is_used function of util-linux. This is particulary useful
696 for devices that do not appear in /proc/self/mounts like overlayfs lowerdir
698 (let*-values (((fd) (open-fdes device O_RDONLY))
699 ((ret err) (%ioctl fd BLKRRPART %null-pointer)))
707 ;; We get EINVAL for devices that have the GENHD_FL_NO_PART_SCAN flag
708 ;; set in the kernel, in particular loopback devices, though we do seem
709 ;; to get it for SCSI storage (/dev/sr0) on QEMU.
712 (throw 'system-error "ioctl" "~A"
713 (list (strerror err))
721 ;; Linux clone flags, from linux/sched.h
722 (define CLONE_CHILD_CLEARTID #x00200000)
723 (define CLONE_CHILD_SETTID #x01000000)
724 (define CLONE_NEWNS #x00020000)
725 (define CLONE_NEWUTS #x04000000)
726 (define CLONE_NEWIPC #x08000000)
727 (define CLONE_NEWUSER #x10000000)
728 (define CLONE_NEWPID #x20000000)
729 (define CLONE_NEWNET #x40000000)
731 (define %set-automatic-finalization-enabled?!
732 ;; When using a statically-linked Guile, for instance in the initrd, we
733 ;; cannot resolve this symbol, but most of the time we don't need it
734 ;; anyway. Thus, delay it.
736 (pointer->procedure int
738 "scm_set_automatic_finalization_enabled"
742 "Switch on or off automatic finalization in a separate thread.
743 Turning finalization off shuts down the finalization thread as a side effect."
744 (->bool ((force proc) (if enabled? 1 0))))))
746 (define-syntax-rule (without-automatic-finalization exp)
747 "Turn off automatic finalization within the dynamic extent of EXP."
751 (set! enabled? (%set-automatic-finalization-enabled?! #f)))
755 (%set-automatic-finalization-enabled?! enabled?)))))
757 ;; The libc interface to sys_clone is not useful for Scheme programs, so the
758 ;; low-level system call is wrapped instead. The 'syscall' function is
759 ;; declared in <unistd.h> as a variadic function; in practice, it expects 6
760 ;; pointer-sized arguments, as shown in, e.g., x86_64/syscall.S.
762 (let* ((proc (syscall->procedure int "syscall"
767 ;; TODO: Don't do this.
768 (syscall-id (match (utsname:machine (uname))
776 "Create a new child process by duplicating the current parent process.
777 Unlike the fork system call, clone accepts FLAGS that specify which resources
778 are shared between the parent and child processes."
779 (let-values (((ret err)
780 ;; Guile 2.2 runs a finalization thread. 'primitive-fork'
781 ;; takes care of shutting it down before forking, and we
782 ;; must do the same here. Failing to do that, if the
783 ;; child process calls 'primitive-fork', it will hang
784 ;; while trying to pthread_join the finalization thread
785 ;; since that thread does not exist.
786 (without-automatic-finalization
787 (proc syscall-id flags
788 %null-pointer ;child stack
789 %null-pointer %null-pointer ;ptid & ctid
790 %null-pointer)))) ;unused
792 (throw 'system-error "clone" "~d: ~A"
793 (list flags (strerror err))
798 ;; Some systems may be using an old (pre-2.14) version of glibc where there
799 ;; is no 'setns' function available.
801 (let ((proc (syscall->procedure int "setns" (list int int))))
802 (lambda (fdes nstype)
803 "Reassociate the current process with the namespace specified by FDES, a
804 file descriptor obtained by opening a /proc/PID/ns/* file. NSTYPE specifies
805 which type of namespace the current process may be reassociated with, or 0 if
806 there is no such limitation."
807 (let-values (((ret err) (proc fdes nstype)))
809 (throw 'system-error "setns" "~d ~d: ~A"
810 (list fdes nstype (strerror err))
814 (let ((proc (syscall->procedure int "pivot_root" (list '* '*))))
815 (lambda (new-root put-old)
816 "Change the root file system to NEW-ROOT and move the current root file
818 (let-values (((ret err)
819 (proc (string->pointer new-root)
820 (string->pointer put-old))))
822 (throw 'system-error "pivot_root" "~S ~S: ~A"
823 (list new-root put-old (strerror err))
831 (define (file-type->symbol type)
832 ;; Convert TYPE to symbols like 'stat:type' does.
833 (cond ((= type DT_REG) 'regular)
834 ((= type DT_LNK) 'symlink)
835 ((= type DT_DIR) 'directory)
836 ((= type DT_FIFO) 'fifo)
837 ((= type DT_CHR) 'char-special)
838 ((= type DT_BLK) 'block-special)
839 ((= type DT_SOCK) 'socket)
842 ;; 'struct dirent64' for GNU/Linux.
843 (define-c-struct %struct-dirent-header/linux
844 sizeof-dirent-header/linux
845 (lambda (inode offset length type name)
846 `((type . ,(file-type->symbol type))
848 read-dirent-header/linux
849 write-dirent-header!/linux
852 (length unsigned-short)
854 (name uint8)) ;first byte of 'd_name'
856 ;; 'struct dirent64' for GNU/Hurd.
857 (define-c-struct %struct-dirent-header/hurd
858 sizeof-dirent-header/hurd
859 (lambda (inode length type name-length name)
860 `((type . ,(file-type->symbol type))
862 read-dirent-header/hurd
863 write-dirent-header!/hurd
865 (length unsigned-short)
870 (define-syntax define-generic-identifier
871 (syntax-rules (gnu/linux gnu/hurd =>)
872 "Define a generic identifier that adjust to the current GNU variant."
873 ((_ id (gnu/linux => linux) (gnu/hurd => hurd))
878 (if (string-contains (or (target-type) %host-type)
880 #'(linux args (... ...))
881 #'(hurd args (... ...))))
883 (if (string-contains (or (target-type) %host-type)
888 (define-generic-identifier read-dirent-header
889 (gnu/linux => read-dirent-header/linux)
890 (gnu/hurd => read-dirent-header/hurd))
892 (define-generic-identifier %struct-dirent-header
893 (gnu/linux => %struct-dirent-header/linux)
894 (gnu/hurd => %struct-dirent-header/hurd))
896 (define-generic-identifier sizeof-dirent-header
897 (gnu/linux => sizeof-dirent-header/linux)
898 (gnu/hurd => sizeof-dirent-header/hurd))
900 ;; Constants for the 'type' field, from <dirent.h>.
901 (define DT_UNKNOWN 0)
911 (define string->pointer/utf-8
912 (cut string->pointer <> "UTF-8"))
914 (define pointer->string/utf-8
915 (cut pointer->string <> <> "UTF-8"))
918 (let ((proc (syscall->procedure '* "opendir" '(*))))
919 (lambda* (name #:optional (string->pointer string->pointer/utf-8))
920 (let-values (((ptr err)
921 (proc (string->pointer name))))
922 (if (null-pointer? ptr)
923 (throw 'system-error "opendir*"
924 "~A: ~A" (list name (strerror err))
929 (let ((proc (syscall->procedure int "closedir" '(*))))
931 (let-values (((ret err)
934 (throw 'system-error "closedir"
935 "closedir: ~A" (list (strerror err))
939 (let ((proc (syscall->procedure '* "readdir64" '(*))))
940 (lambda* (directory #:optional (pointer->string pointer->string/utf-8))
941 (let ((ptr (proc directory)))
942 (and (not (null-pointer? ptr))
943 (cons (pointer->string
944 (make-pointer (+ (pointer-address ptr)
945 (c-struct-field-offset
946 %struct-dirent-header name)))
949 (pointer->bytevector ptr sizeof-dirent-header))))))))
951 (define* (scandir* name #:optional
953 (entry<? (lambda (entry1 entry2)
958 (string<? name1 name2)))))))
960 (string->pointer string->pointer/utf-8)
961 (pointer->string pointer->string/utf-8))
962 "This procedure improves on Guile's 'scandir' procedure in several ways:
964 1. Systematically encode decode file names using STRING->POINTER and
965 POINTER->STRING (UTF-8 by default; this works around a defect in Guile 2.0/2.2
966 where 'scandir' decodes file names according to the current locale, which is
967 not always desirable.
969 2. Each entry that is returned has the form (NAME . PROPERTIES).
970 PROPERTIES is an alist showing additional properties about the entry, as
971 found in 'struct dirent'. An entry may look like this:
973 (\"foo.scm\" (type . regular) (inode . 123456))
975 Callers must be prepared to deal with the case where 'type' is 'unknown'
976 since some file systems do not provide that information.
978 3. Raise to 'system-error' when NAME cannot be opened."
979 (let ((directory (opendir* name string->pointer)))
983 (let loop ((result '()))
984 (match (readdir* directory pointer->string)
986 (sort result entry<?))
988 (loop (if (select? entry)
992 (closedir* directory)))))
996 ;;; Advisory file locking.
999 (define-c-struct %struct-flock ;<fcntl.h>
1011 ;; On Linux-based systems, this is usually 7, but not always
1012 ;; (exceptions include SPARC.) On GNU/Hurd, it's 9.
1013 (cond ((string-contains %host-type "sparc") 9) ; sparc-*-linux-gnu
1014 ((string-contains %host-type "linux") 7) ; *-linux-gnu
1018 ;; Likewise: GNU/Hurd and SPARC use 8, while the others typically use 6.
1019 (cond ((string-contains %host-type "sparc") 8) ; sparc-*-linux-gnu
1020 ((string-contains %host-type "linux") 6) ; *-linux-gnu
1024 ;; The F_RDLCK, F_WRLCK, and F_UNLCK constants.
1025 (cond ((string-contains %host-type "sparc") #(1 2 3)) ; sparc-*-linux-gnu
1026 ((string-contains %host-type "hppa") #(1 2 3)) ; hppa-*-linux-gnu
1027 ((string-contains %host-type "linux") #(0 1 2)) ; *-linux-gnu
1028 (else #(1 2 3)))) ; *-gnu*
1031 (let ((proc (syscall->procedure int "fcntl" `(,int ,int *))))
1032 (lambda* (fd-or-port operation #:key (wait? #t))
1033 "Perform locking OPERATION on the file beneath FD-OR-PORT. OPERATION
1034 must be a symbol, one of 'read-lock, 'write-lock, or 'unlock. When WAIT? is
1035 true, block until the lock is acquired; otherwise, thrown an 'flock-error'
1036 exception if it's already taken."
1037 (define (operation->int op)
1039 ((read-lock) (vector-ref F_xxLCK 0))
1040 ((write-lock) (vector-ref F_xxLCK 1))
1041 ((unlock) (vector-ref F_xxLCK 2))
1042 (else (error "invalid fcntl-flock operation" op))))
1045 (if (port? fd-or-port)
1050 (make-bytevector sizeof-flock))
1053 (operation->int operation) SEEK_SET
1057 ;; XXX: 'fcntl' is a vararg function, but here we happily use the
1058 ;; standard ABI; crossing fingers.
1059 (let-values (((ret err)
1062 F_SETLKW ;lock & wait
1063 F_SETLK) ;non-blocking attempt
1064 (bytevector->pointer bv))))
1066 ;; Presumably we got EAGAIN or so.
1067 (throw 'flock-error err))))))
1071 ;;; Miscellaneous, aka. 'prctl'.
1075 ;; Should it win the API contest against 'ioctl'? You tell us!
1076 (syscall->procedure int "prctl"
1077 (list int unsigned-long unsigned-long
1078 unsigned-long unsigned-long)))
1080 (define PR_SET_NAME 15) ;<linux/prctl.h>
1081 (define PR_GET_NAME 16)
1083 (define %max-thread-name-length
1084 ;; Maximum length in bytes of the process name, including the terminating
1088 (define (set-thread-name name)
1089 "Set the name of the calling thread to NAME. NAME is truncated to 15
1091 (let ((ptr (string->pointer name)))
1092 (let-values (((ret err)
1094 (pointer-address ptr) 0 0 0)))
1096 (throw 'set-process-name "set-process-name"
1097 "set-process-name: ~A"
1098 (list (strerror err))
1101 (define (thread-name)
1102 "Return the name of the calling thread as a string."
1103 (let ((buf (make-bytevector %max-thread-name-length)))
1104 (let-values (((ret err)
1106 (pointer-address (bytevector->pointer buf))
1109 (bytes->string (bytevector->u8-list buf))
1110 (throw 'process-name "process-name"
1112 (list (strerror err))
1117 ;;; Network interfaces.
1120 (define SIOCGIFCONF ;from <bits/ioctls.h>
1121 (if (string-contains %host-type "linux")
1123 #xf00801a4)) ;GNU/Hurd
1124 (define SIOCGIFFLAGS
1125 (if (string-contains %host-type "linux")
1127 #xc4804191)) ;GNU/Hurd
1128 (define SIOCSIFFLAGS
1129 (if (string-contains %host-type "linux")
1131 -1)) ;FIXME: GNU/Hurd?
1133 (if (string-contains %host-type "linux")
1135 -1)) ;FIXME: GNU/Hurd?
1137 (if (string-contains %host-type "linux")
1139 -1)) ;FIXME: GNU/Hurd?
1140 (define SIOCGIFNETMASK
1141 (if (string-contains %host-type "linux")
1143 -1)) ;FIXME: GNU/Hurd?
1144 (define SIOCSIFNETMASK
1145 (if (string-contains %host-type "linux")
1147 -1)) ;FIXME: GNU/Hurd?
1149 (if (string-contains %host-type "linux")
1151 -1)) ;FIXME: GNU/Hurd?
1153 (if (string-contains %host-type "linux")
1155 -1)) ;FIXME: GNU/Hurd?
1157 ;; Flags and constants from <net/if.h>.
1159 (define-as-needed IFF_UP #x1) ;Interface is up
1160 (define-as-needed IFF_BROADCAST #x2) ;Broadcast address valid.
1161 (define-as-needed IFF_LOOPBACK #x8) ;Is a loopback net.
1162 (define-as-needed IFF_RUNNING #x40) ;interface RFC2863 OPER_UP
1164 (define IF_NAMESIZE 16) ;maximum interface name size
1166 (define-c-struct %ifconf-struct
1171 (length int) ;int ifc_len
1172 (request '*)) ;struct ifreq *ifc_ifcu
1174 (define ifreq-struct-size
1175 ;; 'struct ifreq' begins with an array of IF_NAMESIZE bytes containing the
1176 ;; interface name (nul-terminated), followed by a bunch of stuff. This is
1177 ;; its size in bytes.
1178 (if (= 8 (sizeof '*))
1182 (define-c-struct sockaddr-in ;<linux/in.h>
1184 (lambda (family port address)
1185 (make-socket-address family address port))
1188 (family unsigned-short)
1189 (port (int16 ~ big))
1190 (address (int32 ~ big)))
1192 (define-c-struct sockaddr-in6 ;<linux/in6.h>
1194 (lambda (family port flowinfo address scopeid)
1195 (make-socket-address family address port flowinfo scopeid))
1198 (family unsigned-short)
1199 (port (int16 ~ big))
1200 (flowinfo (int32 ~ big))
1201 (address (int128 ~ big))
1204 (define (write-socket-address! sockaddr bv index)
1205 "Write SOCKADDR, a socket address as returned by 'make-socket-address', to
1206 bytevector BV at INDEX."
1207 (let ((family (sockaddr:fam sockaddr)))
1208 (cond ((= family AF_INET)
1209 (write-sockaddr-in! bv index
1211 (sockaddr:port sockaddr)
1212 (sockaddr:addr sockaddr)))
1213 ((= family AF_INET6)
1214 (write-sockaddr-in6! bv index
1216 (sockaddr:port sockaddr)
1217 (sockaddr:flowinfo sockaddr)
1218 (sockaddr:addr sockaddr)
1219 (sockaddr:scopeid sockaddr)))
1221 (error "unsupported socket address" sockaddr)))))
1223 (define PF_PACKET 17) ;<bits/socket.h>
1224 (define AF_PACKET PF_PACKET)
1226 (define* (read-socket-address bv #:optional (index 0))
1227 "Read a socket address from bytevector BV at INDEX."
1228 (let ((family (bytevector-u16-native-ref bv index)))
1229 (cond ((= family AF_INET)
1230 (read-sockaddr-in bv index))
1231 ((= family AF_INET6)
1232 (read-sockaddr-in6 bv index))
1234 ;; XXX: Unsupported address family, such as AF_PACKET. Return a
1235 ;; vector such that the vector can at least call 'sockaddr:fam'.
1239 ;; The most terrible interface, live from Scheme.
1240 (syscall->procedure int "ioctl" (list int unsigned-long '*)))
1242 (define (bytes->string bytes)
1243 "Read BYTES, a list of bytes, and return the null-terminated string decoded
1244 from there, or #f if that would be an empty string."
1245 (match (take-while (negate zero?) bytes)
1249 (list->string (map integer->char non-zero)))))
1251 (define (bytevector->string-list bv stride len)
1252 "Return the null-terminated strings found in BV every STRIDE bytes. Read at
1253 most LEN bytes from BV."
1254 (let loop ((bytes (take (bytevector->u8-list bv)
1255 (min len (bytevector-length bv))))
1261 (loop (drop bytes stride)
1262 (cons (bytes->string bytes) result))))))
1264 (define* (network-interface-names #:optional sock)
1265 "Return the names of existing network interfaces. This is typically limited
1266 to interfaces that are currently up."
1267 (let* ((close? (not sock))
1268 (sock (or sock (socket SOCK_STREAM AF_INET 0)))
1269 (len (* ifreq-struct-size 10))
1270 (reqs (make-bytevector len))
1271 (conf (make-bytevector sizeof-ifconf)))
1272 (write-ifconf! conf 0
1273 len (bytevector->pointer reqs))
1275 (let-values (((ret err)
1276 (%ioctl (fileno sock) SIOCGIFCONF
1277 (bytevector->pointer conf))))
1281 (bytevector->string-list reqs ifreq-struct-size
1282 (match (read-ifconf conf)
1284 (throw 'system-error "network-interface-list"
1285 "network-interface-list: ~A"
1286 (list (strerror err))
1289 (define %interface-line
1290 ;; Regexp matching an interface line in Linux's /proc/net/dev.
1291 (make-regexp "^[[:blank:]]*([[:graph:]]+):.*$"))
1293 (define (all-network-interface-names)
1294 "Return all the names of the registered network interfaces, including those
1296 (call-with-input-file "/proc/net/dev" ;XXX: Linux-specific
1298 (let loop ((interfaces '()))
1299 (let ((line (read-line port)))
1300 (cond ((eof-object? line)
1301 (reverse interfaces))
1302 ((regexp-exec %interface-line line)
1305 (loop (cons (match:substring match 1) interfaces))))
1307 (loop interfaces))))))))
1309 (define-as-needed (network-interface-flags socket name)
1310 "Return a number that is the bit-wise or of 'IFF*' flags for network
1312 (let ((req (make-bytevector ifreq-struct-size)))
1313 (bytevector-copy! (string->utf8 name) 0 req 0
1314 (min (string-length name) (- IF_NAMESIZE 1)))
1315 (let-values (((ret err)
1316 (%ioctl (fileno socket) SIOCGIFFLAGS
1317 (bytevector->pointer req))))
1320 ;; The 'ifr_flags' field is IF_NAMESIZE bytes after the
1321 ;; beginning of 'struct ifreq', and it's a short int.
1322 (bytevector-sint-ref req IF_NAMESIZE (native-endianness)
1325 (throw 'system-error "network-interface-flags"
1326 "network-interface-flags on ~A: ~A"
1327 (list name (strerror err))
1330 (define (loopback-network-interface? name)
1331 "Return true if NAME designates a loopback network interface."
1332 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1333 (flags (network-interface-flags sock name)))
1335 (not (zero? (logand flags IFF_LOOPBACK)))))
1337 (define (network-interface-running? name)
1338 "Return true if NAME designates a running network interface."
1339 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1340 (flags (network-interface-flags sock name)))
1342 (not (zero? (logand flags IFF_RUNNING)))))
1344 (define-as-needed (set-network-interface-flags socket name flags)
1345 "Set the flag of network interface NAME to FLAGS."
1346 (let ((req (make-bytevector ifreq-struct-size)))
1347 (bytevector-copy! (string->utf8 name) 0 req 0
1348 (min (string-length name) (- IF_NAMESIZE 1)))
1349 ;; Set the 'ifr_flags' field.
1350 (bytevector-uint-set! req IF_NAMESIZE flags (native-endianness)
1352 (let-values (((ret err)
1353 (%ioctl (fileno socket) SIOCSIFFLAGS
1354 (bytevector->pointer req))))
1356 (throw 'system-error "set-network-interface-flags"
1357 "set-network-interface-flags on ~A: ~A"
1358 (list name (strerror err))
1361 (define-as-needed (set-network-interface-address socket name sockaddr)
1362 "Set the address of network interface NAME to SOCKADDR."
1363 (let ((req (make-bytevector ifreq-struct-size)))
1364 (bytevector-copy! (string->utf8 name) 0 req 0
1365 (min (string-length name) (- IF_NAMESIZE 1)))
1366 ;; Set the 'ifr_addr' field.
1367 (write-socket-address! sockaddr req IF_NAMESIZE)
1368 (let-values (((ret err)
1369 (%ioctl (fileno socket) SIOCSIFADDR
1370 (bytevector->pointer req))))
1372 (throw 'system-error "set-network-interface-address"
1373 "set-network-interface-address on ~A: ~A"
1374 (list name (strerror err))
1377 (define (set-network-interface-netmask socket name sockaddr)
1378 "Set the network mask of interface NAME to SOCKADDR."
1379 (let ((req (make-bytevector ifreq-struct-size)))
1380 (bytevector-copy! (string->utf8 name) 0 req 0
1381 (min (string-length name) (- IF_NAMESIZE 1)))
1382 ;; Set the 'ifr_addr' field.
1383 (write-socket-address! sockaddr req IF_NAMESIZE)
1384 (let-values (((ret err)
1385 (%ioctl (fileno socket) SIOCSIFNETMASK
1386 (bytevector->pointer req))))
1388 (throw 'system-error "set-network-interface-netmask"
1389 "set-network-interface-netmask on ~A: ~A"
1390 (list name (strerror err))
1393 (define (network-interface-address socket name)
1394 "Return the address of network interface NAME. The result is an object of
1395 the same type as that returned by 'make-socket-address'."
1396 (let ((req (make-bytevector ifreq-struct-size)))
1397 (bytevector-copy! (string->utf8 name) 0 req 0
1398 (min (string-length name) (- IF_NAMESIZE 1)))
1399 (let-values (((ret err)
1400 (%ioctl (fileno socket) SIOCGIFADDR
1401 (bytevector->pointer req))))
1403 (read-socket-address req IF_NAMESIZE)
1404 (throw 'system-error "network-interface-address"
1405 "network-interface-address on ~A: ~A"
1406 (list name (strerror err))
1409 (define (network-interface-netmask socket name)
1410 "Return the netmask of network interface NAME. The result is an object of
1411 the same type as that returned by 'make-socket-address'."
1412 (let ((req (make-bytevector ifreq-struct-size)))
1413 (bytevector-copy! (string->utf8 name) 0 req 0
1414 (min (string-length name) (- IF_NAMESIZE 1)))
1415 (let-values (((ret err)
1416 (%ioctl (fileno socket) SIOCGIFNETMASK
1417 (bytevector->pointer req))))
1419 (read-socket-address req IF_NAMESIZE)
1420 (throw 'system-error "network-interface-netmask"
1421 "network-interface-netmask on ~A: ~A"
1422 (list name (strerror err))
1425 (define* (configure-network-interface name sockaddr flags
1427 "Configure network interface NAME to use SOCKADDR, an address as returned by
1428 'make-socket-address', and FLAGS, a bitwise-or of IFF_* constants. If NETMASK
1429 is true, it must be a socket address to use as the network mask."
1430 (let ((sock (socket (sockaddr:fam sockaddr) SOCK_STREAM 0)))
1434 (set-network-interface-address sock name sockaddr)
1435 (set-network-interface-flags sock name flags)
1437 (set-network-interface-netmask sock name netmask)))
1439 (close-port sock)))))
1441 (define* (set-network-interface-up name
1442 #:key (family AF_INET))
1443 "Turn up the interface NAME."
1444 (let ((sock (socket family SOCK_STREAM 0)))
1448 (let ((flags (network-interface-flags sock name)))
1449 (set-network-interface-flags sock name
1450 (logior flags IFF_UP))))
1452 (close-port sock)))))
1459 (define-c-struct %rtentry ;'struct rtentry' from <net/route.h>
1464 (pad1 unsigned-long)
1465 (destination (array uint8 16)) ;struct sockaddr
1466 (gateway (array uint8 16)) ;struct sockaddr
1467 (genmask (array uint8 16)) ;struct sockaddr
1468 (flags unsigned-short)
1473 (pad4 (array uint8 (if (= 8 (sizeof* '*)) 3 1)))
1477 (window unsigned-long)
1478 (initial-rtt unsigned-short))
1480 (define RTF_UP #x0001) ;'rtentry' flags from <net/route.h>
1481 (define RTF_GATEWAY #x0002)
1483 (define %sockaddr-any
1484 (make-socket-address AF_INET INADDR_ANY 0))
1486 (define add-network-route/gateway
1487 ;; To allow field names to be matched as literals, we need to move them out
1488 ;; of the lambda's body since the parameters have the same name. A lot of
1489 ;; fuss for very little.
1490 (let-syntax ((gateway-offset (identifier-syntax
1491 (c-struct-field-offset %rtentry gateway)))
1492 (destination-offset (identifier-syntax
1493 (c-struct-field-offset %rtentry destination)))
1494 (genmask-offset (identifier-syntax
1495 (c-struct-field-offset %rtentry genmask))))
1496 (lambda* (socket gateway
1497 #:key (destination %sockaddr-any) (genmask %sockaddr-any))
1498 "Add a network route for DESTINATION (a socket address as returned by
1499 'make-socket-address') that goes through GATEWAY (a socket address). For
1502 (add-network-route/gateway sock
1503 (make-socket-address
1505 (inet-pton AF_INET \"192.168.0.1\")
1508 is equivalent to this 'net-tools' command:
1510 route add -net default gw 192.168.0.1
1512 because the default value of DESTINATION is \"0.0.0.0\"."
1513 (let ((route (make-bytevector sizeof-rtentry 0)))
1514 (write-socket-address! gateway route gateway-offset)
1515 (write-socket-address! destination route destination-offset)
1516 (write-socket-address! genmask route genmask-offset)
1517 (bytevector-u16-native-set! route
1518 (c-struct-field-offset %rtentry flags)
1519 (logior RTF_UP RTF_GATEWAY))
1520 (let-values (((ret err)
1521 (%ioctl (fileno socket) SIOCADDRT
1522 (bytevector->pointer route))))
1524 (throw 'system-error "add-network-route/gateway"
1525 "add-network-route/gateway: ~A"
1526 (list (strerror err))
1529 (define delete-network-route
1530 (let-syntax ((destination-offset (identifier-syntax
1531 (c-struct-field-offset %rtentry destination))))
1532 (lambda* (socket destination)
1533 "Delete the network route for DESTINATION. For instance, the call:
1535 (delete-network-route sock
1536 (make-socket-address AF_INET INADDR_ANY 0))
1538 is equivalent to the 'net-tools' command:
1540 route del -net default
1543 (let ((route (make-bytevector sizeof-rtentry 0)))
1544 (write-socket-address! destination route destination-offset)
1545 (let-values (((ret err)
1546 (%ioctl (fileno socket) SIOCDELRT
1547 (bytevector->pointer route))))
1549 (throw 'system-error "delete-network-route"
1550 "delete-network-route: ~A"
1551 (list (strerror err))
1556 ;;; Details about network interfaces---aka. 'getifaddrs'.
1559 ;; Network interfaces. XXX: We would call it <network-interface> but that
1560 ;; would collide with the ioctl wrappers above.
1561 (define-record-type <interface>
1562 (make-interface name flags address netmask broadcast-address)
1564 (name interface-name) ;string
1565 (flags interface-flags) ;or'd IFF_* values
1566 (address interface-address) ;sockaddr | #f
1567 (netmask interface-netmask) ;sockaddr | #f
1568 (broadcast-address interface-broadcast-address)) ;sockaddr | #f
1570 (define (write-interface interface port)
1572 (($ <interface> name flags address)
1573 (format port "#<interface ~s " name)
1574 (unless (zero? (logand IFF_UP flags))
1575 (display "up " port))
1577 ;; Check whether ADDRESS really is a sockaddr.
1579 (if (member (sockaddr:fam address) (list AF_INET AF_INET6))
1580 (format port "~a " (inet-ntop (sockaddr:fam address)
1581 (sockaddr:addr address)))
1582 (format port "family:~a " (sockaddr:fam address))))
1584 (format port "~a>" (number->string (object-address interface) 16)))))
1586 (set-record-type-printer! <interface> write-interface)
1588 (define (values->interface next name flags address netmask
1589 broadcast-address data)
1590 "Given the raw field values passed as arguments, return a pair whose car is
1591 an <interface> object, and whose cdr is the pointer NEXT."
1592 (define (maybe-socket-address pointer)
1593 (if (null-pointer? pointer)
1595 (read-socket-address (pointer->bytevector pointer 50)))) ;XXX: size
1597 (cons (make-interface (if (null-pointer? name)
1599 (pointer->string name))
1601 (maybe-socket-address address)
1602 (maybe-socket-address netmask)
1603 (maybe-socket-address broadcast-address)
1608 (define-c-struct ifaddrs ;<ifaddrs.h>
1615 (flags unsigned-int)
1621 (define (unfold-interface-list ptr)
1622 "Call 'read-ifaddrs' on PTR and all its 'next' fields, recursively, and
1623 return the list of resulting <interface> objects."
1624 (let loop ((ptr ptr)
1626 (if (null-pointer? ptr)
1628 (match (read-ifaddrs (pointer->bytevector ptr %sizeof-ifaddrs))
1630 (loop ptr (cons ifaddr result)))))))
1632 (define network-interfaces
1633 (let ((proc (syscall->procedure int "getifaddrs" (list '*))))
1635 "Return a list of <interface> objects, each denoting a configured
1636 network interface. This is implemented using the 'getifaddrs' libc function."
1637 (let*-values (((ptr)
1638 (bytevector->pointer (make-bytevector (sizeof* '*))))
1642 (let* ((ptr (dereference-pointer ptr))
1643 (result (unfold-interface-list ptr)))
1646 (throw 'system-error "network-interfaces" "~A"
1647 (list (strerror err))
1650 (define free-ifaddrs
1651 (syscall->procedure void "freeifaddrs" '(*)))
1658 (define-syntax bits->symbols-body
1662 ((_ bits (name names ...) (value values ...))
1663 (let ((result (bits->symbols-body bits (names ...) (values ...))))
1664 (if (zero? (logand bits value))
1666 (cons 'name result))))))
1668 (define-syntax define-bits
1669 (syntax-rules (define)
1670 "Define the given numerical constants under CONSTRUCTOR, such that
1671 (CONSTRUCTOR NAME) returns VALUE. Define BITS->SYMBOLS as a procedure that,
1672 given an integer, returns the list of names of the constants that are or'd."
1673 ((_ constructor bits->symbols (define names values) ...)
1675 (define-syntax constructor
1676 (syntax-rules (names ...)
1678 ((_ names) values) ...
1679 ((_ first rest (... ...))
1680 (logior (constructor first) rest (... ...)))))
1681 (define (bits->symbols bits)
1682 (bits->symbols-body bits (names ...) (values ...)))))))
1684 ;; 'local-flags' bits from <bits/termios.h>
1685 (define-bits local-flags
1686 local-flags->symbols
1687 (define ISIG #o0000001)
1688 (define ICANON #o0000002)
1689 (define XCASE #o0000004)
1690 (define ECHO #o0000010)
1691 (define ECHOE #o0000020)
1692 (define ECHOK #o0000040)
1693 (define ECHONL #o0000100)
1694 (define NOFLSH #o0000200)
1695 (define TOSTOP #o0000400)
1696 (define ECHOCTL #o0001000)
1697 (define ECHOPRT #o0002000)
1698 (define ECHOKE #o0004000)
1699 (define FLUSHO #o0010000)
1700 (define PENDIN #o0040000)
1701 (define IEXTEN #o0100000)
1702 (define EXTPROC #o0200000))
1704 (define-bits input-flags
1705 input-flags->symbols
1706 (define IGNBRK #o0000001)
1707 (define BRKINT #o0000002)
1708 (define IGNPAR #o0000004)
1709 (define PARMRK #o0000010)
1710 (define INPCK #o0000020)
1711 (define ISTRIP #o0000040)
1712 (define INLCR #o0000100)
1713 (define IGNCR #o0000200)
1714 (define ICRNL #o0000400)
1715 (define IUCLC #o0001000)
1716 (define IXON #o0002000)
1717 (define IXANY #o0004000)
1718 (define IXOFF #o0010000)
1719 (define IMAXBEL #o0020000)
1720 (define IUTF8 #o0040000))
1722 ;; "Actions" values for 'tcsetattr'.
1723 (define-bits tcsetattr-action
1724 %unused-tcsetattr-action->symbols
1726 (define TCSADRAIN 1)
1727 (define TCSAFLUSH 2))
1729 (define-record-type <termios>
1730 (termios input-flags output-flags control-flags local-flags
1731 line-discipline control-chars
1732 input-speed output-speed)
1734 (input-flags termios-input-flags)
1735 (output-flags termios-output-flags)
1736 (control-flags termios-control-flags)
1737 (local-flags termios-local-flags)
1738 (line-discipline termios-line-discipline)
1739 (control-chars termios-control-chars)
1740 (input-speed termios-input-speed)
1741 (output-speed termios-output-speed))
1743 (define-c-struct %termios ;<bits/termios.h>
1748 (input-flags unsigned-int)
1749 (output-flags unsigned-int)
1750 (control-flags unsigned-int)
1751 (local-flags unsigned-int)
1752 (line-discipline uint8)
1753 (control-chars (array uint8 32))
1754 (input-speed unsigned-int)
1755 (output-speed unsigned-int))
1758 (let ((proc (syscall->procedure int "tcgetattr" (list int '*))))
1760 "Return the <termios> structure for the tty at FD."
1761 (let*-values (((bv) (make-bytevector sizeof-termios))
1762 ((ret err) (proc fd (bytevector->pointer bv))))
1765 (throw 'system-error "tcgetattr" "~A"
1766 (list (strerror err))
1770 (let ((proc (syscall->procedure int "tcsetattr" (list int int '*))))
1771 (lambda (fd actions termios)
1772 "Use TERMIOS for the tty at FD. ACTIONS is one of of the values
1773 produced by 'tcsetattr-action'; see tcsetattr(3) for details."
1775 (make-bytevector sizeof-termios))
1777 (let-syntax ((match/write (syntax-rules ()
1780 (($ <termios> fields ...)
1781 (write-termios! bv 0 fields ...)))))))
1782 (match/write input-flags output-flags control-flags local-flags
1783 line-discipline control-chars input-speed output-speed))
1785 (let-values (((ret err) (proc fd actions (bytevector->pointer bv))))
1787 (throw 'system-error "tcgetattr" "~A"
1788 (list (strerror err))
1791 (define-syntax TIOCGWINSZ ;<asm-generic/ioctls.h>
1792 (identifier-syntax #x5413))
1794 (define-record-type <window-size>
1795 (window-size rows columns x-pixels y-pixels)
1797 (rows window-size-rows)
1798 (columns window-size-columns)
1799 (x-pixels window-size-x-pixels)
1800 (y-pixels window-size-y-pixels))
1802 (define-c-struct winsize ;<bits/ioctl-types.h>
1807 (rows unsigned-short)
1808 (columns unsigned-short)
1809 (x-pixels unsigned-short)
1810 (y-pixels unsigned-short))
1812 (define* (terminal-window-size #:optional (port (current-output-port)))
1813 "Return a <window-size> structure describing the terminal at PORT, or raise
1814 a 'system-error' if PORT is not backed by a terminal. This procedure
1815 corresponds to the TIOCGWINSZ ioctl."
1816 (let*-values (((size) (make-bytevector sizeof-winsize))
1817 ((ret err) (%ioctl (fileno port) TIOCGWINSZ
1818 (bytevector->pointer size))))
1821 (throw 'system-error "terminal-window-size" "~A"
1822 (list (strerror err))
1825 (define* (terminal-columns #:optional (port (current-output-port)))
1826 "Return the best approximation of the number of columns of the terminal at
1827 PORT, trying to guess a reasonable value if all else fails. The result is
1828 always a positive integer."
1830 (match (and=> (getenv "COLUMNS") string->number)
1832 ((? number? columns)
1833 (if (> columns 0) columns 80))))
1835 (catch 'system-error
1837 (if (file-port? port)
1838 (match (window-size-columns (terminal-window-size port))
1839 ;; Things like Emacs shell-mode return 0, which is unreasonable.
1841 ((? number? columns) columns))
1844 (let ((errno (system-error-errno args)))
1845 ;; ENOTTY is what we're after but 2012-and-earlier Linux versions
1846 ;; would return EINVAL instead in some cases:
1847 ;; <https://bugs.ruby-lang.org/issues/10494>.
1848 ;; Furthermore, some FUSE file systems like unionfs return ENOSYS for
1850 (if (memv errno (list ENOTTY EINVAL ENOSYS))
1852 (apply throw args))))))
1859 (define-record-type <utmpx-entry>
1860 (utmpx type pid line id user host termination exit
1861 session time address)
1863 (type utmpx-login-type) ;login-type
1865 (line utmpx-line) ;device name
1867 (user utmpx-user) ;user name
1868 (host utmpx-host) ;host name | #f
1869 (termination utmpx-termination-status)
1870 (exit utmpx-exit-status)
1871 (session utmpx-session-id) ;session ID, for windowing
1872 (time utmpx-time) ;entry time
1873 (address utmpx-address))
1875 (define-c-struct %utmpx ;<utmpx.h>
1877 (lambda (type pid line id user host termination exit session
1878 seconds useconds address %reserved)
1880 (bytes->string line) id
1881 (bytes->string user)
1882 (bytes->string host) termination exit
1884 (make-time time-utc (* 1000 useconds) seconds)
1890 (line (array uint8 32))
1891 (id (array uint8 4))
1892 (user (array uint8 32))
1893 (host (array uint8 256))
1897 (time-seconds int32)
1898 (time-useconds int32)
1899 (address-v6 (array int32 4))
1900 (%reserved (array uint8 20)))
1902 (define-bits login-type
1903 %unused-login-type->symbols
1904 (define EMPTY 0) ;No valid user accounting information.
1905 (define RUN_LVL 1) ;The system's runlevel.
1906 (define BOOT_TIME 2) ;Time of system boot.
1907 (define NEW_TIME 3) ;Time after system clock changed.
1908 (define OLD_TIME 4) ;Time when system clock changed.
1910 (define INIT_PROCESS 5) ;Process spawned by the init process.
1911 (define LOGIN_PROCESS 6) ;Session leader of a logged in user.
1912 (define USER_PROCESS 7) ;Normal process.
1913 (define DEAD_PROCESS 8) ;Terminated process.
1915 (define ACCOUNTING 9)) ;System accounting.
1918 (let ((proc (syscall->procedure void "setutxent" '())))
1920 "Open the user accounting database."
1924 (let ((proc (syscall->procedure void "endutxent" '())))
1926 "Close the user accounting database."
1930 (let ((proc (syscall->procedure '* "getutxent" '())))
1932 "Return the next entry from the user accounting database."
1934 (if (null-pointer? ptr)
1936 (read-utmpx (pointer->bytevector ptr sizeof-utmpx)))))))
1938 (define (utmpx-entries)
1939 "Return the list of entries read from the user accounting database."
1941 (let loop ((entries '()))
1947 (loop (cons entry entries))))))
1949 (define (read-utmpx-from-port port)
1950 "Read a utmpx entry from PORT. Return either the EOF object or a utmpx
1952 (match (get-bytevector-n port sizeof-utmpx)
1953 ((? eof-object? eof)
1958 ;;; syscalls.scm ends here