syscalls.scm 86 KB

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