syscalls.scm 90 KB

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