1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2014, 2015, 2016, 2017 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)
56 file-system-block-size
57 file-system-block-count
58 file-system-blocks-free
59 file-system-blocks-available
60 file-system-file-count
61 file-system-free-file-nodes
62 file-system-identifier
63 file-system-maximum-name-length
64 file-system-fragment-size
65 file-system-mount-flags
92 all-network-interface-names
93 network-interface-names
94 network-interface-netmask
95 network-interface-running?
96 loopback-network-interface?
97 network-interface-address
98 set-network-interface-netmask
99 set-network-interface-up
100 configure-network-interface
101 add-network-route/gateway
109 interface-broadcast-address
115 termios-control-flags
117 termios-line-discipline
118 termios-control-chars
141 utmpx-termination-status
148 (read-utmpx-from-port . read-utmpx)))
152 ;;; This module provides bindings to libc's syscall wrappers. It uses the
153 ;;; FFI, and thus requires a dynamically-linked Guile.
155 ;;; Some syscalls are already defined in statically-linked Guile by applying
156 ;;; 'guile-linux-syscalls.patch'.
158 ;;; Visibility of syscall's symbols shared between this module and static Guile
159 ;;; is a bit delicate. It is handled by 'define-as-needed' macro.
161 ;;; This macro is used to export symbols in dynamic Guile context, and to
162 ;;; re-export them in static Guile context.
164 ;;; This way, even if they don't appear in #:export list, it is safe to use
165 ;;; syscalls from this module in static or dynamic Guile context.
171 ;;; Packed structures.
174 (define-syntax sizeof*
175 ;; XXX: This duplicates 'compile-time-value'.
176 (syntax-rules (int128 array)
180 (* (sizeof* type) n))
182 (let-syntax ((v (lambda (s)
183 (let ((val (sizeof type)))
188 (define-syntax alignof*
189 ;; XXX: This duplicates 'compile-time-value'.
190 (syntax-rules (int128 array)
196 (let-syntax ((v (lambda (s)
197 (let ((val (alignof type)))
202 (define-syntax align ;as found in (system foreign)
204 "Add to OFFSET whatever it takes to get proper alignment for TYPE."
205 ((_ offset (type ~ endianness))
208 (1+ (logior (1- offset) (1- (alignof* type)))))))
210 (define-syntax type-size
217 (define-syntax struct-alignment
219 "Compute the alignment for the aggregate made of TYPES at OFFSET. The
220 result is the alignment of the \"most strictly aligned component\"."
221 ((_ offset types ...)
222 (max (align offset types) ...))))
224 (define-syntax struct-size
226 "Return the size in bytes of the structure made of TYPES."
227 ((_ offset (types-processed ...))
228 ;; The SysV ABI P.S. says: "Aggregates (structures and arrays) and unions
229 ;; assume the alignment of their most strictly aligned component." As an
230 ;; example, a struct such as "int32, int16" has size 8, not 6.
231 (1+ (logior (1- offset)
232 (1- (struct-alignment offset types-processed ...)))))
233 ((_ offset (types-processed ...) type0 types ...)
234 (struct-size (+ (type-size type0) (align offset type0))
235 (type0 types-processed ...)
238 (define-syntax write-type
239 (syntax-rules (~ array *)
240 ((_ bv offset (type ~ order) value)
241 (bytevector-uint-set! bv offset value
242 (endianness order) (sizeof* type)))
243 ((_ bv offset (array type n) value)
250 (write-type bv o type head)
251 (loop (+ 1 i) tail (+ o (sizeof* type))))))))
252 ((_ bv offset '* value)
253 (bytevector-uint-set! bv offset (pointer-address value)
254 (native-endianness) (sizeof* '*)))
255 ((_ bv offset type value)
256 (bytevector-uint-set! bv offset value
257 (native-endianness) (sizeof* type)))))
259 (define-syntax write-types
263 ((_ bv offset (type0 types ...) (field0 fields ...))
265 (write-type bv (align offset type0) type0 field0)
267 (+ (align offset type0) (type-size type0))
268 (types ...) (fields ...))))))
270 (define-syntax read-type
271 (syntax-rules (~ array quote *)
273 (make-pointer (bytevector-uint-ref bv offset
276 ((_ bv offset (type ~ order))
277 (bytevector-uint-ref bv offset
278 (endianness order) (sizeof* type)))
279 ((_ bv offset (array type n))
280 (unfold (lambda (i) (= i n))
282 (read-type bv (+ offset (* i (sizeof* type))) type))
286 (bytevector-uint-ref bv offset
287 (native-endianness) (sizeof* type)))))
289 (define-syntax read-types
291 ((_ return bv offset () (values ...))
293 ((_ return bv offset (type0 types ...) (values ...))
296 (+ (align offset type0) (type-size type0))
298 (values ... (read-type bv
302 (define-syntax define-c-struct-macro
304 "Define NAME as a macro that can be queried to get information about the C
305 struct it represents. In particular:
307 (NAME field-offset FIELD)
309 returns the offset in bytes of FIELD within the C struct represented by NAME."
310 ((_ name ((fields types) ...))
311 (define-c-struct-macro name
313 ((fields types) ...)))
314 ((_ name (fields ...) offset (clauses ...) ((field type) rest ...))
315 (define-c-struct-macro name
317 (+ (align offset type) (type-size type))
318 (clauses ... ((_ field-offset field) (align offset type)))
320 ((_ name (fields ...) offset (clauses ...) ())
322 (syntax-rules (field-offset fields ...)
325 (define-syntax define-c-struct
327 "Define SIZE as the size in bytes of the C structure made of FIELDS. READ
328 as a deserializer and WRITE! as a serializer for the C structure with the
329 given TYPES. READ uses WRAP-FIELDS to return its value."
330 ((_ name size wrap-fields read write! (fields types) ...)
332 (define-c-struct-macro name
333 ((fields types) ...))
335 (struct-size 0 () types ...))
336 (define (write! bv offset fields ...)
337 (write-types bv offset (types ...) (fields ...)))
338 (define* (read bv #:optional (offset 0))
339 (read-types wrap-fields bv offset (types ...) ()))))))
341 (define-syntax-rule (c-struct-field-offset type field)
342 "Return the offset in BYTES of FIELD within TYPE, where TYPE is a C struct
343 defined with 'define-c-struct' and FIELD is a field identifier. An
344 expansion-time error is raised if FIELD does not exist in TYPE."
345 (type field-offset field))
352 (define %libc-errno-pointer
353 ;; Glibc's 'errno' pointer, for use with Guile < 2.0.12.
354 (let ((errno-loc (false-if-exception
355 (dynamic-func "__errno_location" (dynamic-link)))))
357 (let ((proc (pointer->procedure '* errno-loc '())))
360 (define errno ;for Guile < 2.0.12
361 (if %libc-errno-pointer
362 (let ((bv (pointer->bytevector %libc-errno-pointer (sizeof int))))
364 "Return the current errno."
365 ;; XXX: We assume that nothing changes 'errno' while we're doing all this.
366 ;; In particular, that means that no async must be running here.
368 ;; Use one of the fixed-size native-ref procedures because they are
369 ;; optimized down to a single VM instruction, which reduces the risk
370 ;; that we fiddle with 'errno' (needed on Guile 2.0.5, libc 2.11.)
371 (let-syntax ((ref (lambda (s)
376 #'(bytevector-s32-native-ref bv 0))
378 #'(bytevector-s64-native-ref bv 0))
380 (error "unsupported 'int' size"
385 (define (call-with-restart-on-EINTR thunk)
390 (if (= (system-error-errno args) EINTR)
392 (apply throw args))))))
394 (define-syntax-rule (restart-on-EINTR expr)
395 "Evaluate EXPR and restart upon EINTR. Return the value of EXPR."
396 (call-with-restart-on-EINTR (lambda () expr)))
398 (define (syscall->procedure return-type name argument-types)
399 "Return a procedure that wraps the C function NAME using the dynamic FFI,
400 and that returns two values: NAME's return value, and errno.
402 If an error occurs while creating the binding, defer the error report until
403 the returned procedure is called."
406 (let ((ptr (dynamic-func name (dynamic-link))))
407 ;; The #:return-errno? facility was introduced in Guile 2.0.12.
408 ;; Support older versions of Guile by catching 'wrong-number-of-args'.
409 (catch 'wrong-number-of-args
411 (pointer->procedure return-type ptr argument-types
414 (let ((proc (pointer->procedure return-type ptr argument-types)))
416 (let ((result (apply proc args))
418 (values result err))))))))
421 (error (format #f "~a: syscall->procedure failed: ~s"
424 (define-syntax define-as-needed
426 "Define VARIABLE. If VARIABLE already exists in (guile) then re-export it,
427 otherwise export the newly-defined VARIABLE."
428 ((_ (proc args ...) body ...)
429 (define-as-needed proc (lambda* (args ...) body ...)))
432 (when (module-defined? the-scm-module 'variable)
433 (re-export variable))
436 (if (module-defined? the-scm-module 'variable)
437 (module-ref the-scm-module 'variable)
440 (unless (module-defined? the-scm-module 'variable)
441 (export variable))))))
448 (define (augment-mtab source target type options)
449 "Augment /etc/mtab with information about the given mount point."
450 (let ((port (open-file "/etc/mtab" "a")))
451 (format port "~a ~a ~a ~a 0 0~%"
452 source target type (or options "rw"))
455 (define (read-mtab port)
456 "Read an mtab-formatted file from PORT, returning a list of tuples."
457 (let loop ((result '()))
458 (let ((line (read-line port)))
459 (if (eof-object? line)
461 (loop (cons (string-tokenize line) result))))))
463 (define (remove-from-mtab target)
464 "Remove mount point TARGET from /etc/mtab."
466 (remove (match-lambda
467 ((device mount-point type options freq passno)
468 (string=? target mount-point))
470 (call-with-input-file "/etc/mtab" read-mtab)))
472 (call-with-output-file "/etc/mtab"
474 (for-each (match-lambda
475 ((device mount-point type options freq passno)
476 (format port "~a ~a ~a ~a ~a ~a~%"
477 device mount-point type options freq passno)))
480 ;; Linux mount flags, from libc's <sys/mount.h>.
485 (define MS_REMOUNT 32)
486 (define MS_BIND 4096)
487 (define MS_MOVE 8192)
488 (define MS_STRICTATIME 16777216)
491 (define MNT_DETACH 2)
492 (define MNT_EXPIRE 4)
493 (define UMOUNT_NOFOLLOW 8)
495 (define-as-needed (mount source target type
496 #:optional (flags 0) options
497 #:key (update-mtab? #f))
498 "Mount device SOURCE on TARGET as a file system TYPE.
499 Optionally, FLAGS may be a bitwise-or of the MS_* <sys/mount.h>
500 constants, and OPTIONS may be a string. When FLAGS contains
501 MS_REMOUNT, SOURCE and TYPE are ignored. When UPDATE-MTAB? is true,
502 update /etc/mtab. Raise a 'system-error' exception on error."
503 ;; XXX: '#:update-mtab?' is not implemented by core 'mount'.
504 (let ((proc (syscall->procedure int "mount" `(* * * ,unsigned-long *))))
505 (let-values (((ret err)
507 (string->pointer source)
509 (string->pointer target)
511 (string->pointer type)
515 (string->pointer options)
518 (throw 'system-error "mount" "mount ~S on ~S: ~A"
519 (list source target (strerror err))
522 (augment-mtab source target type options)))))
524 (define-as-needed (umount target
526 #:key (update-mtab? #f))
527 "Unmount TARGET. Optionally FLAGS may be one of the MNT_* or UMOUNT_*
528 constants from <sys/mount.h>."
529 ;; XXX: '#:update-mtab?' is not implemented by core 'umount'.
530 (let ((proc (syscall->procedure int "umount2" `(* ,int))))
531 (let-values (((ret err)
532 (proc (string->pointer target) flags)))
534 (throw 'system-error "umount" "~S: ~A"
535 (list target (strerror err))
538 (remove-from-mtab target)))))
540 (define (mount-points)
541 "Return the mounts points for currently mounted file systems."
542 (call-with-input-file "/proc/mounts"
544 (let loop ((result '()))
545 (let ((line (read-line port)))
546 (if (eof-object? line)
548 (match (string-tokenize line)
549 ((source mount-point _ ...)
550 (loop (cons mount-point result))))))))))
553 (let ((proc (syscall->procedure int "swapon" (list '* int))))
554 (lambda* (device #:optional (flags 0))
555 "Use the block special device at DEVICE for swapping."
556 (let-values (((ret err)
557 (proc (string->pointer device) flags)))
559 (throw 'system-error "swapon" "~S: ~A"
560 (list device (strerror err))
564 (let ((proc (syscall->procedure int "swapoff" '(*))))
566 "Stop using block special device DEVICE for swapping."
567 (let-values (((ret err) (proc (string->pointer device))))
569 (throw 'system-error "swapoff" "~S: ~A"
570 (list device (strerror err))
573 (define-as-needed RB_AUTOBOOT #x01234567)
574 (define-as-needed RB_HALT_SYSTEM #xcdef0123)
575 (define-as-needed RB_ENABLED_CAD #x89abcdef)
576 (define-as-needed RB_DISABLE_CAD 0)
577 (define-as-needed RB_POWER_OFF #x4321fedc)
578 (define-as-needed RB_SW_SUSPEND #xd000fce2)
579 (define-as-needed RB_KEXEC #x45584543)
581 (define-as-needed (reboot #:optional (cmd RB_AUTOBOOT))
582 (let ((proc (syscall->procedure int "reboot" (list int))))
583 (let-values (((ret err) (proc cmd)))
585 (throw 'system-error "reboot" "~S: ~A"
586 (list cmd (strerror err))
589 (define-as-needed (load-linux-module data #:optional (options ""))
590 (let ((proc (syscall->procedure int "init_module"
591 (list '* unsigned-long '*))))
592 (let-values (((ret err)
593 (proc (bytevector->pointer data)
594 (bytevector-length data)
595 (string->pointer options))))
597 (throw 'system-error "load-linux-module" "~A"
598 (list (strerror err))
601 (define (kernel? pid)
602 "Return #t if PID designates a \"kernel thread\" rather than a normal
604 (let ((stat (call-with-input-file (format #f "/proc/~a/stat" pid)
605 (compose string-tokenize read-string))))
606 ;; See proc.txt in Linux's documentation for the list of fields.
608 ((pid tcomm state ppid pgrp sid tty_nr tty_pgrp flags min_flt
609 cmin_flt maj_flt cmaj_flt utime stime cutime cstime
610 priority nice num_thread it_real_value start_time
612 (= string->number start_code) (= string->number end_code) _ ...)
613 ;; Got this obscure trick from sysvinit's 'killall5' program.
614 (and (zero? start_code) (zero? end_code))))))
617 "Return the list of live processes."
618 (sort (filter-map (lambda (file)
619 (let ((pid (string->number file)))
627 (let ((proc (syscall->procedure '* "mkdtemp" '(*))))
629 "Create a new unique directory in the file system using the template
630 string TMPL and return its file name. TMPL must end with 'XXXXXX'."
631 (let-values (((result err) (proc (string->pointer tmpl))))
632 (when (null-pointer? result)
633 (throw 'system-error "mkdtemp!" "~S: ~A"
634 (list tmpl (strerror err))
636 (pointer->string result)))))
639 (let ((proc (syscall->procedure int "fdatasync" (list int))))
641 "Flush buffered output of PORT, an output file port, and then call
642 fdatasync(2) on the underlying file descriptor."
644 (let*-values (((fd) (fileno port))
645 ((ret err) (proc fd)))
647 (throw 'system-error "fdatasync" "~S: ~A"
648 (list fd (strerror err))
652 (define-record-type <file-system>
653 (file-system type block-size blocks blocks-free
654 blocks-available files free-files identifier
655 name-length fragment-size mount-flags spare)
657 (type file-system-type)
658 (block-size file-system-block-size)
659 (blocks file-system-block-count)
660 (blocks-free file-system-blocks-free)
661 (blocks-available file-system-blocks-available)
662 (files file-system-file-count)
663 (free-files file-system-free-file-nodes)
664 (identifier file-system-identifier)
665 (name-length file-system-maximum-name-length)
666 (fragment-size file-system-fragment-size)
667 (mount-flags file-system-mount-flags)
668 (spare file-system--spare))
670 (define-syntax fsword ;fsword_t
671 (identifier-syntax long))
673 (define-c-struct %statfs ;<bits/statfs.h>
674 sizeof-statfs ;slightly overestimated
682 (blocks-available uint64)
685 (identifier (array int 2))
687 (fragment-size fsword)
689 (spare (array fsword 4)))
692 (let ((proc (syscall->procedure int "statfs64" '(* *))))
694 "Return a <file-system> data structure describing the file system
696 (let*-values (((stat) (make-bytevector sizeof-statfs))
697 ((ret err) (proc (string->pointer file)
698 (bytevector->pointer stat))))
701 (throw 'system-error "statfs" "~A: ~A"
702 (list file (strerror err))
705 (define (free-disk-space file)
706 "Return the free disk space, in bytes, on the file system that hosts FILE."
707 (let ((fs (statfs file)))
708 (* (file-system-block-size fs)
709 (file-system-blocks-available fs))))
716 ;; Linux clone flags, from linux/sched.h
717 (define CLONE_CHILD_CLEARTID #x00200000)
718 (define CLONE_CHILD_SETTID #x01000000)
719 (define CLONE_NEWNS #x00020000)
720 (define CLONE_NEWUTS #x04000000)
721 (define CLONE_NEWIPC #x08000000)
722 (define CLONE_NEWUSER #x10000000)
723 (define CLONE_NEWPID #x20000000)
724 (define CLONE_NEWNET #x40000000)
728 (define %set-automatic-finalization-enabled?!
729 ;; When using a statically-linked Guile, for instance in the initrd, we
730 ;; cannot resolve this symbol, but most of the time we don't need it
731 ;; anyway. Thus, delay it.
733 (pointer->procedure int
735 "scm_set_automatic_finalization_enabled"
739 "Switch on or off automatic finalization in a separate thread.
740 Turning finalization off shuts down the finalization thread as a side effect."
741 (->bool ((force proc) (if enabled? 1 0))))))
743 (define-syntax-rule (without-automatic-finalization exp)
744 "Turn off automatic finalization within the dynamic extent of EXP."
748 (set! enabled? (%set-automatic-finalization-enabled?! #f)))
752 (%set-automatic-finalization-enabled?! enabled?))))))
755 (define-syntax-rule (without-automatic-finalization exp)
756 ;; Nothing to do here: Guile 2.0 does not have a separate finalization
760 ;; The libc interface to sys_clone is not useful for Scheme programs, so the
761 ;; low-level system call is wrapped instead. The 'syscall' function is
762 ;; declared in <unistd.h> as a variadic function; in practice, it expects 6
763 ;; pointer-sized arguments, as shown in, e.g., x86_64/syscall.S.
765 (let* ((proc (syscall->procedure int "syscall"
770 ;; TODO: Don't do this.
771 (syscall-id (match (utsname:machine (uname))
779 "Create a new child process by duplicating the current parent process.
780 Unlike the fork system call, clone accepts FLAGS that specify which resources
781 are shared between the parent and child processes."
782 (let-values (((ret err)
783 ;; Guile 2.2 runs a finalization thread. 'primitive-fork'
784 ;; takes care of shutting it down before forking, and we
785 ;; must do the same here. Failing to do that, if the
786 ;; child process calls 'primitive-fork', it will hang
787 ;; while trying to pthread_join the finalization thread
788 ;; since that thread does not exist.
789 (without-automatic-finalization
790 (proc syscall-id flags
791 %null-pointer ;child stack
792 %null-pointer %null-pointer ;ptid & ctid
793 %null-pointer)))) ;unused
795 (throw 'system-error "clone" "~d: ~A"
796 (list flags (strerror err))
801 ;; Some systems may be using an old (pre-2.14) version of glibc where there
802 ;; is no 'setns' function available.
804 (let ((proc (syscall->procedure int "setns" (list int int))))
805 (lambda (fdes nstype)
806 "Reassociate the current process with the namespace specified by FDES, a
807 file descriptor obtained by opening a /proc/PID/ns/* file. NSTYPE specifies
808 which type of namespace the current process may be reassociated with, or 0 if
809 there is no such limitation."
810 (let-values (((ret err) (proc fdes nstype)))
812 (throw 'system-error "setns" "~d ~d: ~A"
813 (list fdes nstype (strerror err))
817 (let ((proc (syscall->procedure int "pivot_root" (list '* '*))))
818 (lambda (new-root put-old)
819 "Change the root file system to NEW-ROOT and move the current root file
821 (let-values (((ret err)
822 (proc (string->pointer new-root)
823 (string->pointer put-old))))
825 (throw 'system-error "pivot_root" "~S ~S: ~A"
826 (list new-root put-old (strerror err))
834 (define (file-type->symbol type)
835 ;; Convert TYPE to symbols like 'stat:type' does.
836 (cond ((= type DT_REG) 'regular)
837 ((= type DT_LNK) 'symlink)
838 ((= type DT_DIR) 'directory)
839 ((= type DT_FIFO) 'fifo)
840 ((= type DT_CHR) 'char-special)
841 ((= type DT_BLK) 'block-special)
842 ((= type DT_SOCK) 'socket)
845 ;; 'struct dirent64' for GNU/Linux.
846 (define-c-struct %struct-dirent-header/linux
847 sizeof-dirent-header/linux
848 (lambda (inode offset length type name)
849 `((type . ,(file-type->symbol type))
851 read-dirent-header/linux
852 write-dirent-header!/linux
855 (length unsigned-short)
857 (name uint8)) ;first byte of 'd_name'
859 ;; 'struct dirent64' for GNU/Hurd.
860 (define-c-struct %struct-dirent-header/hurd
861 sizeof-dirent-header/hurd
862 (lambda (inode length type name-length name)
863 `((type . ,(file-type->symbol type))
865 read-dirent-header/hurd
866 write-dirent-header!/hurd
868 (length unsigned-short)
873 (define-syntax define-generic-identifier
874 (syntax-rules (gnu/linux gnu/hurd =>)
875 "Define a generic identifier that adjust to the current GNU variant."
876 ((_ id (gnu/linux => linux) (gnu/hurd => hurd))
881 (if (string-contains (or (target-type) %host-type)
883 #'(linux args (... ...))
884 #'(hurd args (... ...))))
886 (if (string-contains (or (target-type) %host-type)
891 (define-generic-identifier read-dirent-header
892 (gnu/linux => read-dirent-header/linux)
893 (gnu/hurd => read-dirent-header/hurd))
895 (define-generic-identifier %struct-dirent-header
896 (gnu/linux => %struct-dirent-header/linux)
897 (gnu/hurd => %struct-dirent-header/hurd))
899 (define-generic-identifier sizeof-dirent-header
900 (gnu/linux => sizeof-dirent-header/linux)
901 (gnu/hurd => sizeof-dirent-header/hurd))
903 ;; Constants for the 'type' field, from <dirent.h>.
904 (define DT_UNKNOWN 0)
914 (define string->pointer/utf-8
915 (cut string->pointer <> "UTF-8"))
917 (define pointer->string/utf-8
918 (cut pointer->string <> <> "UTF-8"))
921 (let ((proc (syscall->procedure '* "opendir" '(*))))
922 (lambda* (name #:optional (string->pointer string->pointer/utf-8))
923 (let-values (((ptr err)
924 (proc (string->pointer name))))
925 (if (null-pointer? ptr)
926 (throw 'system-error "opendir*"
927 "~A: ~A" (list name (strerror err))
932 (let ((proc (syscall->procedure int "closedir" '(*))))
934 (let-values (((ret err)
937 (throw 'system-error "closedir"
938 "closedir: ~A" (list (strerror err))
942 (let ((proc (syscall->procedure '* "readdir64" '(*))))
943 (lambda* (directory #:optional (pointer->string pointer->string/utf-8))
944 (let ((ptr (proc directory)))
945 (and (not (null-pointer? ptr))
946 (cons (pointer->string
947 (make-pointer (+ (pointer-address ptr)
948 (c-struct-field-offset
949 %struct-dirent-header name)))
952 (pointer->bytevector ptr sizeof-dirent-header))))))))
954 (define* (scandir* name #:optional
956 (entry<? (lambda (entry1 entry2)
961 (string<? name1 name2)))))))
963 (string->pointer string->pointer/utf-8)
964 (pointer->string pointer->string/utf-8))
965 "This procedure improves on Guile's 'scandir' procedure in several ways:
967 1. Systematically encode decode file names using STRING->POINTER and
968 POINTER->STRING (UTF-8 by default; this works around a defect in Guile 2.0/2.2
969 where 'scandir' decodes file names according to the current locale, which is
970 not always desirable.
972 2. Each entry that is returned has the form (NAME . PROPERTIES).
973 PROPERTIES is an alist showing additional properties about the entry, as
974 found in 'struct dirent'. An entry may look like this:
976 (\"foo.scm\" (type . regular) (inode . 123456))
978 Callers must be prepared to deal with the case where 'type' is 'unknown'
979 since some file systems do not provide that information.
981 3. Raise to 'system-error' when NAME cannot be opened."
982 (let ((directory (opendir* name string->pointer)))
986 (let loop ((result '()))
987 (match (readdir* directory pointer->string)
989 (sort result entry<?))
991 (loop (if (select? entry)
995 (closedir* directory)))))
999 ;;; Advisory file locking.
1002 (define-c-struct %struct-flock ;<fcntl.h>
1014 ;; On Linux-based systems, this is usually 7, but not always
1015 ;; (exceptions include SPARC.) On GNU/Hurd, it's 9.
1016 (cond ((string-contains %host-type "sparc") 9) ; sparc-*-linux-gnu
1017 ((string-contains %host-type "linux") 7) ; *-linux-gnu
1021 ;; Likewise: GNU/Hurd and SPARC use 8, while the others typically use 6.
1022 (cond ((string-contains %host-type "sparc") 8) ; sparc-*-linux-gnu
1023 ((string-contains %host-type "linux") 6) ; *-linux-gnu
1027 ;; The F_RDLCK, F_WRLCK, and F_UNLCK constants.
1028 (cond ((string-contains %host-type "sparc") #(1 2 3)) ; sparc-*-linux-gnu
1029 ((string-contains %host-type "hppa") #(1 2 3)) ; hppa-*-linux-gnu
1030 ((string-contains %host-type "linux") #(0 1 2)) ; *-linux-gnu
1031 (else #(1 2 3)))) ; *-gnu*
1034 (let ((proc (syscall->procedure int "fcntl" `(,int ,int *))))
1035 (lambda* (fd-or-port operation #:key (wait? #t))
1036 "Perform locking OPERATION on the file beneath FD-OR-PORT. OPERATION
1037 must be a symbol, one of 'read-lock, 'write-lock, or 'unlock. When WAIT? is
1038 true, block until the lock is acquired; otherwise, thrown an 'flock-error'
1039 exception if it's already taken."
1040 (define (operation->int op)
1042 ((read-lock) (vector-ref F_xxLCK 0))
1043 ((write-lock) (vector-ref F_xxLCK 1))
1044 ((unlock) (vector-ref F_xxLCK 2))
1045 (else (error "invalid fcntl-flock operation" op))))
1048 (if (port? fd-or-port)
1053 (make-bytevector sizeof-flock))
1056 (operation->int operation) SEEK_SET
1060 ;; XXX: 'fcntl' is a vararg function, but here we happily use the
1061 ;; standard ABI; crossing fingers.
1062 (let-values (((ret err)
1065 F_SETLKW ;lock & wait
1066 F_SETLK) ;non-blocking attempt
1067 (bytevector->pointer bv))))
1069 ;; Presumably we got EAGAIN or so.
1070 (throw 'flock-error err))))))
1074 ;;; Miscellaneous, aka. 'prctl'.
1078 ;; Should it win the API contest against 'ioctl'? You tell us!
1079 (syscall->procedure int "prctl"
1080 (list int unsigned-long unsigned-long
1081 unsigned-long unsigned-long)))
1083 (define PR_SET_NAME 15) ;<linux/prctl.h>
1084 (define PR_GET_NAME 16)
1086 (define %max-thread-name-length
1087 ;; Maximum length in bytes of the process name, including the terminating
1091 (define (set-thread-name name)
1092 "Set the name of the calling thread to NAME. NAME is truncated to 15
1094 (let ((ptr (string->pointer name)))
1095 (let-values (((ret err)
1097 (pointer-address ptr) 0 0 0)))
1099 (throw 'set-process-name "set-process-name"
1100 "set-process-name: ~A"
1101 (list (strerror err))
1104 (define (thread-name)
1105 "Return the name of the calling thread as a string."
1106 (let ((buf (make-bytevector %max-thread-name-length)))
1107 (let-values (((ret err)
1109 (pointer-address (bytevector->pointer buf))
1112 (bytes->string (bytevector->u8-list buf))
1113 (throw 'process-name "process-name"
1115 (list (strerror err))
1120 ;;; Network interfaces.
1123 (define SIOCGIFCONF ;from <bits/ioctls.h>
1124 (if (string-contains %host-type "linux")
1126 #xf00801a4)) ;GNU/Hurd
1127 (define SIOCGIFFLAGS
1128 (if (string-contains %host-type "linux")
1130 #xc4804191)) ;GNU/Hurd
1131 (define SIOCSIFFLAGS
1132 (if (string-contains %host-type "linux")
1134 -1)) ;FIXME: GNU/Hurd?
1136 (if (string-contains %host-type "linux")
1138 -1)) ;FIXME: GNU/Hurd?
1140 (if (string-contains %host-type "linux")
1142 -1)) ;FIXME: GNU/Hurd?
1143 (define SIOCGIFNETMASK
1144 (if (string-contains %host-type "linux")
1146 -1)) ;FIXME: GNU/Hurd?
1147 (define SIOCSIFNETMASK
1148 (if (string-contains %host-type "linux")
1150 -1)) ;FIXME: GNU/Hurd?
1152 (if (string-contains %host-type "linux")
1154 -1)) ;FIXME: GNU/Hurd?
1156 (if (string-contains %host-type "linux")
1158 -1)) ;FIXME: GNU/Hurd?
1160 ;; Flags and constants from <net/if.h>.
1162 (define-as-needed IFF_UP #x1) ;Interface is up
1163 (define-as-needed IFF_BROADCAST #x2) ;Broadcast address valid.
1164 (define-as-needed IFF_LOOPBACK #x8) ;Is a loopback net.
1165 (define-as-needed IFF_RUNNING #x40) ;interface RFC2863 OPER_UP
1167 (define IF_NAMESIZE 16) ;maximum interface name size
1169 (define-c-struct %ifconf-struct
1174 (length int) ;int ifc_len
1175 (request '*)) ;struct ifreq *ifc_ifcu
1177 (define ifreq-struct-size
1178 ;; 'struct ifreq' begins with an array of IF_NAMESIZE bytes containing the
1179 ;; interface name (nul-terminated), followed by a bunch of stuff. This is
1180 ;; its size in bytes.
1181 (if (= 8 (sizeof '*))
1185 (define-c-struct sockaddr-in ;<linux/in.h>
1187 (lambda (family port address)
1188 (make-socket-address family address port))
1191 (family unsigned-short)
1192 (port (int16 ~ big))
1193 (address (int32 ~ big)))
1195 (define-c-struct sockaddr-in6 ;<linux/in6.h>
1197 (lambda (family port flowinfo address scopeid)
1198 (make-socket-address family address port flowinfo scopeid))
1201 (family unsigned-short)
1202 (port (int16 ~ big))
1203 (flowinfo (int32 ~ big))
1204 (address (int128 ~ big))
1207 (define (write-socket-address! sockaddr bv index)
1208 "Write SOCKADDR, a socket address as returned by 'make-socket-address', to
1209 bytevector BV at INDEX."
1210 (let ((family (sockaddr:fam sockaddr)))
1211 (cond ((= family AF_INET)
1212 (write-sockaddr-in! bv index
1214 (sockaddr:port sockaddr)
1215 (sockaddr:addr sockaddr)))
1216 ((= family AF_INET6)
1217 (write-sockaddr-in6! bv index
1219 (sockaddr:port sockaddr)
1220 (sockaddr:flowinfo sockaddr)
1221 (sockaddr:addr sockaddr)
1222 (sockaddr:scopeid sockaddr)))
1224 (error "unsupported socket address" sockaddr)))))
1226 (define PF_PACKET 17) ;<bits/socket.h>
1227 (define AF_PACKET PF_PACKET)
1229 (define* (read-socket-address bv #:optional (index 0))
1230 "Read a socket address from bytevector BV at INDEX."
1231 (let ((family (bytevector-u16-native-ref bv index)))
1232 (cond ((= family AF_INET)
1233 (read-sockaddr-in bv index))
1234 ((= family AF_INET6)
1235 (read-sockaddr-in6 bv index))
1237 ;; XXX: Unsupported address family, such as AF_PACKET. Return a
1238 ;; vector such that the vector can at least call 'sockaddr:fam'.
1242 ;; The most terrible interface, live from Scheme.
1243 (syscall->procedure int "ioctl" (list int unsigned-long '*)))
1245 (define (bytes->string bytes)
1246 "Read BYTES, a list of bytes, and return the null-terminated string decoded
1247 from there, or #f if that would be an empty string."
1248 (match (take-while (negate zero?) bytes)
1252 (list->string (map integer->char non-zero)))))
1254 (define (bytevector->string-list bv stride len)
1255 "Return the null-terminated strings found in BV every STRIDE bytes. Read at
1256 most LEN bytes from BV."
1257 (let loop ((bytes (take (bytevector->u8-list bv)
1258 (min len (bytevector-length bv))))
1264 (loop (drop bytes stride)
1265 (cons (bytes->string bytes) result))))))
1267 (define* (network-interface-names #:optional sock)
1268 "Return the names of existing network interfaces. This is typically limited
1269 to interfaces that are currently up."
1270 (let* ((close? (not sock))
1271 (sock (or sock (socket SOCK_STREAM AF_INET 0)))
1272 (len (* ifreq-struct-size 10))
1273 (reqs (make-bytevector len))
1274 (conf (make-bytevector sizeof-ifconf)))
1275 (write-ifconf! conf 0
1276 len (bytevector->pointer reqs))
1278 (let-values (((ret err)
1279 (%ioctl (fileno sock) SIOCGIFCONF
1280 (bytevector->pointer conf))))
1284 (bytevector->string-list reqs ifreq-struct-size
1285 (match (read-ifconf conf)
1287 (throw 'system-error "network-interface-list"
1288 "network-interface-list: ~A"
1289 (list (strerror err))
1292 (define %interface-line
1293 ;; Regexp matching an interface line in Linux's /proc/net/dev.
1294 (make-regexp "^[[:blank:]]*([[:graph:]]+):.*$"))
1296 (define (all-network-interface-names)
1297 "Return all the names of the registered network interfaces, including those
1299 (call-with-input-file "/proc/net/dev" ;XXX: Linux-specific
1301 (let loop ((interfaces '()))
1302 (let ((line (read-line port)))
1303 (cond ((eof-object? line)
1304 (reverse interfaces))
1305 ((regexp-exec %interface-line line)
1308 (loop (cons (match:substring match 1) interfaces))))
1310 (loop interfaces))))))))
1312 (define-as-needed (network-interface-flags socket name)
1313 "Return a number that is the bit-wise or of 'IFF*' flags for network
1315 (let ((req (make-bytevector ifreq-struct-size)))
1316 (bytevector-copy! (string->utf8 name) 0 req 0
1317 (min (string-length name) (- IF_NAMESIZE 1)))
1318 (let-values (((ret err)
1319 (%ioctl (fileno socket) SIOCGIFFLAGS
1320 (bytevector->pointer req))))
1323 ;; The 'ifr_flags' field is IF_NAMESIZE bytes after the
1324 ;; beginning of 'struct ifreq', and it's a short int.
1325 (bytevector-sint-ref req IF_NAMESIZE (native-endianness)
1328 (throw 'system-error "network-interface-flags"
1329 "network-interface-flags on ~A: ~A"
1330 (list name (strerror err))
1333 (define (loopback-network-interface? name)
1334 "Return true if NAME designates a loopback network interface."
1335 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1336 (flags (network-interface-flags sock name)))
1338 (not (zero? (logand flags IFF_LOOPBACK)))))
1340 (define (network-interface-running? name)
1341 "Return true if NAME designates a running network interface."
1342 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1343 (flags (network-interface-flags sock name)))
1345 (not (zero? (logand flags IFF_RUNNING)))))
1347 (define-as-needed (set-network-interface-flags socket name flags)
1348 "Set the flag of network interface NAME to FLAGS."
1349 (let ((req (make-bytevector ifreq-struct-size)))
1350 (bytevector-copy! (string->utf8 name) 0 req 0
1351 (min (string-length name) (- IF_NAMESIZE 1)))
1352 ;; Set the 'ifr_flags' field.
1353 (bytevector-uint-set! req IF_NAMESIZE flags (native-endianness)
1355 (let-values (((ret err)
1356 (%ioctl (fileno socket) SIOCSIFFLAGS
1357 (bytevector->pointer req))))
1359 (throw 'system-error "set-network-interface-flags"
1360 "set-network-interface-flags on ~A: ~A"
1361 (list name (strerror err))
1364 (define-as-needed (set-network-interface-address socket name sockaddr)
1365 "Set the address of network interface NAME to SOCKADDR."
1366 (let ((req (make-bytevector ifreq-struct-size)))
1367 (bytevector-copy! (string->utf8 name) 0 req 0
1368 (min (string-length name) (- IF_NAMESIZE 1)))
1369 ;; Set the 'ifr_addr' field.
1370 (write-socket-address! sockaddr req IF_NAMESIZE)
1371 (let-values (((ret err)
1372 (%ioctl (fileno socket) SIOCSIFADDR
1373 (bytevector->pointer req))))
1375 (throw 'system-error "set-network-interface-address"
1376 "set-network-interface-address on ~A: ~A"
1377 (list name (strerror err))
1380 (define (set-network-interface-netmask socket name sockaddr)
1381 "Set the network mask of interface NAME to SOCKADDR."
1382 (let ((req (make-bytevector ifreq-struct-size)))
1383 (bytevector-copy! (string->utf8 name) 0 req 0
1384 (min (string-length name) (- IF_NAMESIZE 1)))
1385 ;; Set the 'ifr_addr' field.
1386 (write-socket-address! sockaddr req IF_NAMESIZE)
1387 (let-values (((ret err)
1388 (%ioctl (fileno socket) SIOCSIFNETMASK
1389 (bytevector->pointer req))))
1391 (throw 'system-error "set-network-interface-netmask"
1392 "set-network-interface-netmask on ~A: ~A"
1393 (list name (strerror err))
1396 (define (network-interface-address socket name)
1397 "Return the address of network interface NAME. The result is an object of
1398 the same type as that returned by 'make-socket-address'."
1399 (let ((req (make-bytevector ifreq-struct-size)))
1400 (bytevector-copy! (string->utf8 name) 0 req 0
1401 (min (string-length name) (- IF_NAMESIZE 1)))
1402 (let-values (((ret err)
1403 (%ioctl (fileno socket) SIOCGIFADDR
1404 (bytevector->pointer req))))
1406 (read-socket-address req IF_NAMESIZE)
1407 (throw 'system-error "network-interface-address"
1408 "network-interface-address on ~A: ~A"
1409 (list name (strerror err))
1412 (define (network-interface-netmask socket name)
1413 "Return the netmask of network interface NAME. The result is an object of
1414 the same type as that returned by 'make-socket-address'."
1415 (let ((req (make-bytevector ifreq-struct-size)))
1416 (bytevector-copy! (string->utf8 name) 0 req 0
1417 (min (string-length name) (- IF_NAMESIZE 1)))
1418 (let-values (((ret err)
1419 (%ioctl (fileno socket) SIOCGIFNETMASK
1420 (bytevector->pointer req))))
1422 (read-socket-address req IF_NAMESIZE)
1423 (throw 'system-error "network-interface-netmask"
1424 "network-interface-netmask on ~A: ~A"
1425 (list name (strerror err))
1428 (define* (configure-network-interface name sockaddr flags
1430 "Configure network interface NAME to use SOCKADDR, an address as returned by
1431 'make-socket-address', and FLAGS, a bitwise-or of IFF_* constants. If NETMASK
1432 is true, it must be a socket address to use as the network mask."
1433 (let ((sock (socket (sockaddr:fam sockaddr) SOCK_STREAM 0)))
1437 (set-network-interface-address sock name sockaddr)
1438 (set-network-interface-flags sock name flags)
1440 (set-network-interface-netmask sock name netmask)))
1442 (close-port sock)))))
1444 (define* (set-network-interface-up name
1445 #:key (family AF_INET))
1446 "Turn up the interface NAME."
1447 (let ((sock (socket family SOCK_STREAM 0)))
1451 (let ((flags (network-interface-flags sock name)))
1452 (set-network-interface-flags sock name
1453 (logior flags IFF_UP))))
1455 (close-port sock)))))
1462 (define-c-struct %rtentry ;'struct rtentry' from <net/route.h>
1467 (pad1 unsigned-long)
1468 (destination (array uint8 16)) ;struct sockaddr
1469 (gateway (array uint8 16)) ;struct sockaddr
1470 (genmask (array uint8 16)) ;struct sockaddr
1471 (flags unsigned-short)
1476 (pad4 (array uint8 (if (= 8 (sizeof* '*)) 3 1)))
1480 (window unsigned-long)
1481 (initial-rtt unsigned-short))
1483 (define RTF_UP #x0001) ;'rtentry' flags from <net/route.h>
1484 (define RTF_GATEWAY #x0002)
1486 (define %sockaddr-any
1487 (make-socket-address AF_INET INADDR_ANY 0))
1489 (define add-network-route/gateway
1490 ;; To allow field names to be matched as literals, we need to move them out
1491 ;; of the lambda's body since the parameters have the same name. A lot of
1492 ;; fuss for very little.
1493 (let-syntax ((gateway-offset (identifier-syntax
1494 (c-struct-field-offset %rtentry gateway)))
1495 (destination-offset (identifier-syntax
1496 (c-struct-field-offset %rtentry destination)))
1497 (genmask-offset (identifier-syntax
1498 (c-struct-field-offset %rtentry genmask))))
1499 (lambda* (socket gateway
1500 #:key (destination %sockaddr-any) (genmask %sockaddr-any))
1501 "Add a network route for DESTINATION (a socket address as returned by
1502 'make-socket-address') that goes through GATEWAY (a socket address). For
1505 (add-network-route/gateway sock
1506 (make-socket-address
1508 (inet-pton AF_INET \"192.168.0.1\")
1511 is equivalent to this 'net-tools' command:
1513 route add -net default gw 192.168.0.1
1515 because the default value of DESTINATION is \"0.0.0.0\"."
1516 (let ((route (make-bytevector sizeof-rtentry 0)))
1517 (write-socket-address! gateway route gateway-offset)
1518 (write-socket-address! destination route destination-offset)
1519 (write-socket-address! genmask route genmask-offset)
1520 (bytevector-u16-native-set! route
1521 (c-struct-field-offset %rtentry flags)
1522 (logior RTF_UP RTF_GATEWAY))
1523 (let-values (((ret err)
1524 (%ioctl (fileno socket) SIOCADDRT
1525 (bytevector->pointer route))))
1527 (throw 'system-error "add-network-route/gateway"
1528 "add-network-route/gateway: ~A"
1529 (list (strerror err))
1532 (define delete-network-route
1533 (let-syntax ((destination-offset (identifier-syntax
1534 (c-struct-field-offset %rtentry destination))))
1535 (lambda* (socket destination)
1536 "Delete the network route for DESTINATION. For instance, the call:
1538 (delete-network-route sock
1539 (make-socket-address AF_INET INADDR_ANY 0))
1541 is equivalent to the 'net-tools' command:
1543 route del -net default
1546 (let ((route (make-bytevector sizeof-rtentry 0)))
1547 (write-socket-address! destination route destination-offset)
1548 (let-values (((ret err)
1549 (%ioctl (fileno socket) SIOCDELRT
1550 (bytevector->pointer route))))
1552 (throw 'system-error "delete-network-route"
1553 "delete-network-route: ~A"
1554 (list (strerror err))
1559 ;;; Details about network interfaces---aka. 'getifaddrs'.
1562 ;; Network interfaces. XXX: We would call it <network-interface> but that
1563 ;; would collide with the ioctl wrappers above.
1564 (define-record-type <interface>
1565 (make-interface name flags address netmask broadcast-address)
1567 (name interface-name) ;string
1568 (flags interface-flags) ;or'd IFF_* values
1569 (address interface-address) ;sockaddr | #f
1570 (netmask interface-netmask) ;sockaddr | #f
1571 (broadcast-address interface-broadcast-address)) ;sockaddr | #f
1573 (define (write-interface interface port)
1575 (($ <interface> name flags address)
1576 (format port "#<interface ~s " name)
1577 (unless (zero? (logand IFF_UP flags))
1578 (display "up " port))
1580 ;; Check whether ADDRESS really is a sockaddr.
1582 (if (member (sockaddr:fam address) (list AF_INET AF_INET6))
1583 (format port "~a " (inet-ntop (sockaddr:fam address)
1584 (sockaddr:addr address)))
1585 (format port "family:~a " (sockaddr:fam address))))
1587 (format port "~a>" (number->string (object-address interface) 16)))))
1589 (set-record-type-printer! <interface> write-interface)
1591 (define (values->interface next name flags address netmask
1592 broadcast-address data)
1593 "Given the raw field values passed as arguments, return a pair whose car is
1594 an <interface> object, and whose cdr is the pointer NEXT."
1595 (define (maybe-socket-address pointer)
1596 (if (null-pointer? pointer)
1598 (read-socket-address (pointer->bytevector pointer 50)))) ;XXX: size
1600 (cons (make-interface (if (null-pointer? name)
1602 (pointer->string name))
1604 (maybe-socket-address address)
1605 (maybe-socket-address netmask)
1606 (maybe-socket-address broadcast-address)
1611 (define-c-struct ifaddrs ;<ifaddrs.h>
1618 (flags unsigned-int)
1624 (define (unfold-interface-list ptr)
1625 "Call 'read-ifaddrs' on PTR and all its 'next' fields, recursively, and
1626 return the list of resulting <interface> objects."
1627 (let loop ((ptr ptr)
1629 (if (null-pointer? ptr)
1631 (match (read-ifaddrs (pointer->bytevector ptr %sizeof-ifaddrs))
1633 (loop ptr (cons ifaddr result)))))))
1635 (define network-interfaces
1636 (let ((proc (syscall->procedure int "getifaddrs" (list '*))))
1638 "Return a list of <interface> objects, each denoting a configured
1639 network interface. This is implemented using the 'getifaddrs' libc function."
1640 (let*-values (((ptr)
1641 (bytevector->pointer (make-bytevector (sizeof* '*))))
1645 (let* ((ptr (dereference-pointer ptr))
1646 (result (unfold-interface-list ptr)))
1649 (throw 'system-error "network-interfaces" "~A"
1650 (list (strerror err))
1653 (define free-ifaddrs
1654 (syscall->procedure void "freeifaddrs" '(*)))
1661 (define-syntax bits->symbols-body
1665 ((_ bits (name names ...) (value values ...))
1666 (let ((result (bits->symbols-body bits (names ...) (values ...))))
1667 (if (zero? (logand bits value))
1669 (cons 'name result))))))
1671 (define-syntax define-bits
1672 (syntax-rules (define)
1673 "Define the given numerical constants under CONSTRUCTOR, such that
1674 (CONSTRUCTOR NAME) returns VALUE. Define BITS->SYMBOLS as a procedure that,
1675 given an integer, returns the list of names of the constants that are or'd."
1676 ((_ constructor bits->symbols (define names values) ...)
1678 (define-syntax constructor
1679 (syntax-rules (names ...)
1681 ((_ names) values) ...
1682 ((_ first rest (... ...))
1683 (logior (constructor first) rest (... ...)))))
1684 (define (bits->symbols bits)
1685 (bits->symbols-body bits (names ...) (values ...)))))))
1687 ;; 'local-flags' bits from <bits/termios.h>
1688 (define-bits local-flags
1689 local-flags->symbols
1690 (define ISIG #o0000001)
1691 (define ICANON #o0000002)
1692 (define XCASE #o0000004)
1693 (define ECHO #o0000010)
1694 (define ECHOE #o0000020)
1695 (define ECHOK #o0000040)
1696 (define ECHONL #o0000100)
1697 (define NOFLSH #o0000200)
1698 (define TOSTOP #o0000400)
1699 (define ECHOCTL #o0001000)
1700 (define ECHOPRT #o0002000)
1701 (define ECHOKE #o0004000)
1702 (define FLUSHO #o0010000)
1703 (define PENDIN #o0040000)
1704 (define IEXTEN #o0100000)
1705 (define EXTPROC #o0200000))
1707 ;; "Actions" values for 'tcsetattr'.
1708 (define-bits tcsetattr-action
1709 %unused-tcsetattr-action->symbols
1711 (define TCSADRAIN 1)
1712 (define TCSAFLUSH 2))
1714 (define-record-type <termios>
1715 (termios input-flags output-flags control-flags local-flags
1716 line-discipline control-chars
1717 input-speed output-speed)
1719 (input-flags termios-input-flags)
1720 (output-flags termios-output-flags)
1721 (control-flags termios-control-flags)
1722 (local-flags termios-local-flags)
1723 (line-discipline termios-line-discipline)
1724 (control-chars termios-control-chars)
1725 (input-speed termios-input-speed)
1726 (output-speed termios-output-speed))
1728 (define-c-struct %termios ;<bits/termios.h>
1733 (input-flags unsigned-int)
1734 (output-flags unsigned-int)
1735 (control-flags unsigned-int)
1736 (local-flags unsigned-int)
1737 (line-discipline uint8)
1738 (control-chars (array uint8 32))
1739 (input-speed unsigned-int)
1740 (output-speed unsigned-int))
1743 (let ((proc (syscall->procedure int "tcgetattr" (list int '*))))
1745 "Return the <termios> structure for the tty at FD."
1746 (let*-values (((bv) (make-bytevector sizeof-termios))
1747 ((ret err) (proc fd (bytevector->pointer bv))))
1750 (throw 'system-error "tcgetattr" "~A"
1751 (list (strerror err))
1755 (let ((proc (syscall->procedure int "tcsetattr" (list int int '*))))
1756 (lambda (fd actions termios)
1757 "Use TERMIOS for the tty at FD. ACTIONS is one of of the values
1758 produced by 'tcsetattr-action'; see tcsetattr(3) for details."
1760 (make-bytevector sizeof-termios))
1762 (let-syntax ((match/write (syntax-rules ()
1765 (($ <termios> fields ...)
1766 (write-termios! bv 0 fields ...)))))))
1767 (match/write input-flags output-flags control-flags local-flags
1768 line-discipline control-chars input-speed output-speed))
1770 (let-values (((ret err) (proc fd actions (bytevector->pointer bv))))
1772 (throw 'system-error "tcgetattr" "~A"
1773 (list (strerror err))
1776 (define-syntax TIOCGWINSZ ;<asm-generic/ioctls.h>
1777 (identifier-syntax #x5413))
1779 (define-record-type <window-size>
1780 (window-size rows columns x-pixels y-pixels)
1782 (rows window-size-rows)
1783 (columns window-size-columns)
1784 (x-pixels window-size-x-pixels)
1785 (y-pixels window-size-y-pixels))
1787 (define-c-struct winsize ;<bits/ioctl-types.h>
1792 (rows unsigned-short)
1793 (columns unsigned-short)
1794 (x-pixels unsigned-short)
1795 (y-pixels unsigned-short))
1797 (define* (terminal-window-size #:optional (port (current-output-port)))
1798 "Return a <window-size> structure describing the terminal at PORT, or raise
1799 a 'system-error' if PORT is not backed by a terminal. This procedure
1800 corresponds to the TIOCGWINSZ ioctl."
1801 (let*-values (((size) (make-bytevector sizeof-winsize))
1802 ((ret err) (%ioctl (fileno port) TIOCGWINSZ
1803 (bytevector->pointer size))))
1806 (throw 'system-error "terminal-window-size" "~A"
1807 (list (strerror err))
1810 (define* (terminal-columns #:optional (port (current-output-port)))
1811 "Return the best approximation of the number of columns of the terminal at
1812 PORT, trying to guess a reasonable value if all else fails. The result is
1813 always a positive integer."
1815 (match (and=> (getenv "COLUMNS") string->number)
1817 ((? number? columns)
1818 (if (> columns 0) columns 80))))
1820 (catch 'system-error
1822 (if (file-port? port)
1823 (match (window-size-columns (terminal-window-size port))
1824 ;; Things like Emacs shell-mode return 0, which is unreasonable.
1826 ((? number? columns) columns))
1829 (let ((errno (system-error-errno args)))
1830 ;; ENOTTY is what we're after but 2012-and-earlier Linux versions
1831 ;; would return EINVAL instead in some cases:
1832 ;; <https://bugs.ruby-lang.org/issues/10494>.
1833 ;; Furthermore, some FUSE file systems like unionfs return ENOSYS for
1835 (if (memv errno (list ENOTTY EINVAL ENOSYS))
1837 (apply throw args))))))
1844 (define-record-type <utmpx-entry>
1845 (utmpx type pid line id user host termination exit
1846 session time address)
1848 (type utmpx-login-type) ;login-type
1850 (line utmpx-line) ;device name
1852 (user utmpx-user) ;user name
1853 (host utmpx-host) ;host name | #f
1854 (termination utmpx-termination-status)
1855 (exit utmpx-exit-status)
1856 (session utmpx-session-id) ;session ID, for windowing
1857 (time utmpx-time) ;entry time
1858 (address utmpx-address))
1860 (define-c-struct %utmpx ;<utmpx.h>
1862 (lambda (type pid line id user host termination exit session
1863 seconds useconds address %reserved)
1865 (bytes->string line) id
1866 (bytes->string user)
1867 (bytes->string host) termination exit
1869 (make-time time-utc (* 1000 useconds) seconds)
1875 (line (array uint8 32))
1876 (id (array uint8 4))
1877 (user (array uint8 32))
1878 (host (array uint8 256))
1882 (time-seconds int32)
1883 (time-useconds int32)
1884 (address-v6 (array int32 4))
1885 (%reserved (array uint8 20)))
1887 (define-bits login-type
1888 %unused-login-type->symbols
1889 (define EMPTY 0) ;No valid user accounting information.
1890 (define RUN_LVL 1) ;The system's runlevel.
1891 (define BOOT_TIME 2) ;Time of system boot.
1892 (define NEW_TIME 3) ;Time after system clock changed.
1893 (define OLD_TIME 4) ;Time when system clock changed.
1895 (define INIT_PROCESS 5) ;Process spawned by the init process.
1896 (define LOGIN_PROCESS 6) ;Session leader of a logged in user.
1897 (define USER_PROCESS 7) ;Normal process.
1898 (define DEAD_PROCESS 8) ;Terminated process.
1900 (define ACCOUNTING 9)) ;System accounting.
1903 (let ((proc (syscall->procedure void "setutxent" '())))
1905 "Open the user accounting database."
1909 (let ((proc (syscall->procedure void "endutxent" '())))
1911 "Close the user accounting database."
1915 (let ((proc (syscall->procedure '* "getutxent" '())))
1917 "Return the next entry from the user accounting database."
1919 (if (null-pointer? ptr)
1921 (read-utmpx (pointer->bytevector ptr sizeof-utmpx)))))))
1923 (define (utmpx-entries)
1924 "Return the list of entries read from the user accounting database."
1926 (let loop ((entries '()))
1932 (loop (cons entry entries))))))
1934 (define (read-utmpx-from-port port)
1935 "Read a utmpx entry from PORT. Return either the EOF object or a utmpx
1937 (match (get-bytevector-n port sizeof-utmpx)
1938 ((? eof-object? eof)
1943 ;;; syscalls.scm ends here