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