1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2014, 2015, 2016 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
4 ;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
6 ;;; This file is part of GNU Guix.
8 ;;; GNU Guix is free software; you can redistribute it and/or modify it
9 ;;; under the terms of the GNU General Public License as published by
10 ;;; the Free Software Foundation; either version 3 of the License, or (at
11 ;;; your option) any later version.
13 ;;; GNU Guix is distributed in the hope that it will be useful, but
14 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;;; GNU General Public License for more details.
18 ;;; You should have received a copy of the GNU General Public License
19 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
21 (define-module (guix build syscalls)
22 #:use-module (system foreign)
23 #:use-module (rnrs bytevectors)
24 #:use-module (srfi srfi-1)
25 #:use-module (srfi srfi-9)
26 #:use-module (srfi srfi-9 gnu)
27 #:use-module (ice-9 rdelim)
28 #:use-module (ice-9 regex)
29 #:use-module (ice-9 match)
30 #:use-module (ice-9 ftw)
53 file-system-block-size
54 file-system-block-count
55 file-system-blocks-free
56 file-system-blocks-available
57 file-system-file-count
58 file-system-free-file-nodes
59 file-system-identifier
60 file-system-maximum-name-length
61 file-system-fragment-size
62 file-system-mount-flags
87 all-network-interface-names
88 network-interface-names
89 network-interface-flags
90 loopback-network-interface?
91 network-interface-address
92 set-network-interface-flags
93 set-network-interface-address
94 set-network-interface-up
95 configure-network-interface
102 interface-broadcast-address
108 termios-control-flags
110 termios-line-discipline
111 termios-control-chars
129 ;;; This module provides bindings to libc's syscall wrappers. It uses the
130 ;;; FFI, and thus requires a dynamically-linked Guile. (For statically-linked
131 ;;; Guile, we instead apply 'guile-linux-syscalls.patch'.)
137 ;;; Packed structures.
140 (define-syntax sizeof*
141 ;; XXX: This duplicates 'compile-time-value'.
142 (syntax-rules (int128 array)
146 (* (sizeof* type) n))
148 (let-syntax ((v (lambda (s)
149 (let ((val (sizeof type)))
154 (define-syntax alignof*
155 ;; XXX: This duplicates 'compile-time-value'.
156 (syntax-rules (int128 array)
162 (let-syntax ((v (lambda (s)
163 (let ((val (alignof type)))
168 (define-syntax align ;as found in (system foreign)
170 "Add to OFFSET whatever it takes to get proper alignment for TYPE."
171 ((_ offset (type ~ endianness))
174 (1+ (logior (1- offset) (1- (alignof* type)))))))
176 (define-syntax type-size
183 (define-syntax struct-alignment
185 "Compute the alignment for the aggregate made of TYPES at OFFSET. The
186 result is the alignment of the \"most strictly aligned component\"."
187 ((_ offset types ...)
188 (max (align offset types) ...))))
190 (define-syntax struct-size
192 "Return the size in bytes of the structure made of TYPES."
193 ((_ offset (types-processed ...))
194 ;; The SysV ABI P.S. says: "Aggregates (structures and arrays) and unions
195 ;; assume the alignment of their most strictly aligned component." As an
196 ;; example, a struct such as "int32, int16" has size 8, not 6.
197 (1+ (logior (1- offset)
198 (1- (struct-alignment offset types-processed ...)))))
199 ((_ offset (types-processed ...) type0 types ...)
200 (struct-size (+ (type-size type0) (align offset type0))
201 (type0 types-processed ...)
204 (define-syntax write-type
205 (syntax-rules (~ array)
206 ((_ bv offset (type ~ order) value)
207 (bytevector-uint-set! bv offset value
208 (endianness order) (sizeof* type)))
209 ((_ bv offset (array type n) value)
216 (write-type bv o type head)
217 (loop (+ 1 i) tail (+ o (sizeof* type))))))))
218 ((_ bv offset type value)
219 (bytevector-uint-set! bv offset value
220 (native-endianness) (sizeof* type)))))
222 (define-syntax write-types
226 ((_ bv offset (type0 types ...) (field0 fields ...))
228 (write-type bv (align offset type0) type0 field0)
230 (+ (align offset type0) (type-size type0))
231 (types ...) (fields ...))))))
233 (define-syntax read-type
234 (syntax-rules (~ array quote *)
236 (make-pointer (bytevector-uint-ref bv offset
239 ((_ bv offset (type ~ order))
240 (bytevector-uint-ref bv offset
241 (endianness order) (sizeof* type)))
242 ((_ bv offset (array type n))
243 (unfold (lambda (i) (= i n))
245 (read-type bv (+ offset (* i (sizeof* type))) type))
249 (bytevector-uint-ref bv offset
250 (native-endianness) (sizeof* type)))))
252 (define-syntax read-types
254 ((_ return bv offset () (values ...))
256 ((_ return bv offset (type0 types ...) (values ...))
259 (+ (align offset type0) (type-size type0))
261 (values ... (read-type bv
265 (define-syntax define-c-struct
267 "Define SIZE as the size in bytes of the C structure made of FIELDS. READ
268 as a deserializer and WRITE! as a serializer for the C structure with the
269 given TYPES. READ uses WRAP-FIELDS to return its value."
270 ((_ name size wrap-fields read write! (fields types) ...)
273 (struct-size 0 () types ...))
274 (define (write! bv offset fields ...)
275 (write-types bv offset (types ...) (fields ...)))
276 (define* (read bv #:optional (offset 0))
277 (read-types wrap-fields bv offset (types ...) ()))))))
284 (define %libc-errno-pointer
285 ;; Glibc's 'errno' pointer.
286 (let ((errno-loc (dynamic-func "__errno_location" (dynamic-link))))
288 (let ((proc (pointer->procedure '* errno-loc '())))
292 (if %libc-errno-pointer
293 (let ((bv (pointer->bytevector %libc-errno-pointer (sizeof int))))
295 "Return the current errno."
296 ;; XXX: We assume that nothing changes 'errno' while we're doing all this.
297 ;; In particular, that means that no async must be running here.
299 ;; Use one of the fixed-size native-ref procedures because they are
300 ;; optimized down to a single VM instruction, which reduces the risk
301 ;; that we fiddle with 'errno' (needed on Guile 2.0.5, libc 2.11.)
302 (let-syntax ((ref (lambda (s)
307 #'(bytevector-s32-native-ref bv 0))
309 #'(bytevector-s64-native-ref bv 0))
311 (error "unsupported 'int' size"
316 (define (call-with-restart-on-EINTR thunk)
321 (if (= (system-error-errno args) EINTR)
323 (apply throw args))))))
325 (define-syntax-rule (restart-on-EINTR expr)
326 "Evaluate EXPR and restart upon EINTR. Return the value of EXPR."
327 (call-with-restart-on-EINTR (lambda () expr)))
329 (define (syscall->procedure return-type name argument-types)
330 "Return a procedure that wraps the C function NAME using the dynamic FFI.
331 If an error occurs while creating the binding, defer the error report until
332 the returned procedure is called."
335 (let ((ptr (dynamic-func name (dynamic-link))))
336 (pointer->procedure return-type ptr argument-types)))
339 (error (format #f "~a: syscall->procedure failed: ~s"
347 (define (augment-mtab source target type options)
348 "Augment /etc/mtab with information about the given mount point."
349 (let ((port (open-file "/etc/mtab" "a")))
350 (format port "~a ~a ~a ~a 0 0~%"
351 source target type (or options "rw"))
354 (define (read-mtab port)
355 "Read an mtab-formatted file from PORT, returning a list of tuples."
356 (let loop ((result '()))
357 (let ((line (read-line port)))
358 (if (eof-object? line)
360 (loop (cons (string-tokenize line) result))))))
362 (define (remove-from-mtab target)
363 "Remove mount point TARGET from /etc/mtab."
365 (remove (match-lambda
366 ((device mount-point type options freq passno)
367 (string=? target mount-point))
369 (call-with-input-file "/etc/mtab" read-mtab)))
371 (call-with-output-file "/etc/mtab"
373 (for-each (match-lambda
374 ((device mount-point type options freq passno)
375 (format port "~a ~a ~a ~a ~a ~a~%"
376 device mount-point type options freq passno)))
379 ;; Linux mount flags, from libc's <sys/mount.h>.
384 (define MS_REMOUNT 32)
385 (define MS_BIND 4096)
386 (define MS_MOVE 8192)
387 (define MS_STRICTATIME 16777216)
390 (define MNT_DETACH 2)
391 (define MNT_EXPIRE 4)
392 (define UMOUNT_NOFOLLOW 8)
395 (let ((proc (syscall->procedure int "mount" `(* * * ,unsigned-long *))))
396 (lambda* (source target type #:optional (flags 0) options
397 #:key (update-mtab? #f))
398 "Mount device SOURCE on TARGET as a file system TYPE. Optionally, FLAGS
399 may be a bitwise-or of the MS_* <sys/mount.h> constants, and OPTIONS may be a
400 string. When FLAGS contains MS_REMOUNT, SOURCE and TYPE are ignored. When
401 UPDATE-MTAB? is true, update /etc/mtab. Raise a 'system-error' exception on
403 (let ((ret (proc (if source
404 (string->pointer source)
406 (string->pointer target)
408 (string->pointer type)
412 (string->pointer options)
416 (throw 'system-error "mount" "mount ~S on ~S: ~A"
417 (list source target (strerror err))
420 (augment-mtab source target type options))))))
423 (let ((proc (syscall->procedure int "umount2" `(* ,int))))
424 (lambda* (target #:optional (flags 0)
425 #:key (update-mtab? #f))
426 "Unmount TARGET. Optionally FLAGS may be one of the MNT_* or UMOUNT_*
427 constants from <sys/mount.h>."
428 (let ((ret (proc (string->pointer target) flags))
431 (throw 'system-error "umount" "~S: ~A"
432 (list target (strerror err))
435 (remove-from-mtab target))))))
437 (define (mount-points)
438 "Return the mounts points for currently mounted file systems."
439 (call-with-input-file "/proc/mounts"
441 (let loop ((result '()))
442 (let ((line (read-line port)))
443 (if (eof-object? line)
445 (match (string-tokenize line)
446 ((source mount-point _ ...)
447 (loop (cons mount-point result))))))))))
450 (let ((proc (syscall->procedure int "swapon" (list '* int))))
451 (lambda* (device #:optional (flags 0))
452 "Use the block special device at DEVICE for swapping."
453 (let ((ret (proc (string->pointer device) flags))
456 (throw 'system-error "swapon" "~S: ~A"
457 (list device (strerror err))
461 (let ((proc (syscall->procedure int "swapoff" '(*))))
463 "Stop using block special device DEVICE for swapping."
464 (let ((ret (proc (string->pointer device)))
467 (throw 'system-error "swapoff" "~S: ~A"
468 (list device (strerror err))
471 (define (kernel? pid)
472 "Return #t if PID designates a \"kernel thread\" rather than a normal
474 (let ((stat (call-with-input-file (format #f "/proc/~a/stat" pid)
475 (compose string-tokenize read-string))))
476 ;; See proc.txt in Linux's documentation for the list of fields.
478 ((pid tcomm state ppid pgrp sid tty_nr tty_pgrp flags min_flt
479 cmin_flt maj_flt cmaj_flt utime stime cutime cstime
480 priority nice num_thread it_real_value start_time
482 (= string->number start_code) (= string->number end_code) _ ...)
483 ;; Got this obscure trick from sysvinit's 'killall5' program.
484 (and (zero? start_code) (zero? end_code))))))
487 "Return the list of live processes."
488 (sort (filter-map (lambda (file)
489 (let ((pid (string->number file)))
497 (let ((proc (syscall->procedure '* "mkdtemp" '(*))))
499 "Create a new unique directory in the file system using the template
500 string TMPL and return its file name. TMPL must end with 'XXXXXX'."
501 (let ((result (proc (string->pointer tmpl)))
503 (when (null-pointer? result)
504 (throw 'system-error "mkdtemp!" "~S: ~A"
505 (list tmpl (strerror err))
507 (pointer->string result)))))
510 (let ((proc (syscall->procedure int "fdatasync" (list int))))
512 "Flush buffered output of PORT, an output file port, and then call
513 fdatasync(2) on the underlying file descriptor."
515 (let* ((fd (fileno port))
519 (throw 'system-error "fdatasync" "~S: ~A"
520 (list fd (strerror err))
524 (define-record-type <file-system>
525 (file-system type block-size blocks blocks-free
526 blocks-available files free-files identifier
527 name-length fragment-size mount-flags spare)
529 (type file-system-type)
530 (block-size file-system-block-size)
531 (blocks file-system-block-count)
532 (blocks-free file-system-blocks-free)
533 (blocks-available file-system-blocks-available)
534 (files file-system-file-count)
535 (free-files file-system-free-file-nodes)
536 (identifier file-system-identifier)
537 (name-length file-system-maximum-name-length)
538 (fragment-size file-system-fragment-size)
539 (mount-flags file-system-mount-flags)
540 (spare file-system--spare))
542 (define-syntax fsword ;fsword_t
543 (identifier-syntax long))
545 (define-c-struct %statfs ;<bits/statfs.h>
546 sizeof-statfs ;slightly overestimated
554 (blocks-available uint64)
557 (identifier (array int 2))
559 (fragment-size fsword)
561 (spare (array fsword 4)))
564 (let ((proc (syscall->procedure int "statfs64" '(* *))))
566 "Return a <file-system> data structure describing the file system
568 (let* ((stat (make-bytevector sizeof-statfs))
569 (ret (proc (string->pointer file) (bytevector->pointer stat)))
573 (throw 'system-error "statfs" "~A: ~A"
574 (list file (strerror err))
582 ;; Linux clone flags, from linux/sched.h
583 (define CLONE_CHILD_CLEARTID #x00200000)
584 (define CLONE_CHILD_SETTID #x01000000)
585 (define CLONE_NEWNS #x00020000)
586 (define CLONE_NEWUTS #x04000000)
587 (define CLONE_NEWIPC #x08000000)
588 (define CLONE_NEWUSER #x10000000)
589 (define CLONE_NEWPID #x20000000)
590 (define CLONE_NEWNET #x40000000)
592 ;; The libc interface to sys_clone is not useful for Scheme programs, so the
593 ;; low-level system call is wrapped instead. The 'syscall' function is
594 ;; declared in <unistd.h> as a variadic function; in practice, it expects 6
595 ;; pointer-sized arguments, as shown in, e.g., x86_64/syscall.S.
597 (let* ((proc (syscall->procedure int "syscall"
602 ;; TODO: Don't do this.
603 (syscall-id (match (utsname:machine (uname))
610 "Create a new child process by duplicating the current parent process.
611 Unlike the fork system call, clone accepts FLAGS that specify which resources
612 are shared between the parent and child processes."
613 (let ((ret (proc syscall-id flags
614 %null-pointer ;child stack
615 %null-pointer %null-pointer ;ptid & ctid
616 %null-pointer)) ;unused
619 (throw 'system-error "clone" "~d: ~A"
620 (list flags (strerror err))
625 ;; Some systems may be using an old (pre-2.14) version of glibc where there
626 ;; is no 'setns' function available.
628 (let ((proc (syscall->procedure int "setns" (list int int))))
629 (lambda (fdes nstype)
630 "Reassociate the current process with the namespace specified by FDES, a
631 file descriptor obtained by opening a /proc/PID/ns/* file. NSTYPE specifies
632 which type of namespace the current process may be reassociated with, or 0 if
633 there is no such limitation."
634 (let ((ret (proc fdes nstype))
637 (throw 'system-error "setns" "~d ~d: ~A"
638 (list fdes nstype (strerror err))
642 (let ((proc (syscall->procedure int "pivot_root" (list '* '*))))
643 (lambda (new-root put-old)
644 "Change the root file system to NEW-ROOT and move the current root file
646 (let ((ret (proc (string->pointer new-root)
647 (string->pointer put-old)))
650 (throw 'system-error "pivot_root" "~S ~S: ~A"
651 (list new-root put-old (strerror err))
656 ;;; Advisory file locking.
659 (define-c-struct %struct-flock ;<fcntl.h>
671 ;; On Linux-based systems, this is usually 7, but not always
672 ;; (exceptions include SPARC.) On GNU/Hurd, it's 9.
673 (cond ((string-contains %host-type "sparc") 9) ; sparc-*-linux-gnu
674 ((string-contains %host-type "linux") 7) ; *-linux-gnu
678 ;; Likewise: GNU/Hurd and SPARC use 8, while the others typically use 6.
679 (cond ((string-contains %host-type "sparc") 8) ; sparc-*-linux-gnu
680 ((string-contains %host-type "linux") 6) ; *-linux-gnu
684 ;; The F_RDLCK, F_WRLCK, and F_UNLCK constants.
685 (cond ((string-contains %host-type "sparc") #(1 2 3)) ; sparc-*-linux-gnu
686 ((string-contains %host-type "hppa") #(1 2 3)) ; hppa-*-linux-gnu
687 ((string-contains %host-type "linux") #(0 1 2)) ; *-linux-gnu
688 (else #(1 2 3)))) ; *-gnu*
691 (let ((proc (syscall->procedure int "fcntl" `(,int ,int *))))
692 (lambda* (fd-or-port operation #:key (wait? #t))
693 "Perform locking OPERATION on the file beneath FD-OR-PORT. OPERATION
694 must be a symbol, one of 'read-lock, 'write-lock, or 'unlock. When WAIT? is
695 true, block until the lock is acquired; otherwise, thrown an 'flock-error'
696 exception if it's already taken."
697 (define (operation->int op)
699 ((read-lock) (vector-ref F_xxLCK 0))
700 ((write-lock) (vector-ref F_xxLCK 1))
701 ((unlock) (vector-ref F_xxLCK 2))
702 (else (error "invalid fcntl-flock operation" op))))
705 (if (port? fd-or-port)
710 (make-bytevector sizeof-flock))
713 (operation->int operation) SEEK_SET
717 ;; XXX: 'fcntl' is a vararg function, but here we happily use the
718 ;; standard ABI; crossing fingers.
721 F_SETLKW ; lock & wait
722 F_SETLK) ; non-blocking attempt
723 (bytevector->pointer bv)))
726 ;; Presumably we got EAGAIN or so.
727 (throw 'flock-error err))))))
731 ;;; Network interfaces.
734 (define SIOCGIFCONF ;from <bits/ioctls.h>
735 (if (string-contains %host-type "linux")
737 #xf00801a4)) ;GNU/Hurd
739 (if (string-contains %host-type "linux")
741 #xc4804191)) ;GNU/Hurd
743 (if (string-contains %host-type "linux")
745 -1)) ;FIXME: GNU/Hurd?
747 (if (string-contains %host-type "linux")
749 -1)) ;FIXME: GNU/Hurd?
751 (if (string-contains %host-type "linux")
753 -1)) ;FIXME: GNU/Hurd?
755 ;; Flags and constants from <net/if.h>.
757 (define IFF_UP #x1) ;Interface is up
758 (define IFF_BROADCAST #x2) ;Broadcast address valid.
759 (define IFF_LOOPBACK #x8) ;Is a loopback net.
761 (define IF_NAMESIZE 16) ;maximum interface name size
763 (define ifconf-struct
764 ;; 'struct ifconf', from <net/if.h>.
765 (list int ;int ifc_len
766 '*)) ;struct ifreq *ifc_ifcu
768 (define ifreq-struct-size
769 ;; 'struct ifreq' begins with an array of IF_NAMESIZE bytes containing the
770 ;; interface name (nul-terminated), followed by a bunch of stuff. This is
771 ;; its size in bytes.
772 (if (= 8 (sizeof '*))
776 (define-c-struct sockaddr-in ;<linux/in.h>
778 (lambda (family port address)
779 (make-socket-address family address port))
782 (family unsigned-short)
784 (address (int32 ~ big)))
786 (define-c-struct sockaddr-in6 ;<linux/in6.h>
788 (lambda (family port flowinfo address scopeid)
789 (make-socket-address family address port flowinfo scopeid))
792 (family unsigned-short)
794 (flowinfo (int32 ~ big))
795 (address (int128 ~ big))
798 (define (write-socket-address! sockaddr bv index)
799 "Write SOCKADDR, a socket address as returned by 'make-socket-address', to
800 bytevector BV at INDEX."
801 (let ((family (sockaddr:fam sockaddr)))
802 (cond ((= family AF_INET)
803 (write-sockaddr-in! bv index
805 (sockaddr:port sockaddr)
806 (sockaddr:addr sockaddr)))
808 (write-sockaddr-in6! bv index
810 (sockaddr:port sockaddr)
811 (sockaddr:flowinfo sockaddr)
812 (sockaddr:addr sockaddr)
813 (sockaddr:scopeid sockaddr)))
815 (error "unsupported socket address" sockaddr)))))
817 (define PF_PACKET 17) ;<bits/socket.h>
818 (define AF_PACKET PF_PACKET)
820 (define* (read-socket-address bv #:optional (index 0))
821 "Read a socket address from bytevector BV at INDEX."
822 (let ((family (bytevector-u16-native-ref bv index)))
823 (cond ((= family AF_INET)
824 (read-sockaddr-in bv index))
826 (read-sockaddr-in6 bv index))
828 ;; XXX: Unsupported address family, such as AF_PACKET. Return a
829 ;; vector such that the vector can at least call 'sockaddr:fam'.
833 ;; The most terrible interface, live from Scheme.
834 (syscall->procedure int "ioctl" (list int unsigned-long '*)))
836 (define (bytevector->string-list bv stride len)
837 "Return the null-terminated strings found in BV every STRIDE bytes. Read at
838 most LEN bytes from BV."
839 (let loop ((bytes (take (bytevector->u8-list bv)
840 (min len (bytevector-length bv))))
846 (loop (drop bytes stride)
847 (cons (list->string (map integer->char
848 (take-while (negate zero?) bytes)))
851 (define* (network-interface-names #:optional sock)
852 "Return the names of existing network interfaces. This is typically limited
853 to interfaces that are currently up."
854 (let* ((close? (not sock))
855 (sock (or sock (socket SOCK_STREAM AF_INET 0)))
856 (len (* ifreq-struct-size 10))
857 (reqs (make-bytevector len))
858 (conf (make-c-struct ifconf-struct
859 (list len (bytevector->pointer reqs))))
860 (ret (%ioctl (fileno sock) SIOCGIFCONF conf))
865 (bytevector->string-list reqs ifreq-struct-size
866 (match (parse-c-struct conf ifconf-struct)
868 (throw 'system-error "network-interface-list"
869 "network-interface-list: ~A"
870 (list (strerror err))
873 (define %interface-line
874 ;; Regexp matching an interface line in Linux's /proc/net/dev.
875 (make-regexp "^[[:blank:]]*([[:graph:]]+):.*$"))
877 (define (all-network-interface-names)
878 "Return all the names of the registered network interfaces, including those
880 (call-with-input-file "/proc/net/dev" ;XXX: Linux-specific
882 (let loop ((interfaces '()))
883 (let ((line (read-line port)))
884 (cond ((eof-object? line)
885 (reverse interfaces))
886 ((regexp-exec %interface-line line)
889 (loop (cons (match:substring match 1) interfaces))))
891 (loop interfaces))))))))
893 (define (network-interface-flags socket name)
894 "Return a number that is the bit-wise or of 'IFF*' flags for network
896 (let ((req (make-bytevector ifreq-struct-size)))
897 (bytevector-copy! (string->utf8 name) 0 req 0
898 (min (string-length name) (- IF_NAMESIZE 1)))
899 (let* ((ret (%ioctl (fileno socket) SIOCGIFFLAGS
900 (bytevector->pointer req)))
904 ;; The 'ifr_flags' field is IF_NAMESIZE bytes after the beginning of
905 ;; 'struct ifreq', and it's a short int.
906 (bytevector-sint-ref req IF_NAMESIZE (native-endianness)
909 (throw 'system-error "network-interface-flags"
910 "network-interface-flags on ~A: ~A"
911 (list name (strerror err))
914 (define (loopback-network-interface? name)
915 "Return true if NAME designates a loopback network interface."
916 (let* ((sock (socket SOCK_STREAM AF_INET 0))
917 (flags (network-interface-flags sock name)))
919 (not (zero? (logand flags IFF_LOOPBACK)))))
921 (define (set-network-interface-flags socket name flags)
922 "Set the flag of network interface NAME to FLAGS."
923 (let ((req (make-bytevector ifreq-struct-size)))
924 (bytevector-copy! (string->utf8 name) 0 req 0
925 (min (string-length name) (- IF_NAMESIZE 1)))
926 ;; Set the 'ifr_flags' field.
927 (bytevector-uint-set! req IF_NAMESIZE flags (native-endianness)
929 (let* ((ret (%ioctl (fileno socket) SIOCSIFFLAGS
930 (bytevector->pointer req)))
933 (throw 'system-error "set-network-interface-flags"
934 "set-network-interface-flags on ~A: ~A"
935 (list name (strerror err))
938 (define (set-network-interface-address socket name sockaddr)
939 "Set the address of network interface NAME to SOCKADDR."
940 (let ((req (make-bytevector ifreq-struct-size)))
941 (bytevector-copy! (string->utf8 name) 0 req 0
942 (min (string-length name) (- IF_NAMESIZE 1)))
943 ;; Set the 'ifr_addr' field.
944 (write-socket-address! sockaddr req IF_NAMESIZE)
945 (let* ((ret (%ioctl (fileno socket) SIOCSIFADDR
946 (bytevector->pointer req)))
949 (throw 'system-error "set-network-interface-address"
950 "set-network-interface-address on ~A: ~A"
951 (list name (strerror err))
954 (define (network-interface-address socket name)
955 "Return the address of network interface NAME. The result is an object of
956 the same type as that returned by 'make-socket-address'."
957 (let ((req (make-bytevector ifreq-struct-size)))
958 (bytevector-copy! (string->utf8 name) 0 req 0
959 (min (string-length name) (- IF_NAMESIZE 1)))
960 (let* ((ret (%ioctl (fileno socket) SIOCGIFADDR
961 (bytevector->pointer req)))
964 (read-socket-address req IF_NAMESIZE)
965 (throw 'system-error "network-interface-address"
966 "network-interface-address on ~A: ~A"
967 (list name (strerror err))
970 (define (configure-network-interface name sockaddr flags)
971 "Configure network interface NAME to use SOCKADDR, an address as returned by
972 'make-socket-address', and FLAGS, a bitwise-or of IFF_* constants."
973 (let ((sock (socket (sockaddr:fam sockaddr) SOCK_STREAM 0)))
977 (set-network-interface-address sock name sockaddr)
978 (set-network-interface-flags sock name flags))
980 (close-port sock)))))
982 (define* (set-network-interface-up name
983 #:key (family AF_INET))
984 "Turn up the interface NAME."
985 (let ((sock (socket family SOCK_STREAM 0)))
989 (let ((flags (network-interface-flags sock name)))
990 (set-network-interface-flags sock name
991 (logior flags IFF_UP))))
993 (close-port sock)))))
997 ;;; Details about network interfaces---aka. 'getifaddrs'.
1000 ;; Network interfaces. XXX: We would call it <network-interface> but that
1001 ;; would collide with the ioctl wrappers above.
1002 (define-record-type <interface>
1003 (make-interface name flags address netmask broadcast-address)
1005 (name interface-name) ;string
1006 (flags interface-flags) ;or'd IFF_* values
1007 (address interface-address) ;sockaddr | #f
1008 (netmask interface-netmask) ;sockaddr | #f
1009 (broadcast-address interface-broadcast-address)) ;sockaddr | #f
1011 (define (write-interface interface port)
1013 (($ <interface> name flags address)
1014 (format port "#<interface ~s " name)
1015 (unless (zero? (logand IFF_UP flags))
1016 (display "up " port))
1018 ;; Check whether ADDRESS really is a sockaddr.
1020 (if (member (sockaddr:fam address) (list AF_INET AF_INET6))
1021 (format port "~a " (inet-ntop (sockaddr:fam address)
1022 (sockaddr:addr address)))
1023 (format port "family:~a " (sockaddr:fam address))))
1025 (format port "~a>" (number->string (object-address interface) 16)))))
1027 (set-record-type-printer! <interface> write-interface)
1029 (define (values->interface next name flags address netmask
1030 broadcast-address data)
1031 "Given the raw field values passed as arguments, return a pair whose car is
1032 an <interface> object, and whose cdr is the pointer NEXT."
1033 (define (maybe-socket-address pointer)
1034 (if (null-pointer? pointer)
1036 (read-socket-address (pointer->bytevector pointer 50)))) ;XXX: size
1038 (cons (make-interface (if (null-pointer? name)
1040 (pointer->string name))
1042 (maybe-socket-address address)
1043 (maybe-socket-address netmask)
1044 (maybe-socket-address broadcast-address)
1049 (define-c-struct ifaddrs ;<ifaddrs.h>
1056 (flags unsigned-int)
1062 (define (unfold-interface-list ptr)
1063 "Call 'read-ifaddrs' on PTR and all its 'next' fields, recursively, and
1064 return the list of resulting <interface> objects."
1065 (let loop ((ptr ptr)
1067 (if (null-pointer? ptr)
1069 (match (read-ifaddrs (pointer->bytevector ptr %sizeof-ifaddrs))
1071 (loop ptr (cons ifaddr result)))))))
1073 (define network-interfaces
1074 (let ((proc (syscall->procedure int "getifaddrs" (list '*))))
1076 "Return a list of <interface> objects, each denoting a configured
1077 network interface. This is implemented using the 'getifaddrs' libc function."
1078 (let* ((ptr (bytevector->pointer (make-bytevector (sizeof* '*))))
1082 (let* ((ptr (dereference-pointer ptr))
1083 (result (unfold-interface-list ptr)))
1086 (throw 'system-error "network-interfaces" "~A"
1087 (list (strerror err))
1090 (define free-ifaddrs
1091 (syscall->procedure void "freeifaddrs" '(*)))
1098 (define-syntax bits->symbols-body
1102 ((_ bits (name names ...) (value values ...))
1103 (let ((result (bits->symbols-body bits (names ...) (values ...))))
1104 (if (zero? (logand bits value))
1106 (cons 'name result))))))
1108 (define-syntax define-bits
1109 (syntax-rules (define)
1110 "Define the given numerical constants under CONSTRUCTOR, such that
1111 (CONSTRUCTOR NAME) returns VALUE. Define BITS->SYMBOLS as a procedure that,
1112 given an integer, returns the list of names of the constants that are or'd."
1113 ((_ constructor bits->symbols (define names values) ...)
1115 (define-syntax constructor
1116 (syntax-rules (names ...)
1117 ((_ names) values) ...
1118 ((_ several (... ...))
1119 (logior (constructor several) (... ...)))))
1120 (define (bits->symbols bits)
1121 (bits->symbols-body bits (names ...) (values ...)))
1122 (define names values) ...))))
1124 ;; 'local-flags' bits from <bits/termios.h>
1125 (define-bits local-flags
1126 local-flags->symbols
1127 (define ISIG #o0000001)
1128 (define ICANON #o0000002)
1129 (define XCASE #o0000004)
1130 (define ECHO #o0000010)
1131 (define ECHOE #o0000020)
1132 (define ECHOK #o0000040)
1133 (define ECHONL #o0000100)
1134 (define NOFLSH #o0000200)
1135 (define TOSTOP #o0000400)
1136 (define ECHOCTL #o0001000)
1137 (define ECHOPRT #o0002000)
1138 (define ECHOKE #o0004000)
1139 (define FLUSHO #o0010000)
1140 (define PENDIN #o0040000)
1141 (define IEXTEN #o0100000)
1142 (define EXTPROC #o0200000))
1144 ;; "Actions" values for 'tcsetattr'.
1145 (define-bits tcsetattr-action
1146 %unused-tcsetattr-action->symbols
1148 (define TCSADRAIN 1)
1149 (define TCSAFLUSH 2))
1151 (define-record-type <termios>
1152 (termios input-flags output-flags control-flags local-flags
1153 line-discipline control-chars
1154 input-speed output-speed)
1156 (input-flags termios-input-flags)
1157 (output-flags termios-output-flags)
1158 (control-flags termios-control-flags)
1159 (local-flags termios-local-flags)
1160 (line-discipline termios-line-discipline)
1161 (control-chars termios-control-chars)
1162 (input-speed termios-input-speed)
1163 (output-speed termios-output-speed))
1165 (define-c-struct %termios ;<bits/termios.h>
1170 (input-flags unsigned-int)
1171 (output-flags unsigned-int)
1172 (control-flags unsigned-int)
1173 (local-flags unsigned-int)
1174 (line-discipline uint8)
1175 (control-chars (array uint8 32))
1176 (input-speed unsigned-int)
1177 (output-speed unsigned-int))
1180 (let ((proc (syscall->procedure int "tcgetattr" (list int '*))))
1182 "Return the <termios> structure for the tty at FD."
1183 (let* ((bv (make-bytevector sizeof-termios))
1184 (ret (proc fd (bytevector->pointer bv)))
1188 (throw 'system-error "tcgetattr" "~A"
1189 (list (strerror err))
1193 (let ((proc (syscall->procedure int "tcsetattr" (list int int '*))))
1194 (lambda (fd actions termios)
1195 "Use TERMIOS for the tty at FD. ACTIONS is one of of the values
1196 produced by 'tcsetattr-action'; see tcsetattr(3) for details."
1198 (make-bytevector sizeof-termios))
1200 (let-syntax ((match/write (syntax-rules ()
1203 (($ <termios> fields ...)
1204 (write-termios! bv 0 fields ...)))))))
1205 (match/write input-flags output-flags control-flags local-flags
1206 line-discipline control-chars input-speed output-speed))
1208 (let ((ret (proc fd actions (bytevector->pointer bv)))
1211 (throw 'system-error "tcgetattr" "~A"
1212 (list (strerror err))
1215 (define-syntax TIOCGWINSZ ;<asm-generic/ioctls.h>
1216 (identifier-syntax #x5413))
1218 (define-record-type <window-size>
1219 (window-size rows columns x-pixels y-pixels)
1221 (rows window-size-rows)
1222 (columns window-size-columns)
1223 (x-pixels window-size-x-pixels)
1224 (y-pixels window-size-y-pixels))
1226 (define-c-struct winsize ;<bits/ioctl-types.h>
1231 (rows unsigned-short)
1232 (columns unsigned-short)
1233 (x-pixels unsigned-short)
1234 (y-pixels unsigned-short))
1236 (define* (terminal-window-size #:optional (port (current-output-port)))
1237 "Return a <window-size> structure describing the terminal at PORT, or raise
1238 a 'system-error' if PORT is not backed by a terminal. This procedure
1239 corresponds to the TIOCGWINSZ ioctl."
1240 (let* ((size (make-bytevector sizeof-winsize))
1241 (ret (%ioctl (fileno port) TIOCGWINSZ
1242 (bytevector->pointer size)))
1246 (throw 'system-error "terminal-window-size" "~A"
1247 (list (strerror err))
1250 (define* (terminal-columns #:optional (port (current-output-port)))
1251 "Return the best approximation of the number of columns of the terminal at
1252 PORT, trying to guess a reasonable value if all else fails. The result is
1253 always a positive integer."
1255 (match (and=> (getenv "COLUMNS") string->number)
1257 ((? number? columns)
1258 (if (> columns 0) columns 80))))
1260 (catch 'system-error
1262 (if (file-port? port)
1263 (match (window-size-columns (terminal-window-size port))
1264 ;; Things like Emacs shell-mode return 0, which is unreasonable.
1266 ((? number? columns) columns))
1269 (let ((errno (system-error-errno args)))
1270 ;; ENOTTY is what we're after but 2012-and-earlier Linux versions
1271 ;; would return EINVAL instead in some cases:
1272 ;; <https://bugs.ruby-lang.org/issues/10494>.
1273 (if (or (= errno ENOTTY) (= errno EINVAL))
1275 (apply throw args))))))
1277 ;;; syscalls.scm ends here