syscalls.scm 89 KB

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