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