gnu: Add libqglviewer.
[jackhill/guix/guix.git] / guix / build / syscalls.scm
CommitLineData
29fa45f4 1;;; GNU Guix --- Functional package management for GNU
b782688d 2;;; Copyright © 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
577c02eb 3;;; Copyright © 2015 David Thompson <davet@gnu.org>
4f8cede0 4;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
8336df06 5;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
0dc5c856 6;;; Copyright © 2019 Guillaume Le Vaillant <glv@posteo.net>
fd546bbb 7;;; Copyright © 2020 Julien Lepiller <julien@lepiller.eu>
598be42d 8;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
29fa45f4
LC
9;;;
10;;; This file is part of GNU Guix.
11;;;
12;;; GNU Guix is free software; you can redistribute it and/or modify it
13;;; under the terms of the GNU General Public License as published by
14;;; the Free Software Foundation; either version 3 of the License, or (at
15;;; your option) any later version.
16;;;
17;;; GNU Guix is distributed in the hope that it will be useful, but
18;;; WITHOUT ANY WARRANTY; without even the implied warranty of
19;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;;; GNU General Public License for more details.
21;;;
22;;; You should have received a copy of the GNU General Public License
23;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
24
25(define-module (guix build syscalls)
26 #:use-module (system foreign)
86f5decd 27 #:use-module (system base target)
29fa45f4 28 #:use-module (rnrs bytevectors)
3483f004 29 #:autoload (ice-9 binary-ports) (get-bytevector-n)
29fa45f4 30 #:use-module (srfi srfi-1)
e7f5691d
LC
31 #:use-module (srfi srfi-9)
32 #:use-module (srfi srfi-9 gnu)
26ffb693 33 #:use-module (srfi srfi-11)
15030972 34 #:use-module (srfi srfi-19)
fa73c193 35 #:use-module (srfi srfi-26)
29fa45f4 36 #:use-module (ice-9 rdelim)
4d54785c 37 #:use-module (ice-9 regex)
29fa45f4 38 #:use-module (ice-9 match)
17a4d344 39 #:use-module (ice-9 ftw)
26ffb693 40 #:export (MS_RDONLY
577c02eb
DT
41 MS_NOSUID
42 MS_NODEV
43 MS_NOEXEC
29fa45f4 44 MS_REMOUNT
9d305381 45 MS_NOATIME
29fa45f4
LC
46 MS_BIND
47 MS_MOVE
577c02eb 48 MS_STRICTATIME
0dc5c856 49 MS_LAZYTIME
b16d138a
DT
50 MNT_FORCE
51 MNT_DETACH
52 MNT_EXPIRE
53 UMOUNT_NOFOLLOW
25c7ff6a 54
ea982704 55 restart-on-EINTR
ccea821b 56 mount-points
715fc9d4
LC
57 swapon
58 swapoff
a1f70878
LC
59
60 file-system?
61 file-system-type
62 file-system-block-size
63 file-system-block-count
64 file-system-blocks-free
65 file-system-blocks-available
66 file-system-file-count
67 file-system-free-file-nodes
68 file-system-identifier
69 file-system-maximum-name-length
70 file-system-fragment-size
200dac06 71 file-system-mount-flags
a1f70878 72 statfs
65f224dc 73 free-disk-space
b08bea04 74 device-in-use?
5e5f7167 75 add-to-entropy-count
a1f70878 76
7585016f 77 processes
b4abdeb6 78 mkdtemp!
1752a17a 79 fdatasync
df3ce5c1 80 pivot-root
fa73c193 81 scandir*
b7178c22 82
4e0ea3eb 83 fcntl-flock
b7178c22
LC
84 lock-file
85 unlock-file
86 with-file-lock
f49e9131 87 with-file-lock/no-wait
973eea34 88
aa401f9b
LC
89 set-thread-name
90 thread-name
91
ee78d024
DT
92 CLONE_CHILD_CLEARTID
93 CLONE_CHILD_SETTID
8950ed11
DT
94 CLONE_NEWNS
95 CLONE_NEWUTS
96 CLONE_NEWIPC
97 CLONE_NEWUSER
98 CLONE_NEWPID
99 CLONE_NEWNET
100 clone
43ace6ea 101 setns
8950ed11 102
3ca33769
LC
103 PF_PACKET
104 AF_PACKET
b89e7405
LC
105 all-network-interface-names
106 network-interface-names
67e5f3b7 107 network-interface-netmask
0bc6fe32 108 network-interface-running?
c9bf64d6 109 loopback-network-interface?
5f5499d6 110 arp-network-interface?
c9bf64d6 111 network-interface-address
67e5f3b7 112 set-network-interface-netmask
6944fdbd 113 set-network-interface-up
e7f5691d 114 configure-network-interface
9e38e3cf
LC
115 add-network-route/gateway
116 delete-network-route
e7f5691d
LC
117
118 interface?
119 interface-name
120 interface-flags
121 interface-address
122 interface-netmask
123 interface-broadcast-address
29ff6d9f
LC
124 network-interfaces
125
ae4ff9f3
LC
126 termios?
127 termios-input-flags
128 termios-output-flags
129 termios-control-flags
130 termios-local-flags
131 termios-line-discipline
132 termios-control-chars
133 termios-input-speed
134 termios-output-speed
135 local-flags
45c32bd7 136 input-flags
a8f3424b 137 tcsetattr-action
ae4ff9f3
LC
138 tcgetattr
139 tcsetattr
140
29ff6d9f
LC
141 window-size?
142 window-size-rows
143 window-size-columns
144 window-size-x-pixels
145 window-size-y-pixels
146 terminal-window-size
15030972 147 terminal-columns
4593f5a6 148 terminal-rows
15030972
LC
149
150 utmpx?
151 utmpx-login-type
152 utmpx-pid
153 utmpx-line
154 utmpx-id
155 utmpx-user
156 utmpx-host
157 utmpx-termination-status
158 utmpx-exit-status
159 utmpx-session-id
160 utmpx-time
161 utmpx-address
162 login-type
3483f004
LC
163 utmpx-entries
164 (read-utmpx-from-port . read-utmpx)))
29fa45f4
LC
165
166;;; Commentary:
167;;;
168;;; This module provides bindings to libc's syscall wrappers. It uses the
8336df06
MO
169;;; FFI, and thus requires a dynamically-linked Guile.
170;;;
171;;; Some syscalls are already defined in statically-linked Guile by applying
172;;; 'guile-linux-syscalls.patch'.
173;;;
174;;; Visibility of syscall's symbols shared between this module and static Guile
175;;; is a bit delicate. It is handled by 'define-as-needed' macro.
176;;;
177;;; This macro is used to export symbols in dynamic Guile context, and to
178;;; re-export them in static Guile context.
179;;;
180;;; This way, even if they don't appear in #:export list, it is safe to use
181;;; syscalls from this module in static or dynamic Guile context.
29fa45f4
LC
182;;;
183;;; Code:
184
73f38d5f
LC
185\f
186;;;
187;;; Packed structures.
188;;;
189
190(define-syntax sizeof*
191 ;; XXX: This duplicates 'compile-time-value'.
00cd4197 192 (syntax-rules (int128 array)
73f38d5f
LC
193 ((_ int128)
194 16)
00cd4197
LC
195 ((_ (array type n))
196 (* (sizeof* type) n))
73f38d5f
LC
197 ((_ type)
198 (let-syntax ((v (lambda (s)
86f5decd
LC
199 ;; When compiling natively, call 'sizeof' at expansion
200 ;; time; otherwise, emit code to call it at run time.
201 (syntax-case s ()
202 (_
203 (if (= (target-word-size)
204 (with-target %host-type target-word-size))
205 (sizeof type)
206 #'(sizeof type)))))))
73f38d5f
LC
207 v))))
208
209(define-syntax alignof*
210 ;; XXX: This duplicates 'compile-time-value'.
00cd4197 211 (syntax-rules (int128 array)
73f38d5f
LC
212 ((_ int128)
213 16)
00cd4197
LC
214 ((_ (array type n))
215 (alignof* type))
73f38d5f
LC
216 ((_ type)
217 (let-syntax ((v (lambda (s)
86f5decd
LC
218 ;; When compiling natively, call 'sizeof' at expansion
219 ;; time; otherwise, emit code to call it at run time.
220 (syntax-case s ()
221 (_
222 (if (= (target-word-size)
223 (with-target %host-type target-word-size))
224 (alignof type)
225 #'(alignof type)))))))
73f38d5f
LC
226 v))))
227
228(define-syntax align ;as found in (system foreign)
229 (syntax-rules (~)
230 "Add to OFFSET whatever it takes to get proper alignment for TYPE."
231 ((_ offset (type ~ endianness))
232 (align offset type))
233 ((_ offset type)
234 (1+ (logior (1- offset) (1- (alignof* type)))))))
235
236(define-syntax type-size
237 (syntax-rules (~)
238 ((_ (type ~ order))
239 (sizeof* type))
240 ((_ type)
241 (sizeof* type))))
242
785cfa87
LC
243(define-syntax struct-alignment
244 (syntax-rules ()
245 "Compute the alignment for the aggregate made of TYPES at OFFSET. The
246result is the alignment of the \"most strictly aligned component\"."
247 ((_ offset types ...)
248 (max (align offset types) ...))))
249
250(define-syntax struct-size
251 (syntax-rules ()
252 "Return the size in bytes of the structure made of TYPES."
253 ((_ offset (types-processed ...))
254 ;; The SysV ABI P.S. says: "Aggregates (structures and arrays) and unions
255 ;; assume the alignment of their most strictly aligned component." As an
256 ;; example, a struct such as "int32, int16" has size 8, not 6.
257 (1+ (logior (1- offset)
258 (1- (struct-alignment offset types-processed ...)))))
259 ((_ offset (types-processed ...) type0 types ...)
260 (struct-size (+ (type-size type0) (align offset type0))
261 (type0 types-processed ...)
262 types ...))))
263
73f38d5f 264(define-syntax write-type
f43714e6 265 (syntax-rules (~ array *)
73f38d5f
LC
266 ((_ bv offset (type ~ order) value)
267 (bytevector-uint-set! bv offset value
268 (endianness order) (sizeof* type)))
00cd4197
LC
269 ((_ bv offset (array type n) value)
270 (let loop ((i 0)
271 (value value)
272 (o offset))
273 (unless (= i n)
274 (match value
275 ((head . tail)
276 (write-type bv o type head)
277 (loop (+ 1 i) tail (+ o (sizeof* type))))))))
f43714e6
LC
278 ((_ bv offset '* value)
279 (bytevector-uint-set! bv offset (pointer-address value)
280 (native-endianness) (sizeof* '*)))
73f38d5f
LC
281 ((_ bv offset type value)
282 (bytevector-uint-set! bv offset value
283 (native-endianness) (sizeof* type)))))
284
285(define-syntax write-types
286 (syntax-rules ()
287 ((_ bv offset () ())
288 #t)
289 ((_ bv offset (type0 types ...) (field0 fields ...))
290 (begin
291 (write-type bv (align offset type0) type0 field0)
292 (write-types bv
293 (+ (align offset type0) (type-size type0))
294 (types ...) (fields ...))))))
295
296(define-syntax read-type
00cd4197 297 (syntax-rules (~ array quote *)
73f38d5f
LC
298 ((_ bv offset '*)
299 (make-pointer (bytevector-uint-ref bv offset
300 (native-endianness)
301 (sizeof* '*))))
302 ((_ bv offset (type ~ order))
303 (bytevector-uint-ref bv offset
304 (endianness order) (sizeof* type)))
00cd4197
LC
305 ((_ bv offset (array type n))
306 (unfold (lambda (i) (= i n))
307 (lambda (i)
308 (read-type bv (+ offset (* i (sizeof* type))) type))
309 1+
310 0))
73f38d5f
LC
311 ((_ bv offset type)
312 (bytevector-uint-ref bv offset
313 (native-endianness) (sizeof* type)))))
314
315(define-syntax read-types
316 (syntax-rules ()
317 ((_ return bv offset () (values ...))
318 (return values ...))
319 ((_ return bv offset (type0 types ...) (values ...))
320 (read-types return
321 bv
322 (+ (align offset type0) (type-size type0))
323 (types ...)
324 (values ... (read-type bv
325 (align offset type0)
326 type0))))))
327
8eb790f3
LC
328(define-syntax define-c-struct-macro
329 (syntax-rules ()
330 "Define NAME as a macro that can be queried to get information about the C
331struct it represents. In particular:
332
333 (NAME field-offset FIELD)
334
335returns the offset in bytes of FIELD within the C struct represented by NAME."
336 ((_ name ((fields types) ...))
337 (define-c-struct-macro name
338 (fields ...) 0 ()
339 ((fields types) ...)))
340 ((_ name (fields ...) offset (clauses ...) ((field type) rest ...))
341 (define-c-struct-macro name
342 (fields ...)
343 (+ (align offset type) (type-size type))
344 (clauses ... ((_ field-offset field) (align offset type)))
345 (rest ...)))
346 ((_ name (fields ...) offset (clauses ...) ())
347 (define-syntax name
348 (syntax-rules (field-offset fields ...)
349 clauses ...)))))
350
73f38d5f
LC
351(define-syntax define-c-struct
352 (syntax-rules ()
785cfa87
LC
353 "Define SIZE as the size in bytes of the C structure made of FIELDS. READ
354as a deserializer and WRITE! as a serializer for the C structure with the
355given TYPES. READ uses WRAP-FIELDS to return its value."
356 ((_ name size wrap-fields read write! (fields types) ...)
73f38d5f 357 (begin
8eb790f3
LC
358 (define-c-struct-macro name
359 ((fields types) ...))
785cfa87
LC
360 (define size
361 (struct-size 0 () types ...))
73f38d5f
LC
362 (define (write! bv offset fields ...)
363 (write-types bv offset (types ...) (fields ...)))
f77863a0 364 (define* (read bv #:optional (offset 0))
73f38d5f
LC
365 (read-types wrap-fields bv offset (types ...) ()))))))
366
8eb790f3
LC
367(define-syntax-rule (c-struct-field-offset type field)
368 "Return the offset in BYTES of FIELD within TYPE, where TYPE is a C struct
369defined with 'define-c-struct' and FIELD is a field identifier. An
370expansion-time error is raised if FIELD does not exist in TYPE."
371 (type field-offset field))
372
73f38d5f
LC
373\f
374;;;
375;;; FFI.
376;;;
377
ea982704
LC
378(define (call-with-restart-on-EINTR thunk)
379 (let loop ()
380 (catch 'system-error
381 thunk
382 (lambda args
383 (if (= (system-error-errno args) EINTR)
384 (loop)
385 (apply throw args))))))
386
387(define-syntax-rule (restart-on-EINTR expr)
388 "Evaluate EXPR and restart upon EINTR. Return the value of EXPR."
389 (call-with-restart-on-EINTR (lambda () expr)))
390
4f8cede0 391(define (syscall->procedure return-type name argument-types)
26ffb693
LC
392 "Return a procedure that wraps the C function NAME using the dynamic FFI,
393and that returns two values: NAME's return value, and errno.
394
4f8cede0
MW
395If an error occurs while creating the binding, defer the error report until
396the returned procedure is called."
397 (catch #t
398 (lambda ()
399 (let ((ptr (dynamic-func name (dynamic-link))))
26ffb693 400 ;; The #:return-errno? facility was introduced in Guile 2.0.12.
1d84d7bf
LC
401 (pointer->procedure return-type ptr argument-types
402 #:return-errno? #t)))
4f8cede0
MW
403 (lambda args
404 (lambda _
f8121329
LC
405 (throw 'system-error name "~A" (list (strerror ENOSYS))
406 (list ENOSYS))))))
4f8cede0 407
8336df06
MO
408(define-syntax define-as-needed
409 (syntax-rules ()
410 "Define VARIABLE. If VARIABLE already exists in (guile) then re-export it,
411 otherwise export the newly-defined VARIABLE."
412 ((_ (proc args ...) body ...)
413 (define-as-needed proc (lambda* (args ...) body ...)))
414 ((_ variable value)
96783ed6
LC
415 (if (module-defined? the-scm-module 'variable)
416 (module-re-export! (current-module) '(variable))
417 (begin
418 (module-define! (current-module) 'variable value)
419 (module-export! (current-module) '(variable)))))))
8336df06 420
73f38d5f
LC
421\f
422;;;
423;;; File systems.
424;;;
425
29fa45f4
LC
426(define (augment-mtab source target type options)
427 "Augment /etc/mtab with information about the given mount point."
428 (let ((port (open-file "/etc/mtab" "a")))
429 (format port "~a ~a ~a ~a 0 0~%"
430 source target type (or options "rw"))
431 (close-port port)))
432
433(define (read-mtab port)
434 "Read an mtab-formatted file from PORT, returning a list of tuples."
435 (let loop ((result '()))
436 (let ((line (read-line port)))
437 (if (eof-object? line)
438 (reverse result)
439 (loop (cons (string-tokenize line) result))))))
440
441(define (remove-from-mtab target)
442 "Remove mount point TARGET from /etc/mtab."
443 (define entries
444 (remove (match-lambda
445 ((device mount-point type options freq passno)
446 (string=? target mount-point))
447 (_ #f))
cd4a3cb3 448 (call-with-input-file "/etc/mtab" read-mtab)))
29fa45f4 449
cd4a3cb3 450 (call-with-output-file "/etc/mtab"
29fa45f4
LC
451 (lambda (port)
452 (for-each (match-lambda
453 ((device mount-point type options freq passno)
454 (format port "~a ~a ~a ~a ~a ~a~%"
455 device mount-point type options freq passno)))
456 entries))))
457
458;; Linux mount flags, from libc's <sys/mount.h>.
577c02eb
DT
459(define MS_RDONLY 1)
460(define MS_NOSUID 2)
461(define MS_NODEV 4)
462(define MS_NOEXEC 8)
463(define MS_REMOUNT 32)
9d305381 464(define MS_NOATIME 1024)
577c02eb
DT
465(define MS_BIND 4096)
466(define MS_MOVE 8192)
467(define MS_STRICTATIME 16777216)
0dc5c856 468(define MS_LAZYTIME 33554432)
29fa45f4 469
b16d138a
DT
470(define MNT_FORCE 1)
471(define MNT_DETACH 2)
472(define MNT_EXPIRE 4)
473(define UMOUNT_NOFOLLOW 8)
474
7df4d346
MO
475(define-as-needed (mount source target type
476 #:optional (flags 0) options
f91fcd9c 477 #:key (update-mtab? #f))
7df4d346 478 "Mount device SOURCE on TARGET as a file system TYPE.
f91fcd9c
MO
479Optionally, FLAGS may be a bitwise-or of the MS_* <sys/mount.h>
480constants, and OPTIONS may be a string. When FLAGS contains
481MS_REMOUNT, SOURCE and TYPE are ignored. When UPDATE-MTAB? is true,
482update /etc/mtab. Raise a 'system-error' exception on error."
7df4d346
MO
483 ;; XXX: '#:update-mtab?' is not implemented by core 'mount'.
484 (let ((proc (syscall->procedure int "mount" `(* * * ,unsigned-long *))))
485 (let-values (((ret err)
486 (proc (if source
487 (string->pointer source)
488 %null-pointer)
489 (string->pointer target)
490 (if type
491 (string->pointer type)
492 %null-pointer)
493 flags
494 (if options
495 (string->pointer options)
496 %null-pointer))))
497 (unless (zero? ret)
498 (throw 'system-error "mount" "mount ~S on ~S: ~A"
499 (list source target (strerror err))
500 (list err)))
501 (when update-mtab?
502 (augment-mtab source target type options)))))
503
504(define-as-needed (umount target
505 #:optional (flags 0)
506 #:key (update-mtab? #f))
507 "Unmount TARGET. Optionally FLAGS may be one of the MNT_* or UMOUNT_*
29fa45f4 508constants from <sys/mount.h>."
7df4d346
MO
509 ;; XXX: '#:update-mtab?' is not implemented by core 'umount'.
510 (let ((proc (syscall->procedure int "umount2" `(* ,int))))
511 (let-values (((ret err)
512 (proc (string->pointer target) flags)))
513 (unless (zero? ret)
514 (throw 'system-error "umount" "~S: ~A"
515 (list target (strerror err))
516 (list err)))
517 (when update-mtab?
518 (remove-from-mtab target)))))
29fa45f4 519
ccea821b
LC
520(define (mount-points)
521 "Return the mounts points for currently mounted file systems."
522 (call-with-input-file "/proc/mounts"
523 (lambda (port)
524 (let loop ((result '()))
525 (let ((line (read-line port)))
526 (if (eof-object? line)
527 (reverse result)
528 (match (string-tokenize line)
529 ((source mount-point _ ...)
530 (loop (cons mount-point result))))))))))
531
715fc9d4 532(define swapon
4f8cede0 533 (let ((proc (syscall->procedure int "swapon" (list '* int))))
715fc9d4
LC
534 (lambda* (device #:optional (flags 0))
535 "Use the block special device at DEVICE for swapping."
26ffb693
LC
536 (let-values (((ret err)
537 (proc (string->pointer device) flags)))
715fc9d4
LC
538 (unless (zero? ret)
539 (throw 'system-error "swapon" "~S: ~A"
540 (list device (strerror err))
541 (list err)))))))
542
543(define swapoff
4f8cede0 544 (let ((proc (syscall->procedure int "swapoff" '(*))))
715fc9d4
LC
545 (lambda (device)
546 "Stop using block special device DEVICE for swapping."
26ffb693 547 (let-values (((ret err) (proc (string->pointer device))))
715fc9d4 548 (unless (zero? ret)
60a56db0 549 (throw 'system-error "swapoff" "~S: ~A"
715fc9d4
LC
550 (list device (strerror err))
551 (list err)))))))
552
8336df06
MO
553(define-as-needed RB_AUTOBOOT #x01234567)
554(define-as-needed RB_HALT_SYSTEM #xcdef0123)
555(define-as-needed RB_ENABLED_CAD #x89abcdef)
556(define-as-needed RB_DISABLE_CAD 0)
557(define-as-needed RB_POWER_OFF #x4321fedc)
558(define-as-needed RB_SW_SUSPEND #xd000fce2)
559(define-as-needed RB_KEXEC #x45584543)
560
561(define-as-needed (reboot #:optional (cmd RB_AUTOBOOT))
562 (let ((proc (syscall->procedure int "reboot" (list int))))
563 (let-values (((ret err) (proc cmd)))
564 (unless (zero? ret)
565 (throw 'system-error "reboot" "~S: ~A"
566 (list cmd (strerror err))
567 (list err))))))
568
23e525e1
MO
569(define-as-needed (load-linux-module data #:optional (options ""))
570 (let ((proc (syscall->procedure int "init_module"
571 (list '* unsigned-long '*))))
572 (let-values (((ret err)
573 (proc (bytevector->pointer data)
574 (bytevector-length data)
575 (string->pointer options))))
576 (unless (zero? ret)
577 (throw 'system-error "load-linux-module" "~A"
578 (list (strerror err))
579 (list err))))))
580
17a4d344
LC
581(define (kernel? pid)
582 "Return #t if PID designates a \"kernel thread\" rather than a normal
583user-land process."
584 (let ((stat (call-with-input-file (format #f "/proc/~a/stat" pid)
585 (compose string-tokenize read-string))))
586 ;; See proc.txt in Linux's documentation for the list of fields.
587 (match stat
588 ((pid tcomm state ppid pgrp sid tty_nr tty_pgrp flags min_flt
589 cmin_flt maj_flt cmaj_flt utime stime cutime cstime
590 priority nice num_thread it_real_value start_time
591 vsize rss rsslim
592 (= string->number start_code) (= string->number end_code) _ ...)
593 ;; Got this obscure trick from sysvinit's 'killall5' program.
594 (and (zero? start_code) (zero? end_code))))))
595
596(define (processes)
597 "Return the list of live processes."
598 (sort (filter-map (lambda (file)
599 (let ((pid (string->number file)))
600 (and pid
601 (not (kernel? pid))
602 pid)))
603 (scandir "/proc"))
604 <))
605
b4abdeb6 606(define mkdtemp!
d1f33ba4 607 (let ((proc (syscall->procedure '* "mkdtemp" '(*))))
b4abdeb6
DT
608 (lambda (tmpl)
609 "Create a new unique directory in the file system using the template
610string TMPL and return its file name. TMPL must end with 'XXXXXX'."
26ffb693 611 (let-values (((result err) (proc (string->pointer tmpl))))
b4abdeb6
DT
612 (when (null-pointer? result)
613 (throw 'system-error "mkdtemp!" "~S: ~A"
614 (list tmpl (strerror err))
615 (list err)))
616 (pointer->string result)))))
617
1752a17a
LC
618(define fdatasync
619 (let ((proc (syscall->procedure int "fdatasync" (list int))))
620 (lambda (port)
621 "Flush buffered output of PORT, an output file port, and then call
622fdatasync(2) on the underlying file descriptor."
623 (force-output port)
26ffb693
LC
624 (let*-values (((fd) (fileno port))
625 ((ret err) (proc fd)))
1752a17a
LC
626 (unless (zero? ret)
627 (throw 'system-error "fdatasync" "~S: ~A"
628 (list fd (strerror err))
629 (list err)))))))
630
a1f70878
LC
631
632(define-record-type <file-system>
633 (file-system type block-size blocks blocks-free
634 blocks-available files free-files identifier
00cd4197 635 name-length fragment-size mount-flags spare)
a1f70878
LC
636 file-system?
637 (type file-system-type)
638 (block-size file-system-block-size)
639 (blocks file-system-block-count)
640 (blocks-free file-system-blocks-free)
641 (blocks-available file-system-blocks-available)
642 (files file-system-file-count)
643 (free-files file-system-free-file-nodes)
644 (identifier file-system-identifier)
645 (name-length file-system-maximum-name-length)
646 (fragment-size file-system-fragment-size)
200dac06 647 (mount-flags file-system-mount-flags)
00cd4197 648 (spare file-system--spare))
a1f70878
LC
649
650(define-syntax fsword ;fsword_t
651 (identifier-syntax long))
652
200dac06 653(define-c-struct %statfs ;<bits/statfs.h>
a1f70878
LC
654 sizeof-statfs ;slightly overestimated
655 file-system
656 read-statfs
657 write-statfs!
658 (type fsword)
659 (block-size fsword)
660 (blocks uint64)
661 (blocks-free uint64)
662 (blocks-available uint64)
663 (files uint64)
664 (free-files uint64)
00cd4197 665 (identifier (array int 2))
a1f70878
LC
666 (name-length fsword)
667 (fragment-size fsword)
200dac06 668 (mount-flags fsword)
00cd4197 669 (spare (array fsword 4)))
a1f70878
LC
670
671(define statfs
96f2a432 672 (let ((proc (syscall->procedure int "statfs64" '(* *))))
a1f70878
LC
673 (lambda (file)
674 "Return a <file-system> data structure describing the file system
675mounted at FILE."
26ffb693
LC
676 (let*-values (((stat) (make-bytevector sizeof-statfs))
677 ((ret err) (proc (string->pointer file)
678 (bytevector->pointer stat))))
a1f70878 679 (if (zero? ret)
96f2a432 680 (read-statfs stat)
a1f70878
LC
681 (throw 'system-error "statfs" "~A: ~A"
682 (list file (strerror err))
683 (list err)))))))
684
65f224dc
LC
685(define (free-disk-space file)
686 "Return the free disk space, in bytes, on the file system that hosts FILE."
687 (let ((fs (statfs file)))
688 (* (file-system-block-size fs)
689 (file-system-blocks-available fs))))
690
25c7ff6a
LC
691;; Flags for the *at command, notably the 'utime' procedure of libguile.
692;; From <fcntl.h>.
456c7ade
LC
693(define-as-needed AT_FDCWD -100)
694(define-as-needed AT_SYMLINK_NOFOLLOW #x100)
695(define-as-needed AT_REMOVEDIR #x200)
696(define-as-needed AT_SYMLINK_FOLLOW #x400)
697(define-as-needed AT_NO_AUTOMOUNT #x800)
698(define-as-needed AT_EMPTY_PATH #x1000)
25c7ff6a 699
b08bea04
MO
700(define-syntax BLKRRPART ;<sys/mount.h>
701 (identifier-syntax #x125F))
702
703(define* (device-in-use? device)
704 "Return #t if the block DEVICE is in use, #f otherwise. This is inspired
88401314 705from fdisk_device_is_used function of util-linux. This is particularly useful
b08bea04
MO
706for devices that do not appear in /proc/self/mounts like overlayfs lowerdir
707backend device."
a1f5dfc2
LC
708 (let*-values (((fd) (open-fdes device O_RDONLY))
709 ((ret err) (%ioctl fd BLKRRPART %null-pointer)))
710 (close-fdes fd)
b08bea04
MO
711 (cond
712 ((= ret 0)
713 #f)
714 ((= err EBUSY)
715 #t)
07758945
LC
716 ((= err EINVAL)
717 ;; We get EINVAL for devices that have the GENHD_FL_NO_PART_SCAN flag
718 ;; set in the kernel, in particular loopback devices, though we do seem
719 ;; to get it for SCSI storage (/dev/sr0) on QEMU.
720 #f)
b08bea04
MO
721 (else
722 (throw 'system-error "ioctl" "~A"
723 (list (strerror err))
724 (list err))))))
725
73f38d5f 726\f
5e5f7167
LC
727;;;
728;;; Random.
729;;;
730
731;; From <uapi/linux/random.h>.
732(define RNDADDTOENTCNT #x40045201)
733
734(define (add-to-entropy-count port-or-fd n)
735 "Add N to the kernel's entropy count (the value that can be read from
736/proc/sys/kernel/random/entropy_avail). PORT-OR-FD must correspond to
737/dev/urandom or /dev/random. Raise to 'system-error with EPERM when the
738caller lacks root privileges."
739 (let ((fd (if (port? port-or-fd)
740 (fileno port-or-fd)
741 port-or-fd))
742 (box (make-bytevector (sizeof int))))
743 (bytevector-sint-set! box 0 n (native-endianness)
744 (sizeof int))
745 (let-values (((ret err)
746 (%ioctl fd RNDADDTOENTCNT
747 (bytevector->pointer box))))
748 (unless (zero? err)
749 (throw 'system-error "add-to-entropy-count" "~A"
750 (list (strerror err))
751 (list err))))))
752
753\f
73f38d5f
LC
754;;;
755;;; Containers.
756;;;
757
8950ed11 758;; Linux clone flags, from linux/sched.h
ee78d024
DT
759(define CLONE_CHILD_CLEARTID #x00200000)
760(define CLONE_CHILD_SETTID #x01000000)
761(define CLONE_NEWNS #x00020000)
762(define CLONE_NEWUTS #x04000000)
763(define CLONE_NEWIPC #x08000000)
764(define CLONE_NEWUSER #x10000000)
765(define CLONE_NEWPID #x20000000)
766(define CLONE_NEWNET #x40000000)
8950ed11 767
a65177a6
LC
768(define %set-automatic-finalization-enabled?!
769 ;; When using a statically-linked Guile, for instance in the initrd, we
770 ;; cannot resolve this symbol, but most of the time we don't need it
771 ;; anyway. Thus, delay it.
772 (let ((proc (delay
773 (pointer->procedure int
774 (dynamic-func
775 "scm_set_automatic_finalization_enabled"
776 (dynamic-link))
777 (list int)))))
778 (lambda (enabled?)
779 "Switch on or off automatic finalization in a separate thread.
70dfdd50 780Turning finalization off shuts down the finalization thread as a side effect."
a65177a6
LC
781 (->bool ((force proc) (if enabled? 1 0))))))
782
783(define-syntax-rule (without-automatic-finalization exp)
784 "Turn off automatic finalization within the dynamic extent of EXP."
785 (let ((enabled? #t))
786 (dynamic-wind
787 (lambda ()
788 (set! enabled? (%set-automatic-finalization-enabled?! #f)))
789 (lambda ()
790 exp)
791 (lambda ()
792 (%set-automatic-finalization-enabled?! enabled?)))))
70dfdd50 793
8950ed11 794;; The libc interface to sys_clone is not useful for Scheme programs, so the
0e3cc311
LC
795;; low-level system call is wrapped instead. The 'syscall' function is
796;; declared in <unistd.h> as a variadic function; in practice, it expects 6
797;; pointer-sized arguments, as shown in, e.g., x86_64/syscall.S.
8950ed11 798(define clone
4f8cede0
MW
799 (let* ((proc (syscall->procedure int "syscall"
800 (list long ;sysno
801 unsigned-long ;flags
802 '* '* '*
803 '*)))
8950ed11
DT
804 ;; TODO: Don't do this.
805 (syscall-id (match (utsname:machine (uname))
806 ("i686" 120)
807 ("x86_64" 56)
808 ("mips64" 5055)
4f8cede0 809 ("armv7l" 120)
7f0bb654 810 ("aarch64" 220)
4f8cede0 811 (_ #f))))
8950ed11
DT
812 (lambda (flags)
813 "Create a new child process by duplicating the current parent process.
814Unlike the fork system call, clone accepts FLAGS that specify which resources
815are shared between the parent and child processes."
26ffb693 816 (let-values (((ret err)
70dfdd50
LC
817 ;; Guile 2.2 runs a finalization thread. 'primitive-fork'
818 ;; takes care of shutting it down before forking, and we
819 ;; must do the same here. Failing to do that, if the
820 ;; child process calls 'primitive-fork', it will hang
821 ;; while trying to pthread_join the finalization thread
822 ;; since that thread does not exist.
823 (without-automatic-finalization
824 (proc syscall-id flags
825 %null-pointer ;child stack
826 %null-pointer %null-pointer ;ptid & ctid
827 %null-pointer)))) ;unused
cf897cba
DT
828 (if (= ret -1)
829 (throw 'system-error "clone" "~d: ~A"
830 (list flags (strerror err))
831 (list err))
832 ret)))))
8950ed11 833
43ace6ea 834(define setns
39e336b5
DT
835 ;; Some systems may be using an old (pre-2.14) version of glibc where there
836 ;; is no 'setns' function available.
837 (false-if-exception
d1f33ba4 838 (let ((proc (syscall->procedure int "setns" (list int int))))
39e336b5
DT
839 (lambda (fdes nstype)
840 "Reassociate the current process with the namespace specified by FDES, a
43ace6ea
DT
841file descriptor obtained by opening a /proc/PID/ns/* file. NSTYPE specifies
842which type of namespace the current process may be reassociated with, or 0 if
843there is no such limitation."
26ffb693 844 (let-values (((ret err) (proc fdes nstype)))
39e336b5
DT
845 (unless (zero? ret)
846 (throw 'system-error "setns" "~d ~d: ~A"
847 (list fdes nstype (strerror err))
848 (list err))))))))
43ace6ea 849
df3ce5c1 850(define pivot-root
4f8cede0 851 (let ((proc (syscall->procedure int "pivot_root" (list '* '*))))
df3ce5c1
DT
852 (lambda (new-root put-old)
853 "Change the root file system to NEW-ROOT and move the current root file
854system to PUT-OLD."
26ffb693
LC
855 (let-values (((ret err)
856 (proc (string->pointer new-root)
857 (string->pointer put-old))))
df3ce5c1
DT
858 (unless (zero? ret)
859 (throw 'system-error "pivot_root" "~S ~S: ~A"
860 (list new-root put-old (strerror err))
861 (list err)))))))
862
7585016f 863\f
fa73c193
LC
864;;;
865;;; Opendir & co.
866;;;
867
1ab9e483
LC
868(define (file-type->symbol type)
869 ;; Convert TYPE to symbols like 'stat:type' does.
870 (cond ((= type DT_REG) 'regular)
871 ((= type DT_LNK) 'symlink)
872 ((= type DT_DIR) 'directory)
873 ((= type DT_FIFO) 'fifo)
874 ((= type DT_CHR) 'char-special)
875 ((= type DT_BLK) 'block-special)
876 ((= type DT_SOCK) 'socket)
877 (else 'unknown)))
878
879;; 'struct dirent64' for GNU/Linux.
880(define-c-struct %struct-dirent-header/linux
881 sizeof-dirent-header/linux
fa73c193 882 (lambda (inode offset length type name)
1ab9e483
LC
883 `((type . ,(file-type->symbol type))
884 (inode . ,inode)))
885 read-dirent-header/linux
886 write-dirent-header!/linux
fa73c193
LC
887 (inode int64)
888 (offset int64)
889 (length unsigned-short)
890 (type uint8)
891 (name uint8)) ;first byte of 'd_name'
892
1ab9e483
LC
893;; 'struct dirent64' for GNU/Hurd.
894(define-c-struct %struct-dirent-header/hurd
895 sizeof-dirent-header/hurd
896 (lambda (inode length type name-length name)
897 `((type . ,(file-type->symbol type))
898 (inode . ,inode)))
899 read-dirent-header/hurd
900 write-dirent-header!/hurd
901 (inode int64)
902 (length unsigned-short)
903 (type uint8)
904 (namelen uint8)
905 (name uint8))
906
fa73c193
LC
907;; Constants for the 'type' field, from <dirent.h>.
908(define DT_UNKNOWN 0)
909(define DT_FIFO 1)
910(define DT_CHR 2)
911(define DT_DIR 4)
912(define DT_BLK 6)
913(define DT_REG 8)
914(define DT_LNK 10)
915(define DT_SOCK 12)
916(define DT_WHT 14)
917
918(define string->pointer/utf-8
919 (cut string->pointer <> "UTF-8"))
920
921(define pointer->string/utf-8
922 (cut pointer->string <> <> "UTF-8"))
923
924(define opendir*
925 (let ((proc (syscall->procedure '* "opendir" '(*))))
926 (lambda* (name #:optional (string->pointer string->pointer/utf-8))
927 (let-values (((ptr err)
928 (proc (string->pointer name))))
929 (if (null-pointer? ptr)
930 (throw 'system-error "opendir*"
3bacc655 931 "~A: ~A" (list name (strerror err))
fa73c193
LC
932 (list err))
933 ptr)))))
934
935(define closedir*
936 (let ((proc (syscall->procedure int "closedir" '(*))))
937 (lambda (directory)
938 (let-values (((ret err)
939 (proc directory)))
940 (unless (zero? ret)
941 (throw 'system-error "closedir"
942 "closedir: ~A" (list (strerror err))
943 (list err)))))))
944
82d8959e
LC
945(define (readdir-procedure name-field-offset sizeof-dirent-header
946 read-dirent-header)
fa73c193
LC
947 (let ((proc (syscall->procedure '* "readdir64" '(*))))
948 (lambda* (directory #:optional (pointer->string pointer->string/utf-8))
949 (let ((ptr (proc directory)))
950 (and (not (null-pointer? ptr))
951 (cons (pointer->string
82d8959e 952 (make-pointer (+ (pointer-address ptr) name-field-offset))
fa73c193
LC
953 -1)
954 (read-dirent-header
955 (pointer->bytevector ptr sizeof-dirent-header))))))))
956
82d8959e
LC
957(define readdir*
958 ;; Decide at run time which one must be used.
fd546bbb 959 (if (string-contains %host-type "linux-gnu")
82d8959e
LC
960 (readdir-procedure (c-struct-field-offset %struct-dirent-header/linux
961 name)
962 sizeof-dirent-header/linux
963 read-dirent-header/linux)
964 (readdir-procedure (c-struct-field-offset %struct-dirent-header/hurd
965 name)
966 sizeof-dirent-header/hurd
967 read-dirent-header/hurd)))
968
fa73c193
LC
969(define* (scandir* name #:optional
970 (select? (const #t))
971 (entry<? (lambda (entry1 entry2)
972 (match entry1
973 ((name1 . _)
974 (match entry2
975 ((name2 . _)
976 (string<? name1 name2)))))))
977 #:key
978 (string->pointer string->pointer/utf-8)
979 (pointer->string pointer->string/utf-8))
980 "This procedure improves on Guile's 'scandir' procedure in several ways:
981
982 1. Systematically encode decode file names using STRING->POINTER and
983 POINTER->STRING (UTF-8 by default; this works around a defect in Guile 2.0/2.2
984 where 'scandir' decodes file names according to the current locale, which is
985 not always desirable.
986
987 2. Each entry that is returned has the form (NAME . PROPERTIES).
988 PROPERTIES is an alist showing additional properties about the entry, as
989 found in 'struct dirent'. An entry may look like this:
990
991 (\"foo.scm\" (type . regular) (inode . 123456))
992
993 Callers must be prepared to deal with the case where 'type' is 'unknown'
994 since some file systems do not provide that information.
995
996 3. Raise to 'system-error' when NAME cannot be opened."
997 (let ((directory (opendir* name string->pointer)))
998 (dynamic-wind
999 (const #t)
1000 (lambda ()
1001 (let loop ((result '()))
1002 (match (readdir* directory pointer->string)
1003 (#f
1004 (sort result entry<?))
1005 (entry
1006 (loop (if (select? entry)
1007 (cons entry result)
1008 result))))))
1009 (lambda ()
1010 (closedir* directory)))))
1011
1012\f
4e0ea3eb
LC
1013;;;
1014;;; Advisory file locking.
1015;;;
1016
d33c8b46
LC
1017(define-c-struct %struct-flock ;<fcntl.h>
1018 sizeof-flock
1019 list
1020 read-flock
1021 write-flock!
1022 (type short)
1023 (whence short)
1024 (start size_t)
1025 (length size_t)
1026 (pid int))
4e0ea3eb
LC
1027
1028(define F_SETLKW
1029 ;; On Linux-based systems, this is usually 7, but not always
1030 ;; (exceptions include SPARC.) On GNU/Hurd, it's 9.
1031 (cond ((string-contains %host-type "sparc") 9) ; sparc-*-linux-gnu
1032 ((string-contains %host-type "linux") 7) ; *-linux-gnu
1033 (else 9))) ; *-gnu*
1034
1035(define F_SETLK
1036 ;; Likewise: GNU/Hurd and SPARC use 8, while the others typically use 6.
1037 (cond ((string-contains %host-type "sparc") 8) ; sparc-*-linux-gnu
1038 ((string-contains %host-type "linux") 6) ; *-linux-gnu
1039 (else 8))) ; *-gnu*
1040
1041(define F_xxLCK
1042 ;; The F_RDLCK, F_WRLCK, and F_UNLCK constants.
1043 (cond ((string-contains %host-type "sparc") #(1 2 3)) ; sparc-*-linux-gnu
1044 ((string-contains %host-type "hppa") #(1 2 3)) ; hppa-*-linux-gnu
1045 ((string-contains %host-type "linux") #(0 1 2)) ; *-linux-gnu
1046 (else #(1 2 3)))) ; *-gnu*
1047
1048(define fcntl-flock
1049 (let ((proc (syscall->procedure int "fcntl" `(,int ,int *))))
1050 (lambda* (fd-or-port operation #:key (wait? #t))
1051 "Perform locking OPERATION on the file beneath FD-OR-PORT. OPERATION
1052must be a symbol, one of 'read-lock, 'write-lock, or 'unlock. When WAIT? is
1053true, block until the lock is acquired; otherwise, thrown an 'flock-error'
1054exception if it's already taken."
1055 (define (operation->int op)
1056 (case op
1057 ((read-lock) (vector-ref F_xxLCK 0))
1058 ((write-lock) (vector-ref F_xxLCK 1))
1059 ((unlock) (vector-ref F_xxLCK 2))
1060 (else (error "invalid fcntl-flock operation" op))))
1061
1062 (define fd
1063 (if (port? fd-or-port)
1064 (fileno fd-or-port)
1065 fd-or-port))
1066
d33c8b46
LC
1067 (define bv
1068 (make-bytevector sizeof-flock))
1069
1070 (write-flock! bv 0
1071 (operation->int operation) SEEK_SET
1072 0 0 ;whole file
1073 0)
1074
4e0ea3eb
LC
1075 ;; XXX: 'fcntl' is a vararg function, but here we happily use the
1076 ;; standard ABI; crossing fingers.
26ffb693
LC
1077 (let-values (((ret err)
1078 (proc fd
1079 (if wait?
1080 F_SETLKW ;lock & wait
1081 F_SETLK) ;non-blocking attempt
1082 (bytevector->pointer bv))))
d33c8b46
LC
1083 (unless (zero? ret)
1084 ;; Presumably we got EAGAIN or so.
1085 (throw 'flock-error err))))))
4e0ea3eb 1086
f49e9131 1087(define* (lock-file file #:key (wait? #t))
b7178c22
LC
1088 "Wait and acquire an exclusive lock on FILE. Return an open port."
1089 (let ((port (open-file file "w0")))
f49e9131 1090 (fcntl-flock port 'write-lock #:wait? wait?)
b7178c22
LC
1091 port))
1092
1093(define (unlock-file port)
1094 "Unlock PORT, a port returned by 'lock-file'."
1095 (fcntl-flock port 'unlock)
1096 (close-port port)
1097 #t)
1098
89ceb86a 1099(define (call-with-file-lock file thunk)
9a067fe7 1100 (let ((port #f))
b7178c22
LC
1101 (dynamic-wind
1102 (lambda ()
9a067fe7
LC
1103 (set! port
1104 (catch 'system-error
1105 (lambda ()
1106 (lock-file file))
1107 (lambda args
1108 ;; When using the statically-linked Guile in the initrd,
1109 ;; 'fcntl-flock' returns ENOSYS unconditionally. Ignore
1110 ;; that error since we're typically the only process running
1111 ;; at this point.
1112 (if (= ENOSYS (system-error-errno args))
1113 #f
1114 (apply throw args))))))
89ceb86a 1115 thunk
b7178c22 1116 (lambda ()
5f0cf1df
LC
1117 (when port
1118 (unlock-file port))))))
b7178c22 1119
f49e9131 1120(define (call-with-file-lock/no-wait file thunk handler)
9a067fe7 1121 (let ((port #f))
f49e9131
JL
1122 (dynamic-wind
1123 (lambda ()
9a067fe7
LC
1124 (set! port
1125 (catch #t
1126 (lambda ()
1127 (lock-file file #:wait? #f))
1128 (lambda (key . args)
1129 (match key
1130 ('flock-error
1131 (apply handler args)
1132 ;; No open port to the lock, so return #f.
1133 #f)
1134 ('system-error
1135 ;; When using the statically-linked Guile in the initrd,
1136 ;; 'fcntl-flock' returns ENOSYS unconditionally. Ignore
1137 ;; that error since we're typically the only process running
1138 ;; at this point.
1139 (if (= ENOSYS (system-error-errno (cons key args)))
1140 #f
1141 (apply throw key args)))
1142 (_ (apply throw key args)))))))
f49e9131
JL
1143 thunk
1144 (lambda ()
1145 (when port
1146 (unlock-file port))))))
1147
89ceb86a
LC
1148(define-syntax-rule (with-file-lock file exp ...)
1149 "Wait to acquire a lock on FILE and evaluate EXP in that context."
1150 (call-with-file-lock file (lambda () exp ...)))
1151
f49e9131
JL
1152(define-syntax-rule (with-file-lock/no-wait file handler exp ...)
1153 "Try to acquire a lock on FILE and evaluate EXP in that context. Execute
1154handler if the lock is already held by another process."
1155 (call-with-file-lock/no-wait file (lambda () exp ...) handler))
1156
4e0ea3eb 1157\f
aa401f9b
LC
1158;;;
1159;;; Miscellaneous, aka. 'prctl'.
1160;;;
1161
1162(define %prctl
1163 ;; Should it win the API contest against 'ioctl'? You tell us!
1164 (syscall->procedure int "prctl"
1165 (list int unsigned-long unsigned-long
1166 unsigned-long unsigned-long)))
1167
1168(define PR_SET_NAME 15) ;<linux/prctl.h>
1169(define PR_GET_NAME 16)
1170
1171(define %max-thread-name-length
1172 ;; Maximum length in bytes of the process name, including the terminating
1173 ;; zero.
1174 16)
1175
1176(define (set-thread-name name)
1177 "Set the name of the calling thread to NAME. NAME is truncated to 15
1178bytes."
1179 (let ((ptr (string->pointer name)))
1180 (let-values (((ret err)
1181 (%prctl PR_SET_NAME
1182 (pointer-address ptr) 0 0 0)))
1183 (unless (zero? ret)
1184 (throw 'set-process-name "set-process-name"
1185 "set-process-name: ~A"
1186 (list (strerror err))
1187 (list err))))))
1188
1189(define (thread-name)
1190 "Return the name of the calling thread as a string."
1191 (let ((buf (make-bytevector %max-thread-name-length)))
1192 (let-values (((ret err)
1193 (%prctl PR_GET_NAME
1194 (pointer-address (bytevector->pointer buf))
1195 0 0 0)))
1196 (if (zero? ret)
1197 (bytes->string (bytevector->u8-list buf))
1198 (throw 'process-name "process-name"
1199 "process-name: ~A"
1200 (list (strerror err))
1201 (list err))))))
1202
1203\f
7585016f
LC
1204;;;
1205;;; Network interfaces.
1206;;;
1207
1208(define SIOCGIFCONF ;from <bits/ioctls.h>
598be42d
JN
1209 ; <net/if.h>
1210 ; <hurd/ioctl.h>
7585016f
LC
1211 (if (string-contains %host-type "linux")
1212 #x8912 ;GNU/Linux
1213 #xf00801a4)) ;GNU/Hurd
973eea34
LC
1214(define SIOCGIFFLAGS
1215 (if (string-contains %host-type "linux")
1216 #x8913 ;GNU/Linux
1217 #xc4804191)) ;GNU/Hurd
c9bf64d6
LC
1218(define SIOCSIFFLAGS
1219 (if (string-contains %host-type "linux")
1220 #x8914 ;GNU/Linux
598be42d 1221 #x84804190)) ;GNU/Hurd
c9bf64d6
LC
1222(define SIOCGIFADDR
1223 (if (string-contains %host-type "linux")
1224 #x8915 ;GNU/Linux
598be42d 1225 #xc08401a1)) ;GNU/Hurd
c9bf64d6
LC
1226(define SIOCSIFADDR
1227 (if (string-contains %host-type "linux")
1228 #x8916 ;GNU/Linux
598be42d 1229 #x8084018c)) ;GNU/Hurd
67e5f3b7
LC
1230(define SIOCGIFNETMASK
1231 (if (string-contains %host-type "linux")
1232 #x891b ;GNU/Linux
598be42d 1233 #xc08401a5)) ;GNU/Hurd
67e5f3b7
LC
1234(define SIOCSIFNETMASK
1235 (if (string-contains %host-type "linux")
1236 #x891c ;GNU/Linux
598be42d 1237 #x80840196)) ;GNU/Hurd
9e38e3cf
LC
1238(define SIOCADDRT
1239 (if (string-contains %host-type "linux")
1240 #x890B ;GNU/Linux
1241 -1)) ;FIXME: GNU/Hurd?
1242(define SIOCDELRT
1243 (if (string-contains %host-type "linux")
1244 #x890C ;GNU/Linux
1245 -1)) ;FIXME: GNU/Hurd?
973eea34
LC
1246
1247;; Flags and constants from <net/if.h>.
1248
c5cd4fad
MO
1249(define-as-needed IFF_UP #x1) ;Interface is up
1250(define-as-needed IFF_BROADCAST #x2) ;Broadcast address valid.
1251(define-as-needed IFF_LOOPBACK #x8) ;Is a loopback net.
0bc6fe32 1252(define-as-needed IFF_RUNNING #x40) ;interface RFC2863 OPER_UP
5f5499d6 1253(define-as-needed IFF_NOARP #x80) ;ARP disabled or unsupported
973eea34
LC
1254
1255(define IF_NAMESIZE 16) ;maximum interface name size
7585016f 1256
9d9d0c9c
LC
1257(define-c-struct %ifconf-struct
1258 sizeof-ifconf
1259 list
1260 read-ifconf
1261 write-ifconf!
1262 (length int) ;int ifc_len
1263 (request '*)) ;struct ifreq *ifc_ifcu
7585016f
LC
1264
1265(define ifreq-struct-size
973eea34
LC
1266 ;; 'struct ifreq' begins with an array of IF_NAMESIZE bytes containing the
1267 ;; interface name (nul-terminated), followed by a bunch of stuff. This is
1268 ;; its size in bytes.
7585016f
LC
1269 (if (= 8 (sizeof '*))
1270 40
1271 32))
1272
c9bf64d6 1273(define-c-struct sockaddr-in ;<linux/in.h>
785cfa87 1274 sizeof-sockaddrin
13f0c6ed
LC
1275 (lambda (family port address)
1276 (make-socket-address family address port))
c9bf64d6
LC
1277 read-sockaddr-in
1278 write-sockaddr-in!
1279 (family unsigned-short)
1280 (port (int16 ~ big))
1281 (address (int32 ~ big)))
1282
1283(define-c-struct sockaddr-in6 ;<linux/in6.h>
785cfa87 1284 sizeof-sockaddr-in6
13f0c6ed
LC
1285 (lambda (family port flowinfo address scopeid)
1286 (make-socket-address family address port flowinfo scopeid))
c9bf64d6
LC
1287 read-sockaddr-in6
1288 write-sockaddr-in6!
1289 (family unsigned-short)
1290 (port (int16 ~ big))
1291 (flowinfo (int32 ~ big))
1292 (address (int128 ~ big))
1293 (scopeid int32))
1294
1295(define (write-socket-address! sockaddr bv index)
1296 "Write SOCKADDR, a socket address as returned by 'make-socket-address', to
1297bytevector BV at INDEX."
1298 (let ((family (sockaddr:fam sockaddr)))
1299 (cond ((= family AF_INET)
1300 (write-sockaddr-in! bv index
1301 family
1302 (sockaddr:port sockaddr)
1303 (sockaddr:addr sockaddr)))
1304 ((= family AF_INET6)
1305 (write-sockaddr-in6! bv index
1306 family
1307 (sockaddr:port sockaddr)
1308 (sockaddr:flowinfo sockaddr)
1309 (sockaddr:addr sockaddr)
1310 (sockaddr:scopeid sockaddr)))
1311 (else
1312 (error "unsupported socket address" sockaddr)))))
1313
3ca33769
LC
1314(define PF_PACKET 17) ;<bits/socket.h>
1315(define AF_PACKET PF_PACKET)
1316
1317(define* (read-socket-address bv #:optional (index 0))
c9bf64d6
LC
1318 "Read a socket address from bytevector BV at INDEX."
1319 (let ((family (bytevector-u16-native-ref bv index)))
1320 (cond ((= family AF_INET)
13f0c6ed 1321 (read-sockaddr-in bv index))
c9bf64d6 1322 ((= family AF_INET6)
13f0c6ed 1323 (read-sockaddr-in6 bv index))
c9bf64d6 1324 (else
3ca33769
LC
1325 ;; XXX: Unsupported address family, such as AF_PACKET. Return a
1326 ;; vector such that the vector can at least call 'sockaddr:fam'.
1327 (vector family)))))
c9bf64d6 1328
7585016f
LC
1329(define %ioctl
1330 ;; The most terrible interface, live from Scheme.
d1f33ba4 1331 (syscall->procedure int "ioctl" (list int unsigned-long '*)))
7585016f 1332
57f068be
LC
1333(define (bytes->string bytes)
1334 "Read BYTES, a list of bytes, and return the null-terminated string decoded
1335from there, or #f if that would be an empty string."
1336 (match (take-while (negate zero?) bytes)
1337 (()
1338 #f)
1339 (non-zero
1340 (list->string (map integer->char non-zero)))))
1341
7585016f
LC
1342(define (bytevector->string-list bv stride len)
1343 "Return the null-terminated strings found in BV every STRIDE bytes. Read at
1344most LEN bytes from BV."
1345 (let loop ((bytes (take (bytevector->u8-list bv)
1346 (min len (bytevector-length bv))))
1347 (result '()))
1348 (match bytes
1349 (()
1350 (reverse result))
1351 (_
1352 (loop (drop bytes stride)
57f068be 1353 (cons (bytes->string bytes) result))))))
7585016f 1354
b89e7405
LC
1355(define* (network-interface-names #:optional sock)
1356 "Return the names of existing network interfaces. This is typically limited
4d54785c 1357to interfaces that are currently up."
7585016f
LC
1358 (let* ((close? (not sock))
1359 (sock (or sock (socket SOCK_STREAM AF_INET 0)))
1360 (len (* ifreq-struct-size 10))
1361 (reqs (make-bytevector len))
9d9d0c9c
LC
1362 (conf (make-bytevector sizeof-ifconf)))
1363 (write-ifconf! conf 0
1364 len (bytevector->pointer reqs))
1365
26ffb693 1366 (let-values (((ret err)
9d9d0c9c
LC
1367 (%ioctl (fileno sock) SIOCGIFCONF
1368 (bytevector->pointer conf))))
26ffb693
LC
1369 (when close?
1370 (close-port sock))
1371 (if (zero? ret)
1372 (bytevector->string-list reqs ifreq-struct-size
9d9d0c9c 1373 (match (read-ifconf conf)
26ffb693
LC
1374 ((len . _) len)))
1375 (throw 'system-error "network-interface-list"
1376 "network-interface-list: ~A"
1377 (list (strerror err))
1378 (list err))))))
7585016f 1379
4d54785c
LC
1380(define %interface-line
1381 ;; Regexp matching an interface line in Linux's /proc/net/dev.
a220b262 1382 (make-regexp "^[[:blank:]]*([[:graph:]]+):.*$"))
4d54785c 1383
b89e7405
LC
1384(define (all-network-interface-names)
1385 "Return all the names of the registered network interfaces, including those
1386that are not up."
4d54785c
LC
1387 (call-with-input-file "/proc/net/dev" ;XXX: Linux-specific
1388 (lambda (port)
1389 (let loop ((interfaces '()))
1390 (let ((line (read-line port)))
1391 (cond ((eof-object? line)
1392 (reverse interfaces))
1393 ((regexp-exec %interface-line line)
1394 =>
1395 (lambda (match)
1396 (loop (cons (match:substring match 1) interfaces))))
1397 (else
1398 (loop interfaces))))))))
1399
c5cd4fad 1400(define-as-needed (network-interface-flags socket name)
973eea34
LC
1401 "Return a number that is the bit-wise or of 'IFF*' flags for network
1402interface NAME."
1403 (let ((req (make-bytevector ifreq-struct-size)))
1404 (bytevector-copy! (string->utf8 name) 0 req 0
1405 (min (string-length name) (- IF_NAMESIZE 1)))
26ffb693
LC
1406 (let-values (((ret err)
1407 (%ioctl (fileno socket) SIOCGIFFLAGS
1408 (bytevector->pointer req))))
973eea34
LC
1409 (if (zero? ret)
1410
c5cd4fad
MO
1411 ;; The 'ifr_flags' field is IF_NAMESIZE bytes after the
1412 ;; beginning of 'struct ifreq', and it's a short int.
973eea34
LC
1413 (bytevector-sint-ref req IF_NAMESIZE (native-endianness)
1414 (sizeof short))
1415
1416 (throw 'system-error "network-interface-flags"
1417 "network-interface-flags on ~A: ~A"
1418 (list name (strerror err))
1419 (list err))))))
1420
1421(define (loopback-network-interface? name)
1422 "Return true if NAME designates a loopback network interface."
1423 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1424 (flags (network-interface-flags sock name)))
1425 (close-port sock)
1426 (not (zero? (logand flags IFF_LOOPBACK)))))
1427
0bc6fe32
DM
1428(define (network-interface-running? name)
1429 "Return true if NAME designates a running network interface."
1430 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1431 (flags (network-interface-flags sock name)))
1432 (close-port sock)
1433 (not (zero? (logand flags IFF_RUNNING)))))
1434
5f5499d6
MB
1435(define (arp-network-interface? name)
1436 "Return true if NAME supports the Address Resolution Protocol."
1437 (let* ((sock (socket SOCK_STREAM AF_INET 0))
1438 (flags (network-interface-flags sock name)))
1439 (close-port sock)
1440 (zero? (logand flags IFF_NOARP))))
1441
c5cd4fad 1442(define-as-needed (set-network-interface-flags socket name flags)
c9bf64d6
LC
1443 "Set the flag of network interface NAME to FLAGS."
1444 (let ((req (make-bytevector ifreq-struct-size)))
1445 (bytevector-copy! (string->utf8 name) 0 req 0
1446 (min (string-length name) (- IF_NAMESIZE 1)))
1447 ;; Set the 'ifr_flags' field.
1448 (bytevector-uint-set! req IF_NAMESIZE flags (native-endianness)
1449 (sizeof short))
26ffb693
LC
1450 (let-values (((ret err)
1451 (%ioctl (fileno socket) SIOCSIFFLAGS
1452 (bytevector->pointer req))))
c9bf64d6
LC
1453 (unless (zero? ret)
1454 (throw 'system-error "set-network-interface-flags"
1455 "set-network-interface-flags on ~A: ~A"
1456 (list name (strerror err))
1457 (list err))))))
1458
c5cd4fad 1459(define-as-needed (set-network-interface-address socket name sockaddr)
c9bf64d6
LC
1460 "Set the address of network interface NAME to SOCKADDR."
1461 (let ((req (make-bytevector ifreq-struct-size)))
1462 (bytevector-copy! (string->utf8 name) 0 req 0
1463 (min (string-length name) (- IF_NAMESIZE 1)))
1464 ;; Set the 'ifr_addr' field.
1465 (write-socket-address! sockaddr req IF_NAMESIZE)
26ffb693
LC
1466 (let-values (((ret err)
1467 (%ioctl (fileno socket) SIOCSIFADDR
1468 (bytevector->pointer req))))
c9bf64d6
LC
1469 (unless (zero? ret)
1470 (throw 'system-error "set-network-interface-address"
1471 "set-network-interface-address on ~A: ~A"
1472 (list name (strerror err))
1473 (list err))))))
1474
67e5f3b7
LC
1475(define (set-network-interface-netmask socket name sockaddr)
1476 "Set the network mask of interface NAME to SOCKADDR."
1477 (let ((req (make-bytevector ifreq-struct-size)))
1478 (bytevector-copy! (string->utf8 name) 0 req 0
1479 (min (string-length name) (- IF_NAMESIZE 1)))
1480 ;; Set the 'ifr_addr' field.
1481 (write-socket-address! sockaddr req IF_NAMESIZE)
1482 (let-values (((ret err)
1483 (%ioctl (fileno socket) SIOCSIFNETMASK
1484 (bytevector->pointer req))))
1485 (unless (zero? ret)
1486 (throw 'system-error "set-network-interface-netmask"
1487 "set-network-interface-netmask on ~A: ~A"
1488 (list name (strerror err))
1489 (list err))))))
1490
c9bf64d6
LC
1491(define (network-interface-address socket name)
1492 "Return the address of network interface NAME. The result is an object of
1493the same type as that returned by 'make-socket-address'."
1494 (let ((req (make-bytevector ifreq-struct-size)))
1495 (bytevector-copy! (string->utf8 name) 0 req 0
1496 (min (string-length name) (- IF_NAMESIZE 1)))
26ffb693
LC
1497 (let-values (((ret err)
1498 (%ioctl (fileno socket) SIOCGIFADDR
1499 (bytevector->pointer req))))
c9bf64d6
LC
1500 (if (zero? ret)
1501 (read-socket-address req IF_NAMESIZE)
1502 (throw 'system-error "network-interface-address"
1503 "network-interface-address on ~A: ~A"
1504 (list name (strerror err))
1505 (list err))))))
1506
67e5f3b7
LC
1507(define (network-interface-netmask socket name)
1508 "Return the netmask of network interface NAME. The result is an object of
1509the same type as that returned by 'make-socket-address'."
1510 (let ((req (make-bytevector ifreq-struct-size)))
1511 (bytevector-copy! (string->utf8 name) 0 req 0
1512 (min (string-length name) (- IF_NAMESIZE 1)))
1513 (let-values (((ret err)
1514 (%ioctl (fileno socket) SIOCGIFNETMASK
1515 (bytevector->pointer req))))
1516 (if (zero? ret)
1517 (read-socket-address req IF_NAMESIZE)
1518 (throw 'system-error "network-interface-netmask"
1519 "network-interface-netmask on ~A: ~A"
1520 (list name (strerror err))
1521 (list err))))))
1522
e9ff8d9f
LC
1523(define* (configure-network-interface name sockaddr flags
1524 #:key netmask)
c9bf64d6 1525 "Configure network interface NAME to use SOCKADDR, an address as returned by
e9ff8d9f
LC
1526'make-socket-address', and FLAGS, a bitwise-or of IFF_* constants. If NETMASK
1527is true, it must be a socket address to use as the network mask."
c9bf64d6
LC
1528 (let ((sock (socket (sockaddr:fam sockaddr) SOCK_STREAM 0)))
1529 (dynamic-wind
1530 (const #t)
1531 (lambda ()
1532 (set-network-interface-address sock name sockaddr)
e9ff8d9f
LC
1533 (set-network-interface-flags sock name flags)
1534 (when netmask
1535 (set-network-interface-netmask sock name netmask)))
c9bf64d6
LC
1536 (lambda ()
1537 (close-port sock)))))
1538
6944fdbd
LC
1539(define* (set-network-interface-up name
1540 #:key (family AF_INET))
1541 "Turn up the interface NAME."
1542 (let ((sock (socket family SOCK_STREAM 0)))
1543 (dynamic-wind
1544 (const #t)
1545 (lambda ()
1546 (let ((flags (network-interface-flags sock name)))
1547 (set-network-interface-flags sock name
1548 (logior flags IFF_UP))))
1549 (lambda ()
1550 (close-port sock)))))
1551
e7f5691d 1552\f
9e38e3cf
LC
1553;;;
1554;;; Network routes.
1555;;;
1556
1557(define-c-struct %rtentry ;'struct rtentry' from <net/route.h>
1558 sizeof-rtentry
1559 list
1560 read-rtentry
1561 write-rtentry!
1562 (pad1 unsigned-long)
1563 (destination (array uint8 16)) ;struct sockaddr
1564 (gateway (array uint8 16)) ;struct sockaddr
1565 (genmask (array uint8 16)) ;struct sockaddr
1566 (flags unsigned-short)
1567 (pad2 short)
1568 (pad3 long)
1569 (tos uint8)
1570 (class uint8)
1571 (pad4 (array uint8 (if (= 8 (sizeof* '*)) 3 1)))
1572 (metric short)
1573 (device '*)
1574 (mtu unsigned-long)
1575 (window unsigned-long)
1576 (initial-rtt unsigned-short))
1577
1578(define RTF_UP #x0001) ;'rtentry' flags from <net/route.h>
1579(define RTF_GATEWAY #x0002)
1580
1581(define %sockaddr-any
1582 (make-socket-address AF_INET INADDR_ANY 0))
1583
1584(define add-network-route/gateway
1585 ;; To allow field names to be matched as literals, we need to move them out
1586 ;; of the lambda's body since the parameters have the same name. A lot of
1587 ;; fuss for very little.
1588 (let-syntax ((gateway-offset (identifier-syntax
1589 (c-struct-field-offset %rtentry gateway)))
1590 (destination-offset (identifier-syntax
1591 (c-struct-field-offset %rtentry destination)))
1592 (genmask-offset (identifier-syntax
1593 (c-struct-field-offset %rtentry genmask))))
1594 (lambda* (socket gateway
1595 #:key (destination %sockaddr-any) (genmask %sockaddr-any))
1596 "Add a network route for DESTINATION (a socket address as returned by
1597'make-socket-address') that goes through GATEWAY (a socket address). For
1598instance, the call:
1599
1600 (add-network-route/gateway sock
1601 (make-socket-address
1602 AF_INET
1603 (inet-pton AF_INET \"192.168.0.1\")
1604 0))
1605
1606is equivalent to this 'net-tools' command:
1607
1608 route add -net default gw 192.168.0.1
1609
1610because the default value of DESTINATION is \"0.0.0.0\"."
1611 (let ((route (make-bytevector sizeof-rtentry 0)))
1612 (write-socket-address! gateway route gateway-offset)
1613 (write-socket-address! destination route destination-offset)
1614 (write-socket-address! genmask route genmask-offset)
1615 (bytevector-u16-native-set! route
1616 (c-struct-field-offset %rtentry flags)
1617 (logior RTF_UP RTF_GATEWAY))
1618 (let-values (((ret err)
1619 (%ioctl (fileno socket) SIOCADDRT
1620 (bytevector->pointer route))))
1621 (unless (zero? ret)
1622 (throw 'system-error "add-network-route/gateway"
1623 "add-network-route/gateway: ~A"
1624 (list (strerror err))
1625 (list err))))))))
1626
1627(define delete-network-route
1628 (let-syntax ((destination-offset (identifier-syntax
1629 (c-struct-field-offset %rtentry destination))))
1630 (lambda* (socket destination)
1631 "Delete the network route for DESTINATION. For instance, the call:
1632
1633 (delete-network-route sock
1634 (make-socket-address AF_INET INADDR_ANY 0))
1635
1636is equivalent to the 'net-tools' command:
1637
1638 route del -net default
1639"
1640
1641 (let ((route (make-bytevector sizeof-rtentry 0)))
1642 (write-socket-address! destination route destination-offset)
1643 (let-values (((ret err)
1644 (%ioctl (fileno socket) SIOCDELRT
1645 (bytevector->pointer route))))
1646 (unless (zero? ret)
1647 (throw 'system-error "delete-network-route"
1648 "delete-network-route: ~A"
1649 (list (strerror err))
1650 (list err))))))))
1651
1652\f
e7f5691d
LC
1653;;;
1654;;; Details about network interfaces---aka. 'getifaddrs'.
1655;;;
1656
1657;; Network interfaces. XXX: We would call it <network-interface> but that
1658;; would collide with the ioctl wrappers above.
1659(define-record-type <interface>
1660 (make-interface name flags address netmask broadcast-address)
1661 interface?
1662 (name interface-name) ;string
1663 (flags interface-flags) ;or'd IFF_* values
1664 (address interface-address) ;sockaddr | #f
1665 (netmask interface-netmask) ;sockaddr | #f
1666 (broadcast-address interface-broadcast-address)) ;sockaddr | #f
1667
1668(define (write-interface interface port)
1669 (match interface
1670 (($ <interface> name flags address)
1671 (format port "#<interface ~s " name)
1672 (unless (zero? (logand IFF_UP flags))
1673 (display "up " port))
001dae0d
LC
1674
1675 ;; Check whether ADDRESS really is a sockaddr.
1676 (when address
1677 (if (member (sockaddr:fam address) (list AF_INET AF_INET6))
1678 (format port "~a " (inet-ntop (sockaddr:fam address)
1679 (sockaddr:addr address)))
1680 (format port "family:~a " (sockaddr:fam address))))
1681
e7f5691d
LC
1682 (format port "~a>" (number->string (object-address interface) 16)))))
1683
1684(set-record-type-printer! <interface> write-interface)
1685
1686(define (values->interface next name flags address netmask
1687 broadcast-address data)
1688 "Given the raw field values passed as arguments, return a pair whose car is
1689an <interface> object, and whose cdr is the pointer NEXT."
1690 (define (maybe-socket-address pointer)
1691 (if (null-pointer? pointer)
1692 #f
1693 (read-socket-address (pointer->bytevector pointer 50)))) ;XXX: size
1694
1695 (cons (make-interface (if (null-pointer? name)
1696 #f
1697 (pointer->string name))
1698 flags
1699 (maybe-socket-address address)
1700 (maybe-socket-address netmask)
1701 (maybe-socket-address broadcast-address)
1702 ;; Ignore DATA.
1703 )
1704 next))
1705
1706(define-c-struct ifaddrs ;<ifaddrs.h>
785cfa87 1707 %sizeof-ifaddrs
e7f5691d
LC
1708 values->interface
1709 read-ifaddrs
1710 write-ifaddrs!
1711 (next '*)
1712 (name '*)
1713 (flags unsigned-int)
1714 (addr '*)
1715 (netmask '*)
1716 (broadcastaddr '*)
1717 (data '*))
1718
e7f5691d
LC
1719(define (unfold-interface-list ptr)
1720 "Call 'read-ifaddrs' on PTR and all its 'next' fields, recursively, and
1721return the list of resulting <interface> objects."
1722 (let loop ((ptr ptr)
1723 (result '()))
1724 (if (null-pointer? ptr)
1725 (reverse result)
f77863a0 1726 (match (read-ifaddrs (pointer->bytevector ptr %sizeof-ifaddrs))
e7f5691d
LC
1727 ((ifaddr . ptr)
1728 (loop ptr (cons ifaddr result)))))))
1729
1730(define network-interfaces
d1f33ba4 1731 (let ((proc (syscall->procedure int "getifaddrs" (list '*))))
e7f5691d
LC
1732 (lambda ()
1733 "Return a list of <interface> objects, each denoting a configured
1734network interface. This is implemented using the 'getifaddrs' libc function."
26ffb693
LC
1735 (let*-values (((ptr)
1736 (bytevector->pointer (make-bytevector (sizeof* '*))))
1737 ((ret err)
1738 (proc ptr)))
e7f5691d
LC
1739 (if (zero? ret)
1740 (let* ((ptr (dereference-pointer ptr))
1741 (result (unfold-interface-list ptr)))
1742 (free-ifaddrs ptr)
1743 result)
1744 (throw 'system-error "network-interfaces" "~A"
1745 (list (strerror err))
1746 (list err)))))))
1747
1748(define free-ifaddrs
d1f33ba4 1749 (syscall->procedure void "freeifaddrs" '(*)))
e7f5691d 1750
29ff6d9f
LC
1751\f
1752;;;
1753;;; Terminals.
1754;;;
1755
ae4ff9f3
LC
1756(define-syntax bits->symbols-body
1757 (syntax-rules ()
1758 ((_ bits () ())
1759 '())
1760 ((_ bits (name names ...) (value values ...))
1761 (let ((result (bits->symbols-body bits (names ...) (values ...))))
1762 (if (zero? (logand bits value))
1763 result
1764 (cons 'name result))))))
1765
1766(define-syntax define-bits
1767 (syntax-rules (define)
1768 "Define the given numerical constants under CONSTRUCTOR, such that
1769 (CONSTRUCTOR NAME) returns VALUE. Define BITS->SYMBOLS as a procedure that,
1770given an integer, returns the list of names of the constants that are or'd."
1771 ((_ constructor bits->symbols (define names values) ...)
1772 (begin
1773 (define-syntax constructor
1774 (syntax-rules (names ...)
334c9530 1775 ((_) 0)
ae4ff9f3 1776 ((_ names) values) ...
334c9530
LC
1777 ((_ first rest (... ...))
1778 (logior (constructor first) rest (... ...)))))
ae4ff9f3 1779 (define (bits->symbols bits)
334c9530 1780 (bits->symbols-body bits (names ...) (values ...)))))))
ae4ff9f3
LC
1781
1782;; 'local-flags' bits from <bits/termios.h>
1783(define-bits local-flags
1784 local-flags->symbols
1785 (define ISIG #o0000001)
1786 (define ICANON #o0000002)
1787 (define XCASE #o0000004)
1788 (define ECHO #o0000010)
1789 (define ECHOE #o0000020)
1790 (define ECHOK #o0000040)
1791 (define ECHONL #o0000100)
1792 (define NOFLSH #o0000200)
1793 (define TOSTOP #o0000400)
1794 (define ECHOCTL #o0001000)
1795 (define ECHOPRT #o0002000)
1796 (define ECHOKE #o0004000)
1797 (define FLUSHO #o0010000)
1798 (define PENDIN #o0040000)
1799 (define IEXTEN #o0100000)
1800 (define EXTPROC #o0200000))
1801
45c32bd7
LC
1802(define-bits input-flags
1803 input-flags->symbols
1804 (define IGNBRK #o0000001)
1805 (define BRKINT #o0000002)
1806 (define IGNPAR #o0000004)
1807 (define PARMRK #o0000010)
1808 (define INPCK #o0000020)
1809 (define ISTRIP #o0000040)
1810 (define INLCR #o0000100)
1811 (define IGNCR #o0000200)
1812 (define ICRNL #o0000400)
1813 (define IUCLC #o0001000)
1814 (define IXON #o0002000)
1815 (define IXANY #o0004000)
1816 (define IXOFF #o0010000)
1817 (define IMAXBEL #o0020000)
1818 (define IUTF8 #o0040000))
1819
ae4ff9f3 1820;; "Actions" values for 'tcsetattr'.
a8f3424b
LC
1821(define-bits tcsetattr-action
1822 %unused-tcsetattr-action->symbols
1823 (define TCSANOW 0)
1824 (define TCSADRAIN 1)
1825 (define TCSAFLUSH 2))
ae4ff9f3
LC
1826
1827(define-record-type <termios>
1828 (termios input-flags output-flags control-flags local-flags
1829 line-discipline control-chars
1830 input-speed output-speed)
1831 termios?
1832 (input-flags termios-input-flags)
1833 (output-flags termios-output-flags)
1834 (control-flags termios-control-flags)
1835 (local-flags termios-local-flags)
1836 (line-discipline termios-line-discipline)
1837 (control-chars termios-control-chars)
1838 (input-speed termios-input-speed)
1839 (output-speed termios-output-speed))
1840
1841(define-c-struct %termios ;<bits/termios.h>
1842 sizeof-termios
1843 termios
1844 read-termios
1845 write-termios!
1846 (input-flags unsigned-int)
1847 (output-flags unsigned-int)
1848 (control-flags unsigned-int)
1849 (local-flags unsigned-int)
1850 (line-discipline uint8)
1851 (control-chars (array uint8 32))
1852 (input-speed unsigned-int)
1853 (output-speed unsigned-int))
1854
1855(define tcgetattr
1856 (let ((proc (syscall->procedure int "tcgetattr" (list int '*))))
1857 (lambda (fd)
1858 "Return the <termios> structure for the tty at FD."
26ffb693
LC
1859 (let*-values (((bv) (make-bytevector sizeof-termios))
1860 ((ret err) (proc fd (bytevector->pointer bv))))
ae4ff9f3
LC
1861 (if (zero? ret)
1862 (read-termios bv)
1863 (throw 'system-error "tcgetattr" "~A"
1864 (list (strerror err))
1865 (list err)))))))
1866
1867(define tcsetattr
1868 (let ((proc (syscall->procedure int "tcsetattr" (list int int '*))))
1869 (lambda (fd actions termios)
a8f3424b
LC
1870 "Use TERMIOS for the tty at FD. ACTIONS is one of of the values
1871produced by 'tcsetattr-action'; see tcsetattr(3) for details."
ae4ff9f3
LC
1872 (define bv
1873 (make-bytevector sizeof-termios))
1874
1875 (let-syntax ((match/write (syntax-rules ()
1876 ((_ fields ...)
1877 (match termios
1878 (($ <termios> fields ...)
1879 (write-termios! bv 0 fields ...)))))))
1880 (match/write input-flags output-flags control-flags local-flags
1881 line-discipline control-chars input-speed output-speed))
1882
26ffb693 1883 (let-values (((ret err) (proc fd actions (bytevector->pointer bv))))
ae4ff9f3
LC
1884 (unless (zero? ret)
1885 (throw 'system-error "tcgetattr" "~A"
1886 (list (strerror err))
1887 (list err)))))))
1888
29ff6d9f
LC
1889(define-syntax TIOCGWINSZ ;<asm-generic/ioctls.h>
1890 (identifier-syntax #x5413))
1891
1892(define-record-type <window-size>
1893 (window-size rows columns x-pixels y-pixels)
1894 window-size?
1895 (rows window-size-rows)
1896 (columns window-size-columns)
1897 (x-pixels window-size-x-pixels)
1898 (y-pixels window-size-y-pixels))
1899
1900(define-c-struct winsize ;<bits/ioctl-types.h>
785cfa87 1901 sizeof-winsize
29ff6d9f
LC
1902 window-size
1903 read-winsize
1904 write-winsize!
1905 (rows unsigned-short)
1906 (columns unsigned-short)
1907 (x-pixels unsigned-short)
1908 (y-pixels unsigned-short))
1909
29ff6d9f
LC
1910(define* (terminal-window-size #:optional (port (current-output-port)))
1911 "Return a <window-size> structure describing the terminal at PORT, or raise
1912a 'system-error' if PORT is not backed by a terminal. This procedure
1913corresponds to the TIOCGWINSZ ioctl."
26ffb693
LC
1914 (let*-values (((size) (make-bytevector sizeof-winsize))
1915 ((ret err) (%ioctl (fileno port) TIOCGWINSZ
1916 (bytevector->pointer size))))
29ff6d9f 1917 (if (zero? ret)
785cfa87 1918 (read-winsize size)
29ff6d9f
LC
1919 (throw 'system-error "terminal-window-size" "~A"
1920 (list (strerror err))
1921 (list err)))))
1922
4593f5a6
LC
1923(define (terminal-dimension window-dimension port fall-back)
1924 "Return the terminal dimension defined by WINDOW-DIMENSION, one of
1925'window-size-columns' or 'window-size-rows' for PORT. If PORT does not
1926correspond to a terminal, return the value returned by FALL-BACK."
29ff6d9f
LC
1927 (catch 'system-error
1928 (lambda ()
6d2b4391 1929 (if (file-port? port)
4593f5a6 1930 (match (window-dimension (terminal-window-size port))
6d2b4391
LC
1931 ;; Things like Emacs shell-mode return 0, which is unreasonable.
1932 (0 (fall-back))
4593f5a6 1933 ((? number? n) n))
6d2b4391 1934 (fall-back)))
29ff6d9f
LC
1935 (lambda args
1936 (let ((errno (system-error-errno args)))
5cd25aad
LC
1937 ;; ENOTTY is what we're after but 2012-and-earlier Linux versions
1938 ;; would return EINVAL instead in some cases:
1939 ;; <https://bugs.ruby-lang.org/issues/10494>.
a6e0ae40
LC
1940 ;; Furthermore, some FUSE file systems like unionfs return ENOSYS for
1941 ;; that ioctl.
1942 (if (memv errno (list ENOTTY EINVAL ENOSYS))
29ff6d9f
LC
1943 (fall-back)
1944 (apply throw args))))))
1945
4593f5a6
LC
1946(define* (terminal-columns #:optional (port (current-output-port)))
1947 "Return the best approximation of the number of columns of the terminal at
1948PORT, trying to guess a reasonable value if all else fails. The result is
1949always a positive integer."
1950 (define (fall-back)
1951 (match (and=> (getenv "COLUMNS") string->number)
1952 (#f 80)
1953 ((? number? columns)
1954 (if (> columns 0) columns 80))))
1955
1956 (terminal-dimension window-size-columns port fall-back))
1957
1958(define* (terminal-rows #:optional (port (current-output-port)))
1959 "Return the best approximation of the number of rows of the terminal at
1960PORT, trying to guess a reasonable value if all else fails. The result is
1961always a positive integer."
1962 (terminal-dimension window-size-rows port (const 25)))
1963
15030972
LC
1964\f
1965;;;
1966;;; utmpx.
1967;;;
1968
1969(define-record-type <utmpx-entry>
1970 (utmpx type pid line id user host termination exit
1971 session time address)
1972 utmpx?
1973 (type utmpx-login-type) ;login-type
1974 (pid utmpx-pid)
1975 (line utmpx-line) ;device name
1976 (id utmpx-id)
1977 (user utmpx-user) ;user name
1978 (host utmpx-host) ;host name | #f
1979 (termination utmpx-termination-status)
1980 (exit utmpx-exit-status)
1981 (session utmpx-session-id) ;session ID, for windowing
1982 (time utmpx-time) ;entry time
1983 (address utmpx-address))
1984
1985(define-c-struct %utmpx ;<utmpx.h>
1986 sizeof-utmpx
1987 (lambda (type pid line id user host termination exit session
1988 seconds useconds address %reserved)
1989 (utmpx type pid
1990 (bytes->string line) id
1991 (bytes->string user)
1992 (bytes->string host) termination exit
1993 session
1994 (make-time time-utc (* 1000 useconds) seconds)
1995 address))
1996 read-utmpx
1997 write-utmpx!
1998 (type short)
1999 (pid int)
2000 (line (array uint8 32))
2001 (id (array uint8 4))
2002 (user (array uint8 32))
2003 (host (array uint8 256))
2004 (termination short)
2005 (exit short)
2006 (session int32)
2007 (time-seconds int32)
2008 (time-useconds int32)
2009 (address-v6 (array int32 4))
2010 (%reserved (array uint8 20)))
2011
2012(define-bits login-type
2013 %unused-login-type->symbols
2014 (define EMPTY 0) ;No valid user accounting information.
2015 (define RUN_LVL 1) ;The system's runlevel.
2016 (define BOOT_TIME 2) ;Time of system boot.
2017 (define NEW_TIME 3) ;Time after system clock changed.
2018 (define OLD_TIME 4) ;Time when system clock changed.
2019
2020 (define INIT_PROCESS 5) ;Process spawned by the init process.
2021 (define LOGIN_PROCESS 6) ;Session leader of a logged in user.
2022 (define USER_PROCESS 7) ;Normal process.
2023 (define DEAD_PROCESS 8) ;Terminated process.
2024
2025 (define ACCOUNTING 9)) ;System accounting.
2026
2027(define setutxent
2028 (let ((proc (syscall->procedure void "setutxent" '())))
2029 (lambda ()
2030 "Open the user accounting database."
2031 (proc))))
2032
2033(define endutxent
2034 (let ((proc (syscall->procedure void "endutxent" '())))
2035 (lambda ()
2036 "Close the user accounting database."
2037 (proc))))
2038
2039(define getutxent
2040 (let ((proc (syscall->procedure '* "getutxent" '())))
2041 (lambda ()
2042 "Return the next entry from the user accounting database."
2043 (let ((ptr (proc)))
2044 (if (null-pointer? ptr)
2045 #f
2046 (read-utmpx (pointer->bytevector ptr sizeof-utmpx)))))))
2047
2048(define (utmpx-entries)
2049 "Return the list of entries read from the user accounting database."
2050 (setutxent)
2051 (let loop ((entries '()))
2052 (match (getutxent)
2053 (#f
2054 (endutxent)
2055 (reverse entries))
2056 ((? utmpx? entry)
2057 (loop (cons entry entries))))))
2058
3483f004
LC
2059(define (read-utmpx-from-port port)
2060 "Read a utmpx entry from PORT. Return either the EOF object or a utmpx
2061entry."
2062 (match (get-bytevector-n port sizeof-utmpx)
2063 ((? eof-object? eof)
2064 eof)
2065 ((? bytevector? bv)
2066 (read-utmpx bv))))
2067
29fa45f4 2068;;; syscalls.scm ends here