syscalls.scm 83 KB

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