syscalls.scm 79 KB

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