syscall_linux.go 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Linux system calls.
  5. // This file is compiled as ordinary Go code,
  6. // but it is also input to mksyscall,
  7. // which parses the //sys lines and generates system call stubs.
  8. // Note that sometimes we use a lowercase //sys name and
  9. // wrap it in our own nicer implementation.
  10. package unix
  11. import (
  12. "encoding/binary"
  13. "slices"
  14. "strconv"
  15. "syscall"
  16. "time"
  17. "unsafe"
  18. )
  19. /*
  20. * Wrapped
  21. */
  22. func Access(path string, mode uint32) (err error) {
  23. return Faccessat(AT_FDCWD, path, mode, 0)
  24. }
  25. func Chmod(path string, mode uint32) (err error) {
  26. return Fchmodat(AT_FDCWD, path, mode, 0)
  27. }
  28. func Chown(path string, uid int, gid int) (err error) {
  29. return Fchownat(AT_FDCWD, path, uid, gid, 0)
  30. }
  31. func Creat(path string, mode uint32) (fd int, err error) {
  32. return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
  33. }
  34. func EpollCreate(size int) (fd int, err error) {
  35. if size <= 0 {
  36. return -1, EINVAL
  37. }
  38. return EpollCreate1(0)
  39. }
  40. //sys FanotifyInit(flags uint, event_f_flags uint) (fd int, err error)
  41. //sys fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error)
  42. func FanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname string) (err error) {
  43. if pathname == "" {
  44. return fanotifyMark(fd, flags, mask, dirFd, nil)
  45. }
  46. p, err := BytePtrFromString(pathname)
  47. if err != nil {
  48. return err
  49. }
  50. return fanotifyMark(fd, flags, mask, dirFd, p)
  51. }
  52. //sys fchmodat(dirfd int, path string, mode uint32) (err error)
  53. //sys fchmodat2(dirfd int, path string, mode uint32, flags int) (err error)
  54. func Fchmodat(dirfd int, path string, mode uint32, flags int) error {
  55. // Linux fchmodat doesn't support the flags parameter, but fchmodat2 does.
  56. // Try fchmodat2 if flags are specified.
  57. if flags != 0 {
  58. err := fchmodat2(dirfd, path, mode, flags)
  59. if err == ENOSYS {
  60. // fchmodat2 isn't available. If the flags are known to be valid,
  61. // return EOPNOTSUPP to indicate that fchmodat doesn't support them.
  62. if flags&^(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 {
  63. return EINVAL
  64. } else if flags&(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 {
  65. return EOPNOTSUPP
  66. }
  67. }
  68. return err
  69. }
  70. return fchmodat(dirfd, path, mode)
  71. }
  72. func InotifyInit() (fd int, err error) {
  73. return InotifyInit1(0)
  74. }
  75. //sys ioctl(fd int, req uint, arg uintptr) (err error) = SYS_IOCTL
  76. //sys ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL
  77. // ioctl itself should not be exposed directly, but additional get/set functions
  78. // for specific types are permissible. These are defined in ioctl.go and
  79. // ioctl_linux.go.
  80. //
  81. // The third argument to ioctl is often a pointer but sometimes an integer.
  82. // Callers should use ioctlPtr when the third argument is a pointer and ioctl
  83. // when the third argument is an integer.
  84. //
  85. // TODO: some existing code incorrectly uses ioctl when it should use ioctlPtr.
  86. //sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
  87. func Link(oldpath string, newpath string) (err error) {
  88. return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
  89. }
  90. func Mkdir(path string, mode uint32) (err error) {
  91. return Mkdirat(AT_FDCWD, path, mode)
  92. }
  93. func Mknod(path string, mode uint32, dev int) (err error) {
  94. return Mknodat(AT_FDCWD, path, mode, dev)
  95. }
  96. func Open(path string, mode int, perm uint32) (fd int, err error) {
  97. return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm)
  98. }
  99. //sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
  100. func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
  101. return openat(dirfd, path, flags|O_LARGEFILE, mode)
  102. }
  103. //sys openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error)
  104. func Openat2(dirfd int, path string, how *OpenHow) (fd int, err error) {
  105. return openat2(dirfd, path, how, SizeofOpenHow)
  106. }
  107. func Pipe(p []int) error {
  108. return Pipe2(p, 0)
  109. }
  110. //sysnb pipe2(p *[2]_C_int, flags int) (err error)
  111. func Pipe2(p []int, flags int) error {
  112. if len(p) != 2 {
  113. return EINVAL
  114. }
  115. var pp [2]_C_int
  116. err := pipe2(&pp, flags)
  117. if err == nil {
  118. p[0] = int(pp[0])
  119. p[1] = int(pp[1])
  120. }
  121. return err
  122. }
  123. //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
  124. func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
  125. if len(fds) == 0 {
  126. return ppoll(nil, 0, timeout, sigmask)
  127. }
  128. return ppoll(&fds[0], len(fds), timeout, sigmask)
  129. }
  130. func Poll(fds []PollFd, timeout int) (n int, err error) {
  131. var ts *Timespec
  132. if timeout >= 0 {
  133. ts = new(Timespec)
  134. *ts = NsecToTimespec(int64(timeout) * 1e6)
  135. }
  136. return Ppoll(fds, ts, nil)
  137. }
  138. //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
  139. func Readlink(path string, buf []byte) (n int, err error) {
  140. return Readlinkat(AT_FDCWD, path, buf)
  141. }
  142. func Rename(oldpath string, newpath string) (err error) {
  143. return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
  144. }
  145. func Rmdir(path string) error {
  146. return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
  147. }
  148. //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
  149. func Symlink(oldpath string, newpath string) (err error) {
  150. return Symlinkat(oldpath, AT_FDCWD, newpath)
  151. }
  152. func Unlink(path string) error {
  153. return Unlinkat(AT_FDCWD, path, 0)
  154. }
  155. //sys Unlinkat(dirfd int, path string, flags int) (err error)
  156. func Utimes(path string, tv []Timeval) error {
  157. if tv == nil {
  158. err := utimensat(AT_FDCWD, path, nil, 0)
  159. if err != ENOSYS {
  160. return err
  161. }
  162. return utimes(path, nil)
  163. }
  164. if len(tv) != 2 {
  165. return EINVAL
  166. }
  167. var ts [2]Timespec
  168. ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
  169. ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
  170. err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
  171. if err != ENOSYS {
  172. return err
  173. }
  174. return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  175. }
  176. //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
  177. func UtimesNano(path string, ts []Timespec) error {
  178. return UtimesNanoAt(AT_FDCWD, path, ts, 0)
  179. }
  180. func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
  181. if ts == nil {
  182. return utimensat(dirfd, path, nil, flags)
  183. }
  184. if len(ts) != 2 {
  185. return EINVAL
  186. }
  187. return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
  188. }
  189. func Futimesat(dirfd int, path string, tv []Timeval) error {
  190. if tv == nil {
  191. return futimesat(dirfd, path, nil)
  192. }
  193. if len(tv) != 2 {
  194. return EINVAL
  195. }
  196. return futimesat(dirfd, path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  197. }
  198. func Futimes(fd int, tv []Timeval) (err error) {
  199. // Believe it or not, this is the best we can do on Linux
  200. // (and is what glibc does).
  201. return Utimes("/proc/self/fd/"+strconv.Itoa(fd), tv)
  202. }
  203. const ImplementsGetwd = true
  204. //sys Getcwd(buf []byte) (n int, err error)
  205. func Getwd() (wd string, err error) {
  206. var buf [PathMax]byte
  207. n, err := Getcwd(buf[0:])
  208. if err != nil {
  209. return "", err
  210. }
  211. // Getcwd returns the number of bytes written to buf, including the NUL.
  212. if n < 1 || n > len(buf) || buf[n-1] != 0 {
  213. return "", EINVAL
  214. }
  215. // In some cases, Linux can return a path that starts with the
  216. // "(unreachable)" prefix, which can potentially be a valid relative
  217. // path. To work around that, return ENOENT if path is not absolute.
  218. if buf[0] != '/' {
  219. return "", ENOENT
  220. }
  221. return string(buf[0 : n-1]), nil
  222. }
  223. func Getgroups() (gids []int, err error) {
  224. n, err := getgroups(0, nil)
  225. if err != nil {
  226. return nil, err
  227. }
  228. if n == 0 {
  229. return nil, nil
  230. }
  231. // Sanity check group count. Max is 1<<16 on Linux.
  232. if n < 0 || n > 1<<20 {
  233. return nil, EINVAL
  234. }
  235. a := make([]_Gid_t, n)
  236. n, err = getgroups(n, &a[0])
  237. if err != nil {
  238. return nil, err
  239. }
  240. gids = make([]int, n)
  241. for i, v := range a[0:n] {
  242. gids[i] = int(v)
  243. }
  244. return
  245. }
  246. func Setgroups(gids []int) (err error) {
  247. if len(gids) == 0 {
  248. return setgroups(0, nil)
  249. }
  250. a := make([]_Gid_t, len(gids))
  251. for i, v := range gids {
  252. a[i] = _Gid_t(v)
  253. }
  254. return setgroups(len(a), &a[0])
  255. }
  256. type WaitStatus uint32
  257. // Wait status is 7 bits at bottom, either 0 (exited),
  258. // 0x7F (stopped), or a signal number that caused an exit.
  259. // The 0x80 bit is whether there was a core dump.
  260. // An extra number (exit code, signal causing a stop)
  261. // is in the high bits. At least that's the idea.
  262. // There are various irregularities. For example, the
  263. // "continued" status is 0xFFFF, distinguishing itself
  264. // from stopped via the core dump bit.
  265. const (
  266. mask = 0x7F
  267. core = 0x80
  268. exited = 0x00
  269. stopped = 0x7F
  270. shift = 8
  271. )
  272. func (w WaitStatus) Exited() bool { return w&mask == exited }
  273. func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
  274. func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
  275. func (w WaitStatus) Continued() bool { return w == 0xFFFF }
  276. func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
  277. func (w WaitStatus) ExitStatus() int {
  278. if !w.Exited() {
  279. return -1
  280. }
  281. return int(w>>shift) & 0xFF
  282. }
  283. func (w WaitStatus) Signal() syscall.Signal {
  284. if !w.Signaled() {
  285. return -1
  286. }
  287. return syscall.Signal(w & mask)
  288. }
  289. func (w WaitStatus) StopSignal() syscall.Signal {
  290. if !w.Stopped() {
  291. return -1
  292. }
  293. return syscall.Signal(w>>shift) & 0xFF
  294. }
  295. func (w WaitStatus) TrapCause() int {
  296. if w.StopSignal() != SIGTRAP {
  297. return -1
  298. }
  299. return int(w>>shift) >> 8
  300. }
  301. //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
  302. func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
  303. var status _C_int
  304. wpid, err = wait4(pid, &status, options, rusage)
  305. if wstatus != nil {
  306. *wstatus = WaitStatus(status)
  307. }
  308. return
  309. }
  310. //sys Waitid(idType int, id int, info *Siginfo, options int, rusage *Rusage) (err error)
  311. func Mkfifo(path string, mode uint32) error {
  312. return Mknod(path, mode|S_IFIFO, 0)
  313. }
  314. func Mkfifoat(dirfd int, path string, mode uint32) error {
  315. return Mknodat(dirfd, path, mode|S_IFIFO, 0)
  316. }
  317. func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
  318. if sa.Port < 0 || sa.Port > 0xFFFF {
  319. return nil, 0, EINVAL
  320. }
  321. sa.raw.Family = AF_INET
  322. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  323. p[0] = byte(sa.Port >> 8)
  324. p[1] = byte(sa.Port)
  325. sa.raw.Addr = sa.Addr
  326. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
  327. }
  328. func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
  329. if sa.Port < 0 || sa.Port > 0xFFFF {
  330. return nil, 0, EINVAL
  331. }
  332. sa.raw.Family = AF_INET6
  333. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  334. p[0] = byte(sa.Port >> 8)
  335. p[1] = byte(sa.Port)
  336. sa.raw.Scope_id = sa.ZoneId
  337. sa.raw.Addr = sa.Addr
  338. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
  339. }
  340. func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
  341. name := sa.Name
  342. n := len(name)
  343. if n >= len(sa.raw.Path) {
  344. return nil, 0, EINVAL
  345. }
  346. sa.raw.Family = AF_UNIX
  347. for i := range n {
  348. sa.raw.Path[i] = int8(name[i])
  349. }
  350. // length is family (uint16), name, NUL.
  351. sl := _Socklen(2)
  352. if n > 0 {
  353. sl += _Socklen(n) + 1
  354. }
  355. if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) {
  356. // Check sl > 3 so we don't change unnamed socket behavior.
  357. sa.raw.Path[0] = 0
  358. // Don't count trailing NUL for abstract address.
  359. sl--
  360. }
  361. return unsafe.Pointer(&sa.raw), sl, nil
  362. }
  363. // SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets.
  364. type SockaddrLinklayer struct {
  365. Protocol uint16
  366. Ifindex int
  367. Hatype uint16
  368. Pkttype uint8
  369. Halen uint8
  370. Addr [8]byte
  371. raw RawSockaddrLinklayer
  372. }
  373. func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
  374. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  375. return nil, 0, EINVAL
  376. }
  377. sa.raw.Family = AF_PACKET
  378. sa.raw.Protocol = sa.Protocol
  379. sa.raw.Ifindex = int32(sa.Ifindex)
  380. sa.raw.Hatype = sa.Hatype
  381. sa.raw.Pkttype = sa.Pkttype
  382. sa.raw.Halen = sa.Halen
  383. sa.raw.Addr = sa.Addr
  384. return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
  385. }
  386. // SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets.
  387. type SockaddrNetlink struct {
  388. Family uint16
  389. Pad uint16
  390. Pid uint32
  391. Groups uint32
  392. raw RawSockaddrNetlink
  393. }
  394. func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
  395. sa.raw.Family = AF_NETLINK
  396. sa.raw.Pad = sa.Pad
  397. sa.raw.Pid = sa.Pid
  398. sa.raw.Groups = sa.Groups
  399. return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
  400. }
  401. // SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets
  402. // using the HCI protocol.
  403. type SockaddrHCI struct {
  404. Dev uint16
  405. Channel uint16
  406. raw RawSockaddrHCI
  407. }
  408. func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
  409. sa.raw.Family = AF_BLUETOOTH
  410. sa.raw.Dev = sa.Dev
  411. sa.raw.Channel = sa.Channel
  412. return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
  413. }
  414. // SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets
  415. // using the L2CAP protocol.
  416. type SockaddrL2 struct {
  417. PSM uint16
  418. CID uint16
  419. Addr [6]uint8
  420. AddrType uint8
  421. raw RawSockaddrL2
  422. }
  423. func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) {
  424. sa.raw.Family = AF_BLUETOOTH
  425. psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm))
  426. psm[0] = byte(sa.PSM)
  427. psm[1] = byte(sa.PSM >> 8)
  428. for i := range len(sa.Addr) {
  429. sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i]
  430. }
  431. cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid))
  432. cid[0] = byte(sa.CID)
  433. cid[1] = byte(sa.CID >> 8)
  434. sa.raw.Bdaddr_type = sa.AddrType
  435. return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil
  436. }
  437. // SockaddrRFCOMM implements the Sockaddr interface for AF_BLUETOOTH type sockets
  438. // using the RFCOMM protocol.
  439. //
  440. // Server example:
  441. //
  442. // fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
  443. // _ = unix.Bind(fd, &unix.SockaddrRFCOMM{
  444. // Channel: 1,
  445. // Addr: [6]uint8{0, 0, 0, 0, 0, 0}, // BDADDR_ANY or 00:00:00:00:00:00
  446. // })
  447. // _ = Listen(fd, 1)
  448. // nfd, sa, _ := Accept(fd)
  449. // fmt.Printf("conn addr=%v fd=%d", sa.(*unix.SockaddrRFCOMM).Addr, nfd)
  450. // Read(nfd, buf)
  451. //
  452. // Client example:
  453. //
  454. // fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
  455. // _ = Connect(fd, &SockaddrRFCOMM{
  456. // Channel: 1,
  457. // Addr: [6]byte{0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc}, // CC:BB:AA:33:22:11
  458. // })
  459. // Write(fd, []byte(`hello`))
  460. type SockaddrRFCOMM struct {
  461. // Addr represents a bluetooth address, byte ordering is little-endian.
  462. Addr [6]uint8
  463. // Channel is a designated bluetooth channel, only 1-30 are available for use.
  464. // Since Linux 2.6.7 and further zero value is the first available channel.
  465. Channel uint8
  466. raw RawSockaddrRFCOMM
  467. }
  468. func (sa *SockaddrRFCOMM) sockaddr() (unsafe.Pointer, _Socklen, error) {
  469. sa.raw.Family = AF_BLUETOOTH
  470. sa.raw.Channel = sa.Channel
  471. sa.raw.Bdaddr = sa.Addr
  472. return unsafe.Pointer(&sa.raw), SizeofSockaddrRFCOMM, nil
  473. }
  474. // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets.
  475. // The RxID and TxID fields are used for transport protocol addressing in
  476. // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with
  477. // zero values for CAN_RAW and CAN_BCM sockets as they have no meaning.
  478. //
  479. // The SockaddrCAN struct must be bound to the socket file descriptor
  480. // using Bind before the CAN socket can be used.
  481. //
  482. // // Read one raw CAN frame
  483. // fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW)
  484. // addr := &SockaddrCAN{Ifindex: index}
  485. // Bind(fd, addr)
  486. // frame := make([]byte, 16)
  487. // Read(fd, frame)
  488. //
  489. // The full SocketCAN documentation can be found in the linux kernel
  490. // archives at: https://www.kernel.org/doc/Documentation/networking/can.txt
  491. type SockaddrCAN struct {
  492. Ifindex int
  493. RxID uint32
  494. TxID uint32
  495. raw RawSockaddrCAN
  496. }
  497. func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
  498. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  499. return nil, 0, EINVAL
  500. }
  501. sa.raw.Family = AF_CAN
  502. sa.raw.Ifindex = int32(sa.Ifindex)
  503. rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
  504. for i := range 4 {
  505. sa.raw.Addr[i] = rx[i]
  506. }
  507. tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
  508. for i := range 4 {
  509. sa.raw.Addr[i+4] = tx[i]
  510. }
  511. return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
  512. }
  513. // SockaddrCANJ1939 implements the Sockaddr interface for AF_CAN using J1939
  514. // protocol (https://en.wikipedia.org/wiki/SAE_J1939). For more information
  515. // on the purposes of the fields, check the official linux kernel documentation
  516. // available here: https://www.kernel.org/doc/Documentation/networking/j1939.rst
  517. type SockaddrCANJ1939 struct {
  518. Ifindex int
  519. Name uint64
  520. PGN uint32
  521. Addr uint8
  522. raw RawSockaddrCAN
  523. }
  524. func (sa *SockaddrCANJ1939) sockaddr() (unsafe.Pointer, _Socklen, error) {
  525. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  526. return nil, 0, EINVAL
  527. }
  528. sa.raw.Family = AF_CAN
  529. sa.raw.Ifindex = int32(sa.Ifindex)
  530. n := (*[8]byte)(unsafe.Pointer(&sa.Name))
  531. for i := range 8 {
  532. sa.raw.Addr[i] = n[i]
  533. }
  534. p := (*[4]byte)(unsafe.Pointer(&sa.PGN))
  535. for i := range 4 {
  536. sa.raw.Addr[i+8] = p[i]
  537. }
  538. sa.raw.Addr[12] = sa.Addr
  539. return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
  540. }
  541. // SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
  542. // SockaddrALG enables userspace access to the Linux kernel's cryptography
  543. // subsystem. The Type and Name fields specify which type of hash or cipher
  544. // should be used with a given socket.
  545. //
  546. // To create a file descriptor that provides access to a hash or cipher, both
  547. // Bind and Accept must be used. Once the setup process is complete, input
  548. // data can be written to the socket, processed by the kernel, and then read
  549. // back as hash output or ciphertext.
  550. //
  551. // Here is an example of using an AF_ALG socket with SHA1 hashing.
  552. // The initial socket setup process is as follows:
  553. //
  554. // // Open a socket to perform SHA1 hashing.
  555. // fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
  556. // addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
  557. // unix.Bind(fd, addr)
  558. // // Note: unix.Accept does not work at this time; must invoke accept()
  559. // // manually using unix.Syscall.
  560. // hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
  561. //
  562. // Once a file descriptor has been returned from Accept, it may be used to
  563. // perform SHA1 hashing. The descriptor is not safe for concurrent use, but
  564. // may be re-used repeatedly with subsequent Write and Read operations.
  565. //
  566. // When hashing a small byte slice or string, a single Write and Read may
  567. // be used:
  568. //
  569. // // Assume hashfd is already configured using the setup process.
  570. // hash := os.NewFile(hashfd, "sha1")
  571. // // Hash an input string and read the results. Each Write discards
  572. // // previous hash state. Read always reads the current state.
  573. // b := make([]byte, 20)
  574. // for i := 0; i < 2; i++ {
  575. // io.WriteString(hash, "Hello, world.")
  576. // hash.Read(b)
  577. // fmt.Println(hex.EncodeToString(b))
  578. // }
  579. // // Output:
  580. // // 2ae01472317d1935a84797ec1983ae243fc6aa28
  581. // // 2ae01472317d1935a84797ec1983ae243fc6aa28
  582. //
  583. // For hashing larger byte slices, or byte streams such as those read from
  584. // a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
  585. // the hash digest instead of creating a new one for a given chunk and finalizing it.
  586. //
  587. // // Assume hashfd and addr are already configured using the setup process.
  588. // hash := os.NewFile(hashfd, "sha1")
  589. // // Hash the contents of a file.
  590. // f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
  591. // b := make([]byte, 4096)
  592. // for {
  593. // n, err := f.Read(b)
  594. // if err == io.EOF {
  595. // break
  596. // }
  597. // unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
  598. // }
  599. // hash.Read(b)
  600. // fmt.Println(hex.EncodeToString(b))
  601. // // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
  602. //
  603. // For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
  604. type SockaddrALG struct {
  605. Type string
  606. Name string
  607. Feature uint32
  608. Mask uint32
  609. raw RawSockaddrALG
  610. }
  611. func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
  612. // Leave room for NUL byte terminator.
  613. if len(sa.Type) > len(sa.raw.Type)-1 {
  614. return nil, 0, EINVAL
  615. }
  616. if len(sa.Name) > len(sa.raw.Name)-1 {
  617. return nil, 0, EINVAL
  618. }
  619. sa.raw.Family = AF_ALG
  620. sa.raw.Feat = sa.Feature
  621. sa.raw.Mask = sa.Mask
  622. copy(sa.raw.Type[:], sa.Type)
  623. copy(sa.raw.Name[:], sa.Name)
  624. return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
  625. }
  626. // SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
  627. // SockaddrVM provides access to Linux VM sockets: a mechanism that enables
  628. // bidirectional communication between a hypervisor and its guest virtual
  629. // machines.
  630. type SockaddrVM struct {
  631. // CID and Port specify a context ID and port address for a VM socket.
  632. // Guests have a unique CID, and hosts may have a well-known CID of:
  633. // - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
  634. // - VMADDR_CID_LOCAL: refers to local communication (loopback).
  635. // - VMADDR_CID_HOST: refers to other processes on the host.
  636. CID uint32
  637. Port uint32
  638. Flags uint8
  639. raw RawSockaddrVM
  640. }
  641. func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
  642. sa.raw.Family = AF_VSOCK
  643. sa.raw.Port = sa.Port
  644. sa.raw.Cid = sa.CID
  645. sa.raw.Flags = sa.Flags
  646. return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
  647. }
  648. type SockaddrXDP struct {
  649. Flags uint16
  650. Ifindex uint32
  651. QueueID uint32
  652. SharedUmemFD uint32
  653. raw RawSockaddrXDP
  654. }
  655. func (sa *SockaddrXDP) sockaddr() (unsafe.Pointer, _Socklen, error) {
  656. sa.raw.Family = AF_XDP
  657. sa.raw.Flags = sa.Flags
  658. sa.raw.Ifindex = sa.Ifindex
  659. sa.raw.Queue_id = sa.QueueID
  660. sa.raw.Shared_umem_fd = sa.SharedUmemFD
  661. return unsafe.Pointer(&sa.raw), SizeofSockaddrXDP, nil
  662. }
  663. // This constant mirrors the #define of PX_PROTO_OE in
  664. // linux/if_pppox.h. We're defining this by hand here instead of
  665. // autogenerating through mkerrors.sh because including
  666. // linux/if_pppox.h causes some declaration conflicts with other
  667. // includes (linux/if_pppox.h includes linux/in.h, which conflicts
  668. // with netinet/in.h). Given that we only need a single zero constant
  669. // out of that file, it's cleaner to just define it by hand here.
  670. const px_proto_oe = 0
  671. type SockaddrPPPoE struct {
  672. SID uint16
  673. Remote []byte
  674. Dev string
  675. raw RawSockaddrPPPoX
  676. }
  677. func (sa *SockaddrPPPoE) sockaddr() (unsafe.Pointer, _Socklen, error) {
  678. if len(sa.Remote) != 6 {
  679. return nil, 0, EINVAL
  680. }
  681. if len(sa.Dev) > IFNAMSIZ-1 {
  682. return nil, 0, EINVAL
  683. }
  684. *(*uint16)(unsafe.Pointer(&sa.raw[0])) = AF_PPPOX
  685. // This next field is in host-endian byte order. We can't use the
  686. // same unsafe pointer cast as above, because this value is not
  687. // 32-bit aligned and some architectures don't allow unaligned
  688. // access.
  689. //
  690. // However, the value of px_proto_oe is 0, so we can use
  691. // encoding/binary helpers to write the bytes without worrying
  692. // about the ordering.
  693. binary.BigEndian.PutUint32(sa.raw[2:6], px_proto_oe)
  694. // This field is deliberately big-endian, unlike the previous
  695. // one. The kernel expects SID to be in network byte order.
  696. binary.BigEndian.PutUint16(sa.raw[6:8], sa.SID)
  697. copy(sa.raw[8:14], sa.Remote)
  698. for i := 14; i < 14+IFNAMSIZ; i++ {
  699. sa.raw[i] = 0
  700. }
  701. copy(sa.raw[14:], sa.Dev)
  702. return unsafe.Pointer(&sa.raw), SizeofSockaddrPPPoX, nil
  703. }
  704. // SockaddrTIPC implements the Sockaddr interface for AF_TIPC type sockets.
  705. // For more information on TIPC, see: http://tipc.sourceforge.net/.
  706. type SockaddrTIPC struct {
  707. // Scope is the publication scopes when binding service/service range.
  708. // Should be set to TIPC_CLUSTER_SCOPE or TIPC_NODE_SCOPE.
  709. Scope int
  710. // Addr is the type of address used to manipulate a socket. Addr must be
  711. // one of:
  712. // - *TIPCSocketAddr: "id" variant in the C addr union
  713. // - *TIPCServiceRange: "nameseq" variant in the C addr union
  714. // - *TIPCServiceName: "name" variant in the C addr union
  715. //
  716. // If nil, EINVAL will be returned when the structure is used.
  717. Addr TIPCAddr
  718. raw RawSockaddrTIPC
  719. }
  720. // TIPCAddr is implemented by types that can be used as an address for
  721. // SockaddrTIPC. It is only implemented by *TIPCSocketAddr, *TIPCServiceRange,
  722. // and *TIPCServiceName.
  723. type TIPCAddr interface {
  724. tipcAddrtype() uint8
  725. tipcAddr() [12]byte
  726. }
  727. func (sa *TIPCSocketAddr) tipcAddr() [12]byte {
  728. var out [12]byte
  729. copy(out[:], (*(*[unsafe.Sizeof(TIPCSocketAddr{})]byte)(unsafe.Pointer(sa)))[:])
  730. return out
  731. }
  732. func (sa *TIPCSocketAddr) tipcAddrtype() uint8 { return TIPC_SOCKET_ADDR }
  733. func (sa *TIPCServiceRange) tipcAddr() [12]byte {
  734. var out [12]byte
  735. copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceRange{})]byte)(unsafe.Pointer(sa)))[:])
  736. return out
  737. }
  738. func (sa *TIPCServiceRange) tipcAddrtype() uint8 { return TIPC_SERVICE_RANGE }
  739. func (sa *TIPCServiceName) tipcAddr() [12]byte {
  740. var out [12]byte
  741. copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceName{})]byte)(unsafe.Pointer(sa)))[:])
  742. return out
  743. }
  744. func (sa *TIPCServiceName) tipcAddrtype() uint8 { return TIPC_SERVICE_ADDR }
  745. func (sa *SockaddrTIPC) sockaddr() (unsafe.Pointer, _Socklen, error) {
  746. if sa.Addr == nil {
  747. return nil, 0, EINVAL
  748. }
  749. sa.raw.Family = AF_TIPC
  750. sa.raw.Scope = int8(sa.Scope)
  751. sa.raw.Addrtype = sa.Addr.tipcAddrtype()
  752. sa.raw.Addr = sa.Addr.tipcAddr()
  753. return unsafe.Pointer(&sa.raw), SizeofSockaddrTIPC, nil
  754. }
  755. // SockaddrL2TPIP implements the Sockaddr interface for IPPROTO_L2TP/AF_INET sockets.
  756. type SockaddrL2TPIP struct {
  757. Addr [4]byte
  758. ConnId uint32
  759. raw RawSockaddrL2TPIP
  760. }
  761. func (sa *SockaddrL2TPIP) sockaddr() (unsafe.Pointer, _Socklen, error) {
  762. sa.raw.Family = AF_INET
  763. sa.raw.Conn_id = sa.ConnId
  764. sa.raw.Addr = sa.Addr
  765. return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP, nil
  766. }
  767. // SockaddrL2TPIP6 implements the Sockaddr interface for IPPROTO_L2TP/AF_INET6 sockets.
  768. type SockaddrL2TPIP6 struct {
  769. Addr [16]byte
  770. ZoneId uint32
  771. ConnId uint32
  772. raw RawSockaddrL2TPIP6
  773. }
  774. func (sa *SockaddrL2TPIP6) sockaddr() (unsafe.Pointer, _Socklen, error) {
  775. sa.raw.Family = AF_INET6
  776. sa.raw.Conn_id = sa.ConnId
  777. sa.raw.Scope_id = sa.ZoneId
  778. sa.raw.Addr = sa.Addr
  779. return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP6, nil
  780. }
  781. // SockaddrIUCV implements the Sockaddr interface for AF_IUCV sockets.
  782. type SockaddrIUCV struct {
  783. UserID string
  784. Name string
  785. raw RawSockaddrIUCV
  786. }
  787. func (sa *SockaddrIUCV) sockaddr() (unsafe.Pointer, _Socklen, error) {
  788. sa.raw.Family = AF_IUCV
  789. // These are EBCDIC encoded by the kernel, but we still need to pad them
  790. // with blanks. Initializing with blanks allows the caller to feed in either
  791. // a padded or an unpadded string.
  792. for i := range 8 {
  793. sa.raw.Nodeid[i] = ' '
  794. sa.raw.User_id[i] = ' '
  795. sa.raw.Name[i] = ' '
  796. }
  797. if len(sa.UserID) > 8 || len(sa.Name) > 8 {
  798. return nil, 0, EINVAL
  799. }
  800. for i, b := range []byte(sa.UserID[:]) {
  801. sa.raw.User_id[i] = int8(b)
  802. }
  803. for i, b := range []byte(sa.Name[:]) {
  804. sa.raw.Name[i] = int8(b)
  805. }
  806. return unsafe.Pointer(&sa.raw), SizeofSockaddrIUCV, nil
  807. }
  808. type SockaddrNFC struct {
  809. DeviceIdx uint32
  810. TargetIdx uint32
  811. NFCProtocol uint32
  812. raw RawSockaddrNFC
  813. }
  814. func (sa *SockaddrNFC) sockaddr() (unsafe.Pointer, _Socklen, error) {
  815. sa.raw.Sa_family = AF_NFC
  816. sa.raw.Dev_idx = sa.DeviceIdx
  817. sa.raw.Target_idx = sa.TargetIdx
  818. sa.raw.Nfc_protocol = sa.NFCProtocol
  819. return unsafe.Pointer(&sa.raw), SizeofSockaddrNFC, nil
  820. }
  821. type SockaddrNFCLLCP struct {
  822. DeviceIdx uint32
  823. TargetIdx uint32
  824. NFCProtocol uint32
  825. DestinationSAP uint8
  826. SourceSAP uint8
  827. ServiceName string
  828. raw RawSockaddrNFCLLCP
  829. }
  830. func (sa *SockaddrNFCLLCP) sockaddr() (unsafe.Pointer, _Socklen, error) {
  831. sa.raw.Sa_family = AF_NFC
  832. sa.raw.Dev_idx = sa.DeviceIdx
  833. sa.raw.Target_idx = sa.TargetIdx
  834. sa.raw.Nfc_protocol = sa.NFCProtocol
  835. sa.raw.Dsap = sa.DestinationSAP
  836. sa.raw.Ssap = sa.SourceSAP
  837. if len(sa.ServiceName) > len(sa.raw.Service_name) {
  838. return nil, 0, EINVAL
  839. }
  840. copy(sa.raw.Service_name[:], sa.ServiceName)
  841. sa.raw.SetServiceNameLen(len(sa.ServiceName))
  842. return unsafe.Pointer(&sa.raw), SizeofSockaddrNFCLLCP, nil
  843. }
  844. var socketProtocol = func(fd int) (int, error) {
  845. return GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL)
  846. }
  847. func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
  848. switch rsa.Addr.Family {
  849. case AF_NETLINK:
  850. pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
  851. sa := new(SockaddrNetlink)
  852. sa.Family = pp.Family
  853. sa.Pad = pp.Pad
  854. sa.Pid = pp.Pid
  855. sa.Groups = pp.Groups
  856. return sa, nil
  857. case AF_PACKET:
  858. pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
  859. sa := new(SockaddrLinklayer)
  860. sa.Protocol = pp.Protocol
  861. sa.Ifindex = int(pp.Ifindex)
  862. sa.Hatype = pp.Hatype
  863. sa.Pkttype = pp.Pkttype
  864. sa.Halen = pp.Halen
  865. sa.Addr = pp.Addr
  866. return sa, nil
  867. case AF_UNIX:
  868. pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
  869. sa := new(SockaddrUnix)
  870. if pp.Path[0] == 0 {
  871. // "Abstract" Unix domain socket.
  872. // Rewrite leading NUL as @ for textual display.
  873. // (This is the standard convention.)
  874. // Not friendly to overwrite in place,
  875. // but the callers below don't care.
  876. pp.Path[0] = '@'
  877. }
  878. // Assume path ends at NUL.
  879. // This is not technically the Linux semantics for
  880. // abstract Unix domain sockets--they are supposed
  881. // to be uninterpreted fixed-size binary blobs--but
  882. // everyone uses this convention.
  883. n := 0
  884. for n < len(pp.Path) && pp.Path[n] != 0 {
  885. n++
  886. }
  887. sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n))
  888. return sa, nil
  889. case AF_INET:
  890. proto, err := socketProtocol(fd)
  891. if err != nil {
  892. return nil, err
  893. }
  894. switch proto {
  895. case IPPROTO_L2TP:
  896. pp := (*RawSockaddrL2TPIP)(unsafe.Pointer(rsa))
  897. sa := new(SockaddrL2TPIP)
  898. sa.ConnId = pp.Conn_id
  899. sa.Addr = pp.Addr
  900. return sa, nil
  901. default:
  902. pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
  903. sa := new(SockaddrInet4)
  904. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  905. sa.Port = int(p[0])<<8 + int(p[1])
  906. sa.Addr = pp.Addr
  907. return sa, nil
  908. }
  909. case AF_INET6:
  910. proto, err := socketProtocol(fd)
  911. if err != nil {
  912. return nil, err
  913. }
  914. switch proto {
  915. case IPPROTO_L2TP:
  916. pp := (*RawSockaddrL2TPIP6)(unsafe.Pointer(rsa))
  917. sa := new(SockaddrL2TPIP6)
  918. sa.ConnId = pp.Conn_id
  919. sa.ZoneId = pp.Scope_id
  920. sa.Addr = pp.Addr
  921. return sa, nil
  922. default:
  923. pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
  924. sa := new(SockaddrInet6)
  925. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  926. sa.Port = int(p[0])<<8 + int(p[1])
  927. sa.ZoneId = pp.Scope_id
  928. sa.Addr = pp.Addr
  929. return sa, nil
  930. }
  931. case AF_VSOCK:
  932. pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
  933. sa := &SockaddrVM{
  934. CID: pp.Cid,
  935. Port: pp.Port,
  936. Flags: pp.Flags,
  937. }
  938. return sa, nil
  939. case AF_BLUETOOTH:
  940. proto, err := socketProtocol(fd)
  941. if err != nil {
  942. return nil, err
  943. }
  944. // only BTPROTO_L2CAP and BTPROTO_RFCOMM can accept connections
  945. switch proto {
  946. case BTPROTO_L2CAP:
  947. pp := (*RawSockaddrL2)(unsafe.Pointer(rsa))
  948. sa := &SockaddrL2{
  949. PSM: pp.Psm,
  950. CID: pp.Cid,
  951. Addr: pp.Bdaddr,
  952. AddrType: pp.Bdaddr_type,
  953. }
  954. return sa, nil
  955. case BTPROTO_RFCOMM:
  956. pp := (*RawSockaddrRFCOMM)(unsafe.Pointer(rsa))
  957. sa := &SockaddrRFCOMM{
  958. Channel: pp.Channel,
  959. Addr: pp.Bdaddr,
  960. }
  961. return sa, nil
  962. }
  963. case AF_XDP:
  964. pp := (*RawSockaddrXDP)(unsafe.Pointer(rsa))
  965. sa := &SockaddrXDP{
  966. Flags: pp.Flags,
  967. Ifindex: pp.Ifindex,
  968. QueueID: pp.Queue_id,
  969. SharedUmemFD: pp.Shared_umem_fd,
  970. }
  971. return sa, nil
  972. case AF_PPPOX:
  973. pp := (*RawSockaddrPPPoX)(unsafe.Pointer(rsa))
  974. if binary.BigEndian.Uint32(pp[2:6]) != px_proto_oe {
  975. return nil, EINVAL
  976. }
  977. sa := &SockaddrPPPoE{
  978. SID: binary.BigEndian.Uint16(pp[6:8]),
  979. Remote: pp[8:14],
  980. }
  981. for i := 14; i < 14+IFNAMSIZ; i++ {
  982. if pp[i] == 0 {
  983. sa.Dev = string(pp[14:i])
  984. break
  985. }
  986. }
  987. return sa, nil
  988. case AF_TIPC:
  989. pp := (*RawSockaddrTIPC)(unsafe.Pointer(rsa))
  990. sa := &SockaddrTIPC{
  991. Scope: int(pp.Scope),
  992. }
  993. // Determine which union variant is present in pp.Addr by checking
  994. // pp.Addrtype.
  995. switch pp.Addrtype {
  996. case TIPC_SERVICE_RANGE:
  997. sa.Addr = (*TIPCServiceRange)(unsafe.Pointer(&pp.Addr))
  998. case TIPC_SERVICE_ADDR:
  999. sa.Addr = (*TIPCServiceName)(unsafe.Pointer(&pp.Addr))
  1000. case TIPC_SOCKET_ADDR:
  1001. sa.Addr = (*TIPCSocketAddr)(unsafe.Pointer(&pp.Addr))
  1002. default:
  1003. return nil, EINVAL
  1004. }
  1005. return sa, nil
  1006. case AF_IUCV:
  1007. pp := (*RawSockaddrIUCV)(unsafe.Pointer(rsa))
  1008. var user [8]byte
  1009. var name [8]byte
  1010. for i := range 8 {
  1011. user[i] = byte(pp.User_id[i])
  1012. name[i] = byte(pp.Name[i])
  1013. }
  1014. sa := &SockaddrIUCV{
  1015. UserID: string(user[:]),
  1016. Name: string(name[:]),
  1017. }
  1018. return sa, nil
  1019. case AF_CAN:
  1020. proto, err := socketProtocol(fd)
  1021. if err != nil {
  1022. return nil, err
  1023. }
  1024. pp := (*RawSockaddrCAN)(unsafe.Pointer(rsa))
  1025. switch proto {
  1026. case CAN_J1939:
  1027. sa := &SockaddrCANJ1939{
  1028. Ifindex: int(pp.Ifindex),
  1029. }
  1030. name := (*[8]byte)(unsafe.Pointer(&sa.Name))
  1031. for i := range 8 {
  1032. name[i] = pp.Addr[i]
  1033. }
  1034. pgn := (*[4]byte)(unsafe.Pointer(&sa.PGN))
  1035. for i := range 4 {
  1036. pgn[i] = pp.Addr[i+8]
  1037. }
  1038. addr := (*[1]byte)(unsafe.Pointer(&sa.Addr))
  1039. addr[0] = pp.Addr[12]
  1040. return sa, nil
  1041. default:
  1042. sa := &SockaddrCAN{
  1043. Ifindex: int(pp.Ifindex),
  1044. }
  1045. rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
  1046. for i := range 4 {
  1047. rx[i] = pp.Addr[i]
  1048. }
  1049. tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
  1050. for i := range 4 {
  1051. tx[i] = pp.Addr[i+4]
  1052. }
  1053. return sa, nil
  1054. }
  1055. case AF_NFC:
  1056. proto, err := socketProtocol(fd)
  1057. if err != nil {
  1058. return nil, err
  1059. }
  1060. switch proto {
  1061. case NFC_SOCKPROTO_RAW:
  1062. pp := (*RawSockaddrNFC)(unsafe.Pointer(rsa))
  1063. sa := &SockaddrNFC{
  1064. DeviceIdx: pp.Dev_idx,
  1065. TargetIdx: pp.Target_idx,
  1066. NFCProtocol: pp.Nfc_protocol,
  1067. }
  1068. return sa, nil
  1069. case NFC_SOCKPROTO_LLCP:
  1070. pp := (*RawSockaddrNFCLLCP)(unsafe.Pointer(rsa))
  1071. if uint64(pp.Service_name_len) > uint64(len(pp.Service_name)) {
  1072. return nil, EINVAL
  1073. }
  1074. sa := &SockaddrNFCLLCP{
  1075. DeviceIdx: pp.Dev_idx,
  1076. TargetIdx: pp.Target_idx,
  1077. NFCProtocol: pp.Nfc_protocol,
  1078. DestinationSAP: pp.Dsap,
  1079. SourceSAP: pp.Ssap,
  1080. ServiceName: string(pp.Service_name[:pp.Service_name_len]),
  1081. }
  1082. return sa, nil
  1083. default:
  1084. return nil, EINVAL
  1085. }
  1086. }
  1087. return nil, EAFNOSUPPORT
  1088. }
  1089. func Accept(fd int) (nfd int, sa Sockaddr, err error) {
  1090. var rsa RawSockaddrAny
  1091. var len _Socklen = SizeofSockaddrAny
  1092. nfd, err = accept4(fd, &rsa, &len, 0)
  1093. if err != nil {
  1094. return
  1095. }
  1096. sa, err = anyToSockaddr(fd, &rsa)
  1097. if err != nil {
  1098. Close(nfd)
  1099. nfd = 0
  1100. }
  1101. return
  1102. }
  1103. func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
  1104. var rsa RawSockaddrAny
  1105. var len _Socklen = SizeofSockaddrAny
  1106. nfd, err = accept4(fd, &rsa, &len, flags)
  1107. if err != nil {
  1108. return
  1109. }
  1110. if len > SizeofSockaddrAny {
  1111. panic("RawSockaddrAny too small")
  1112. }
  1113. sa, err = anyToSockaddr(fd, &rsa)
  1114. if err != nil {
  1115. Close(nfd)
  1116. nfd = 0
  1117. }
  1118. return
  1119. }
  1120. func Getsockname(fd int) (sa Sockaddr, err error) {
  1121. var rsa RawSockaddrAny
  1122. var len _Socklen = SizeofSockaddrAny
  1123. if err = getsockname(fd, &rsa, &len); err != nil {
  1124. return
  1125. }
  1126. return anyToSockaddr(fd, &rsa)
  1127. }
  1128. func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
  1129. var value IPMreqn
  1130. vallen := _Socklen(SizeofIPMreqn)
  1131. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1132. return &value, err
  1133. }
  1134. func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
  1135. var value Ucred
  1136. vallen := _Socklen(SizeofUcred)
  1137. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1138. return &value, err
  1139. }
  1140. func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
  1141. var value TCPInfo
  1142. vallen := _Socklen(SizeofTCPInfo)
  1143. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1144. return &value, err
  1145. }
  1146. // GetsockoptTCPCCVegasInfo returns algorithm specific congestion control information for a socket using the "vegas"
  1147. // algorithm.
  1148. //
  1149. // The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
  1150. //
  1151. // algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
  1152. func GetsockoptTCPCCVegasInfo(fd, level, opt int) (*TCPVegasInfo, error) {
  1153. var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
  1154. vallen := _Socklen(SizeofTCPCCInfo)
  1155. err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
  1156. out := (*TCPVegasInfo)(unsafe.Pointer(&value[0]))
  1157. return out, err
  1158. }
  1159. // GetsockoptTCPCCDCTCPInfo returns algorithm specific congestion control information for a socket using the "dctp"
  1160. // algorithm.
  1161. //
  1162. // The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
  1163. //
  1164. // algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
  1165. func GetsockoptTCPCCDCTCPInfo(fd, level, opt int) (*TCPDCTCPInfo, error) {
  1166. var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
  1167. vallen := _Socklen(SizeofTCPCCInfo)
  1168. err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
  1169. out := (*TCPDCTCPInfo)(unsafe.Pointer(&value[0]))
  1170. return out, err
  1171. }
  1172. // GetsockoptTCPCCBBRInfo returns algorithm specific congestion control information for a socket using the "bbr"
  1173. // algorithm.
  1174. //
  1175. // The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
  1176. //
  1177. // algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
  1178. func GetsockoptTCPCCBBRInfo(fd, level, opt int) (*TCPBBRInfo, error) {
  1179. var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
  1180. vallen := _Socklen(SizeofTCPCCInfo)
  1181. err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
  1182. out := (*TCPBBRInfo)(unsafe.Pointer(&value[0]))
  1183. return out, err
  1184. }
  1185. // GetsockoptString returns the string value of the socket option opt for the
  1186. // socket associated with fd at the given socket level.
  1187. func GetsockoptString(fd, level, opt int) (string, error) {
  1188. buf := make([]byte, 256)
  1189. vallen := _Socklen(len(buf))
  1190. err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  1191. if err != nil {
  1192. if err == ERANGE {
  1193. buf = make([]byte, vallen)
  1194. err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  1195. }
  1196. if err != nil {
  1197. return "", err
  1198. }
  1199. }
  1200. return ByteSliceToString(buf[:vallen]), nil
  1201. }
  1202. func GetsockoptTpacketStats(fd, level, opt int) (*TpacketStats, error) {
  1203. var value TpacketStats
  1204. vallen := _Socklen(SizeofTpacketStats)
  1205. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1206. return &value, err
  1207. }
  1208. func GetsockoptTpacketStatsV3(fd, level, opt int) (*TpacketStatsV3, error) {
  1209. var value TpacketStatsV3
  1210. vallen := _Socklen(SizeofTpacketStatsV3)
  1211. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1212. return &value, err
  1213. }
  1214. func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
  1215. return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
  1216. }
  1217. func SetsockoptPacketMreq(fd, level, opt int, mreq *PacketMreq) error {
  1218. return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
  1219. }
  1220. // SetsockoptSockFprog attaches a classic BPF or an extended BPF program to a
  1221. // socket to filter incoming packets. See 'man 7 socket' for usage information.
  1222. func SetsockoptSockFprog(fd, level, opt int, fprog *SockFprog) error {
  1223. return setsockopt(fd, level, opt, unsafe.Pointer(fprog), unsafe.Sizeof(*fprog))
  1224. }
  1225. func SetsockoptCanRawFilter(fd, level, opt int, filter []CanFilter) error {
  1226. var p unsafe.Pointer
  1227. if len(filter) > 0 {
  1228. p = unsafe.Pointer(&filter[0])
  1229. }
  1230. return setsockopt(fd, level, opt, p, uintptr(len(filter)*SizeofCanFilter))
  1231. }
  1232. func SetsockoptTpacketReq(fd, level, opt int, tp *TpacketReq) error {
  1233. return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp))
  1234. }
  1235. func SetsockoptTpacketReq3(fd, level, opt int, tp *TpacketReq3) error {
  1236. return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp))
  1237. }
  1238. func SetsockoptTCPRepairOpt(fd, level, opt int, o []TCPRepairOpt) (err error) {
  1239. if len(o) == 0 {
  1240. return EINVAL
  1241. }
  1242. return setsockopt(fd, level, opt, unsafe.Pointer(&o[0]), uintptr(SizeofTCPRepairOpt*len(o)))
  1243. }
  1244. func SetsockoptTCPMD5Sig(fd, level, opt int, s *TCPMD5Sig) error {
  1245. return setsockopt(fd, level, opt, unsafe.Pointer(s), unsafe.Sizeof(*s))
  1246. }
  1247. // Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
  1248. // KeyctlInt calls keyctl commands in which each argument is an int.
  1249. // These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
  1250. // KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
  1251. // KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
  1252. // KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
  1253. //sys KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
  1254. // KeyctlBuffer calls keyctl commands in which the third and fourth
  1255. // arguments are a buffer and its length, respectively.
  1256. // These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
  1257. //sys KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
  1258. // KeyctlString calls keyctl commands which return a string.
  1259. // These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.
  1260. func KeyctlString(cmd int, id int) (string, error) {
  1261. // We must loop as the string data may change in between the syscalls.
  1262. // We could allocate a large buffer here to reduce the chance that the
  1263. // syscall needs to be called twice; however, this is unnecessary as
  1264. // the performance loss is negligible.
  1265. var buffer []byte
  1266. for {
  1267. // Try to fill the buffer with data
  1268. length, err := KeyctlBuffer(cmd, id, buffer, 0)
  1269. if err != nil {
  1270. return "", err
  1271. }
  1272. // Check if the data was written
  1273. if length <= len(buffer) {
  1274. // Exclude the null terminator
  1275. return string(buffer[:length-1]), nil
  1276. }
  1277. // Make a bigger buffer if needed
  1278. buffer = make([]byte, length)
  1279. }
  1280. }
  1281. // Keyctl commands with special signatures.
  1282. // KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
  1283. // See the full documentation at:
  1284. // http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html
  1285. func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
  1286. createInt := 0
  1287. if create {
  1288. createInt = 1
  1289. }
  1290. return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
  1291. }
  1292. // KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
  1293. // key handle permission mask as described in the "keyctl setperm" section of
  1294. // http://man7.org/linux/man-pages/man1/keyctl.1.html.
  1295. // See the full documentation at:
  1296. // http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html
  1297. func KeyctlSetperm(id int, perm uint32) error {
  1298. _, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
  1299. return err
  1300. }
  1301. //sys keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL
  1302. // KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
  1303. // See the full documentation at:
  1304. // http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html
  1305. func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
  1306. return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
  1307. }
  1308. //sys keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL
  1309. // KeyctlSearch implements the KEYCTL_SEARCH command.
  1310. // See the full documentation at:
  1311. // http://man7.org/linux/man-pages/man3/keyctl_search.3.html
  1312. func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
  1313. return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
  1314. }
  1315. //sys keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL
  1316. // KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
  1317. // command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
  1318. // of Iovec (each of which represents a buffer) instead of a single buffer.
  1319. // See the full documentation at:
  1320. // http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html
  1321. func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
  1322. return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
  1323. }
  1324. //sys keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL
  1325. // KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
  1326. // computes a Diffie-Hellman shared secret based on the provide params. The
  1327. // secret is written to the provided buffer and the returned size is the number
  1328. // of bytes written (returning an error if there is insufficient space in the
  1329. // buffer). If a nil buffer is passed in, this function returns the minimum
  1330. // buffer length needed to store the appropriate data. Note that this differs
  1331. // from KEYCTL_READ's behavior which always returns the requested payload size.
  1332. // See the full documentation at:
  1333. // http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html
  1334. func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
  1335. return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
  1336. }
  1337. // KeyctlRestrictKeyring implements the KEYCTL_RESTRICT_KEYRING command. This
  1338. // command limits the set of keys that can be linked to the keyring, regardless
  1339. // of keyring permissions. The command requires the "setattr" permission.
  1340. //
  1341. // When called with an empty keyType the command locks the keyring, preventing
  1342. // any further keys from being linked to the keyring.
  1343. //
  1344. // The "asymmetric" keyType defines restrictions requiring key payloads to be
  1345. // DER encoded X.509 certificates signed by keys in another keyring. Restrictions
  1346. // for "asymmetric" include "builtin_trusted", "builtin_and_secondary_trusted",
  1347. // "key_or_keyring:<key>", and "key_or_keyring:<key>:chain".
  1348. //
  1349. // As of Linux 4.12, only the "asymmetric" keyType defines type-specific
  1350. // restrictions.
  1351. //
  1352. // See the full documentation at:
  1353. // http://man7.org/linux/man-pages/man3/keyctl_restrict_keyring.3.html
  1354. // http://man7.org/linux/man-pages/man2/keyctl.2.html
  1355. func KeyctlRestrictKeyring(ringid int, keyType string, restriction string) error {
  1356. if keyType == "" {
  1357. return keyctlRestrictKeyring(KEYCTL_RESTRICT_KEYRING, ringid)
  1358. }
  1359. return keyctlRestrictKeyringByType(KEYCTL_RESTRICT_KEYRING, ringid, keyType, restriction)
  1360. }
  1361. //sys keyctlRestrictKeyringByType(cmd int, arg2 int, keyType string, restriction string) (err error) = SYS_KEYCTL
  1362. //sys keyctlRestrictKeyring(cmd int, arg2 int) (err error) = SYS_KEYCTL
  1363. func recvmsgRaw(fd int, iov []Iovec, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) {
  1364. var msg Msghdr
  1365. msg.Name = (*byte)(unsafe.Pointer(rsa))
  1366. msg.Namelen = uint32(SizeofSockaddrAny)
  1367. var dummy byte
  1368. if len(oob) > 0 {
  1369. if emptyIovecs(iov) {
  1370. var sockType int
  1371. sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  1372. if err != nil {
  1373. return
  1374. }
  1375. // receive at least one normal byte
  1376. if sockType != SOCK_DGRAM {
  1377. var iova [1]Iovec
  1378. iova[0].Base = &dummy
  1379. iova[0].SetLen(1)
  1380. iov = iova[:]
  1381. }
  1382. }
  1383. msg.Control = &oob[0]
  1384. msg.SetControllen(len(oob))
  1385. }
  1386. if len(iov) > 0 {
  1387. msg.Iov = &iov[0]
  1388. msg.SetIovlen(len(iov))
  1389. }
  1390. if n, err = recvmsg(fd, &msg, flags); err != nil {
  1391. return
  1392. }
  1393. oobn = int(msg.Controllen)
  1394. recvflags = int(msg.Flags)
  1395. return
  1396. }
  1397. func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) {
  1398. var msg Msghdr
  1399. msg.Name = (*byte)(ptr)
  1400. msg.Namelen = uint32(salen)
  1401. var dummy byte
  1402. var empty bool
  1403. if len(oob) > 0 {
  1404. empty = emptyIovecs(iov)
  1405. if empty {
  1406. var sockType int
  1407. sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  1408. if err != nil {
  1409. return 0, err
  1410. }
  1411. // send at least one normal byte
  1412. if sockType != SOCK_DGRAM {
  1413. var iova [1]Iovec
  1414. iova[0].Base = &dummy
  1415. iova[0].SetLen(1)
  1416. iov = iova[:]
  1417. }
  1418. }
  1419. msg.Control = &oob[0]
  1420. msg.SetControllen(len(oob))
  1421. }
  1422. if len(iov) > 0 {
  1423. msg.Iov = &iov[0]
  1424. msg.SetIovlen(len(iov))
  1425. }
  1426. if n, err = sendmsg(fd, &msg, flags); err != nil {
  1427. return 0, err
  1428. }
  1429. if len(oob) > 0 && empty {
  1430. n = 0
  1431. }
  1432. return n, nil
  1433. }
  1434. // BindToDevice binds the socket associated with fd to device.
  1435. func BindToDevice(fd int, device string) (err error) {
  1436. return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
  1437. }
  1438. //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
  1439. //sys ptracePtr(request int, pid int, addr uintptr, data unsafe.Pointer) (err error) = SYS_PTRACE
  1440. func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
  1441. // The peek requests are machine-size oriented, so we wrap it
  1442. // to retrieve arbitrary-length data.
  1443. // The ptrace syscall differs from glibc's ptrace.
  1444. // Peeks returns the word in *data, not as the return value.
  1445. var buf [SizeofPtr]byte
  1446. // Leading edge. PEEKTEXT/PEEKDATA don't require aligned
  1447. // access (PEEKUSER warns that it might), but if we don't
  1448. // align our reads, we might straddle an unmapped page
  1449. // boundary and not get the bytes leading up to the page
  1450. // boundary.
  1451. n := 0
  1452. if addr%SizeofPtr != 0 {
  1453. err = ptracePtr(req, pid, addr-addr%SizeofPtr, unsafe.Pointer(&buf[0]))
  1454. if err != nil {
  1455. return 0, err
  1456. }
  1457. n += copy(out, buf[addr%SizeofPtr:])
  1458. out = out[n:]
  1459. }
  1460. // Remainder.
  1461. for len(out) > 0 {
  1462. // We use an internal buffer to guarantee alignment.
  1463. // It's not documented if this is necessary, but we're paranoid.
  1464. err = ptracePtr(req, pid, addr+uintptr(n), unsafe.Pointer(&buf[0]))
  1465. if err != nil {
  1466. return n, err
  1467. }
  1468. copied := copy(out, buf[0:])
  1469. n += copied
  1470. out = out[copied:]
  1471. }
  1472. return n, nil
  1473. }
  1474. func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
  1475. return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
  1476. }
  1477. func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
  1478. return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
  1479. }
  1480. func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
  1481. return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
  1482. }
  1483. func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
  1484. // As for ptracePeek, we need to align our accesses to deal
  1485. // with the possibility of straddling an invalid page.
  1486. // Leading edge.
  1487. n := 0
  1488. if addr%SizeofPtr != 0 {
  1489. var buf [SizeofPtr]byte
  1490. err = ptracePtr(peekReq, pid, addr-addr%SizeofPtr, unsafe.Pointer(&buf[0]))
  1491. if err != nil {
  1492. return 0, err
  1493. }
  1494. n += copy(buf[addr%SizeofPtr:], data)
  1495. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  1496. err = ptrace(pokeReq, pid, addr-addr%SizeofPtr, word)
  1497. if err != nil {
  1498. return 0, err
  1499. }
  1500. data = data[n:]
  1501. }
  1502. // Interior.
  1503. for len(data) > SizeofPtr {
  1504. word := *((*uintptr)(unsafe.Pointer(&data[0])))
  1505. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  1506. if err != nil {
  1507. return n, err
  1508. }
  1509. n += SizeofPtr
  1510. data = data[SizeofPtr:]
  1511. }
  1512. // Trailing edge.
  1513. if len(data) > 0 {
  1514. var buf [SizeofPtr]byte
  1515. err = ptracePtr(peekReq, pid, addr+uintptr(n), unsafe.Pointer(&buf[0]))
  1516. if err != nil {
  1517. return n, err
  1518. }
  1519. copy(buf[0:], data)
  1520. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  1521. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  1522. if err != nil {
  1523. return n, err
  1524. }
  1525. n += len(data)
  1526. }
  1527. return n, nil
  1528. }
  1529. func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
  1530. return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
  1531. }
  1532. func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
  1533. return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
  1534. }
  1535. func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) {
  1536. return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data)
  1537. }
  1538. // elfNT_PRSTATUS is a copy of the debug/elf.NT_PRSTATUS constant so
  1539. // x/sys/unix doesn't need to depend on debug/elf and thus
  1540. // compress/zlib, debug/dwarf, and other packages.
  1541. const elfNT_PRSTATUS = 1
  1542. func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
  1543. var iov Iovec
  1544. iov.Base = (*byte)(unsafe.Pointer(regsout))
  1545. iov.SetLen(int(unsafe.Sizeof(*regsout)))
  1546. return ptracePtr(PTRACE_GETREGSET, pid, uintptr(elfNT_PRSTATUS), unsafe.Pointer(&iov))
  1547. }
  1548. func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
  1549. var iov Iovec
  1550. iov.Base = (*byte)(unsafe.Pointer(regs))
  1551. iov.SetLen(int(unsafe.Sizeof(*regs)))
  1552. return ptracePtr(PTRACE_SETREGSET, pid, uintptr(elfNT_PRSTATUS), unsafe.Pointer(&iov))
  1553. }
  1554. func PtraceSetOptions(pid int, options int) (err error) {
  1555. return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
  1556. }
  1557. func PtraceGetEventMsg(pid int) (msg uint, err error) {
  1558. var data _C_long
  1559. err = ptracePtr(PTRACE_GETEVENTMSG, pid, 0, unsafe.Pointer(&data))
  1560. msg = uint(data)
  1561. return
  1562. }
  1563. func PtraceCont(pid int, signal int) (err error) {
  1564. return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
  1565. }
  1566. func PtraceSyscall(pid int, signal int) (err error) {
  1567. return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
  1568. }
  1569. func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
  1570. func PtraceInterrupt(pid int) (err error) { return ptrace(PTRACE_INTERRUPT, pid, 0, 0) }
  1571. func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
  1572. func PtraceSeize(pid int) (err error) { return ptrace(PTRACE_SEIZE, pid, 0, 0) }
  1573. func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
  1574. //sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
  1575. func Reboot(cmd int) (err error) {
  1576. return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
  1577. }
  1578. func direntIno(buf []byte) (uint64, bool) {
  1579. return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
  1580. }
  1581. func direntReclen(buf []byte) (uint64, bool) {
  1582. return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
  1583. }
  1584. func direntNamlen(buf []byte) (uint64, bool) {
  1585. reclen, ok := direntReclen(buf)
  1586. if !ok {
  1587. return 0, false
  1588. }
  1589. return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
  1590. }
  1591. //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
  1592. func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
  1593. // Certain file systems get rather angry and EINVAL if you give
  1594. // them an empty string of data, rather than NULL.
  1595. if data == "" {
  1596. return mount(source, target, fstype, flags, nil)
  1597. }
  1598. datap, err := BytePtrFromString(data)
  1599. if err != nil {
  1600. return err
  1601. }
  1602. return mount(source, target, fstype, flags, datap)
  1603. }
  1604. //sys mountSetattr(dirfd int, pathname string, flags uint, attr *MountAttr, size uintptr) (err error) = SYS_MOUNT_SETATTR
  1605. // MountSetattr is a wrapper for mount_setattr(2).
  1606. // https://man7.org/linux/man-pages/man2/mount_setattr.2.html
  1607. //
  1608. // Requires kernel >= 5.12.
  1609. func MountSetattr(dirfd int, pathname string, flags uint, attr *MountAttr) error {
  1610. return mountSetattr(dirfd, pathname, flags, attr, unsafe.Sizeof(*attr))
  1611. }
  1612. func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
  1613. if raceenabled {
  1614. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1615. }
  1616. return sendfile(outfd, infd, offset, count)
  1617. }
  1618. // Sendto
  1619. // Recvfrom
  1620. // Socketpair
  1621. /*
  1622. * Direct access
  1623. */
  1624. //sys Acct(path string) (err error)
  1625. //sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
  1626. //sys Adjtimex(buf *Timex) (state int, err error)
  1627. //sysnb Capget(hdr *CapUserHeader, data *CapUserData) (err error)
  1628. //sysnb Capset(hdr *CapUserHeader, data *CapUserData) (err error)
  1629. //sys Chdir(path string) (err error)
  1630. //sys Chroot(path string) (err error)
  1631. //sys ClockAdjtime(clockid int32, buf *Timex) (state int, err error)
  1632. //sys ClockGetres(clockid int32, res *Timespec) (err error)
  1633. //sys ClockGettime(clockid int32, time *Timespec) (err error)
  1634. //sys ClockSettime(clockid int32, time *Timespec) (err error)
  1635. //sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error)
  1636. //sys Close(fd int) (err error)
  1637. //sys CloseRange(first uint, last uint, flags uint) (err error)
  1638. //sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
  1639. //sys DeleteModule(name string, flags int) (err error)
  1640. //sys Dup(oldfd int) (fd int, err error)
  1641. func Dup2(oldfd, newfd int) error {
  1642. return Dup3(oldfd, newfd, 0)
  1643. }
  1644. //sys Dup3(oldfd int, newfd int, flags int) (err error)
  1645. //sysnb EpollCreate1(flag int) (fd int, err error)
  1646. //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
  1647. //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
  1648. //sys Exit(code int) = SYS_EXIT_GROUP
  1649. //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
  1650. //sys Fchdir(fd int) (err error)
  1651. //sys Fchmod(fd int, mode uint32) (err error)
  1652. //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
  1653. //sys Fdatasync(fd int) (err error)
  1654. //sys Fgetxattr(fd int, attr string, dest []byte) (sz int, err error)
  1655. //sys FinitModule(fd int, params string, flags int) (err error)
  1656. //sys Flistxattr(fd int, dest []byte) (sz int, err error)
  1657. //sys Flock(fd int, how int) (err error)
  1658. //sys Fremovexattr(fd int, attr string) (err error)
  1659. //sys Fsetxattr(fd int, attr string, dest []byte, flags int) (err error)
  1660. //sys Fsync(fd int) (err error)
  1661. //sys Fsmount(fd int, flags int, mountAttrs int) (fsfd int, err error)
  1662. //sys Fsopen(fsName string, flags int) (fd int, err error)
  1663. //sys Fspick(dirfd int, pathName string, flags int) (fd int, err error)
  1664. //sys fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error)
  1665. func fsconfigCommon(fd int, cmd uint, key string, value *byte, aux int) (err error) {
  1666. var keyp *byte
  1667. if keyp, err = BytePtrFromString(key); err != nil {
  1668. return
  1669. }
  1670. return fsconfig(fd, cmd, keyp, value, aux)
  1671. }
  1672. // FsconfigSetFlag is equivalent to fsconfig(2) called
  1673. // with cmd == FSCONFIG_SET_FLAG.
  1674. //
  1675. // fd is the filesystem context to act upon.
  1676. // key the parameter key to set.
  1677. func FsconfigSetFlag(fd int, key string) (err error) {
  1678. return fsconfigCommon(fd, FSCONFIG_SET_FLAG, key, nil, 0)
  1679. }
  1680. // FsconfigSetString is equivalent to fsconfig(2) called
  1681. // with cmd == FSCONFIG_SET_STRING.
  1682. //
  1683. // fd is the filesystem context to act upon.
  1684. // key the parameter key to set.
  1685. // value is the parameter value to set.
  1686. func FsconfigSetString(fd int, key string, value string) (err error) {
  1687. var valuep *byte
  1688. if valuep, err = BytePtrFromString(value); err != nil {
  1689. return
  1690. }
  1691. return fsconfigCommon(fd, FSCONFIG_SET_STRING, key, valuep, 0)
  1692. }
  1693. // FsconfigSetBinary is equivalent to fsconfig(2) called
  1694. // with cmd == FSCONFIG_SET_BINARY.
  1695. //
  1696. // fd is the filesystem context to act upon.
  1697. // key the parameter key to set.
  1698. // value is the parameter value to set.
  1699. func FsconfigSetBinary(fd int, key string, value []byte) (err error) {
  1700. if len(value) == 0 {
  1701. return EINVAL
  1702. }
  1703. return fsconfigCommon(fd, FSCONFIG_SET_BINARY, key, &value[0], len(value))
  1704. }
  1705. // FsconfigSetPath is equivalent to fsconfig(2) called
  1706. // with cmd == FSCONFIG_SET_PATH.
  1707. //
  1708. // fd is the filesystem context to act upon.
  1709. // key the parameter key to set.
  1710. // path is a non-empty path for specified key.
  1711. // atfd is a file descriptor at which to start lookup from or AT_FDCWD.
  1712. func FsconfigSetPath(fd int, key string, path string, atfd int) (err error) {
  1713. var valuep *byte
  1714. if valuep, err = BytePtrFromString(path); err != nil {
  1715. return
  1716. }
  1717. return fsconfigCommon(fd, FSCONFIG_SET_PATH, key, valuep, atfd)
  1718. }
  1719. // FsconfigSetPathEmpty is equivalent to fsconfig(2) called
  1720. // with cmd == FSCONFIG_SET_PATH_EMPTY. The same as
  1721. // FconfigSetPath but with AT_PATH_EMPTY implied.
  1722. func FsconfigSetPathEmpty(fd int, key string, path string, atfd int) (err error) {
  1723. var valuep *byte
  1724. if valuep, err = BytePtrFromString(path); err != nil {
  1725. return
  1726. }
  1727. return fsconfigCommon(fd, FSCONFIG_SET_PATH_EMPTY, key, valuep, atfd)
  1728. }
  1729. // FsconfigSetFd is equivalent to fsconfig(2) called
  1730. // with cmd == FSCONFIG_SET_FD.
  1731. //
  1732. // fd is the filesystem context to act upon.
  1733. // key the parameter key to set.
  1734. // value is a file descriptor to be assigned to specified key.
  1735. func FsconfigSetFd(fd int, key string, value int) (err error) {
  1736. return fsconfigCommon(fd, FSCONFIG_SET_FD, key, nil, value)
  1737. }
  1738. // FsconfigCreate is equivalent to fsconfig(2) called
  1739. // with cmd == FSCONFIG_CMD_CREATE.
  1740. //
  1741. // fd is the filesystem context to act upon.
  1742. func FsconfigCreate(fd int) (err error) {
  1743. return fsconfig(fd, FSCONFIG_CMD_CREATE, nil, nil, 0)
  1744. }
  1745. // FsconfigReconfigure is equivalent to fsconfig(2) called
  1746. // with cmd == FSCONFIG_CMD_RECONFIGURE.
  1747. //
  1748. // fd is the filesystem context to act upon.
  1749. func FsconfigReconfigure(fd int) (err error) {
  1750. return fsconfig(fd, FSCONFIG_CMD_RECONFIGURE, nil, nil, 0)
  1751. }
  1752. //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
  1753. //sysnb Getpgid(pid int) (pgid int, err error)
  1754. func Getpgrp() (pid int) {
  1755. pid, _ = Getpgid(0)
  1756. return
  1757. }
  1758. //sysnb Getpid() (pid int)
  1759. //sysnb Getppid() (ppid int)
  1760. //sys Getpriority(which int, who int) (prio int, err error)
  1761. func Getrandom(buf []byte, flags int) (n int, err error) {
  1762. vdsoRet, supported := vgetrandom(buf, uint32(flags))
  1763. if supported {
  1764. if vdsoRet < 0 {
  1765. return 0, errnoErr(syscall.Errno(-vdsoRet))
  1766. }
  1767. return vdsoRet, nil
  1768. }
  1769. var p *byte
  1770. if len(buf) > 0 {
  1771. p = &buf[0]
  1772. }
  1773. r, _, e := Syscall(SYS_GETRANDOM, uintptr(unsafe.Pointer(p)), uintptr(len(buf)), uintptr(flags))
  1774. if e != 0 {
  1775. return 0, errnoErr(e)
  1776. }
  1777. return int(r), nil
  1778. }
  1779. //sysnb Getrusage(who int, rusage *Rusage) (err error)
  1780. //sysnb Getsid(pid int) (sid int, err error)
  1781. //sysnb Gettid() (tid int)
  1782. //sys Getxattr(path string, attr string, dest []byte) (sz int, err error)
  1783. //sys InitModule(moduleImage []byte, params string) (err error)
  1784. //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
  1785. //sysnb InotifyInit1(flags int) (fd int, err error)
  1786. //sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
  1787. //sysnb Kill(pid int, sig syscall.Signal) (err error)
  1788. //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
  1789. //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
  1790. //sys Listxattr(path string, dest []byte) (sz int, err error)
  1791. //sys Llistxattr(path string, dest []byte) (sz int, err error)
  1792. //sys Lremovexattr(path string, attr string) (err error)
  1793. //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error)
  1794. //sys MemfdCreate(name string, flags int) (fd int, err error)
  1795. //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
  1796. //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
  1797. //sys MoveMount(fromDirfd int, fromPathName string, toDirfd int, toPathName string, flags int) (err error)
  1798. //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
  1799. //sys OpenTree(dfd int, fileName string, flags uint) (r int, err error)
  1800. //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error)
  1801. //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
  1802. //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
  1803. //sys pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error)
  1804. //sys read(fd int, p []byte) (n int, err error)
  1805. //sys Removexattr(path string, attr string) (err error)
  1806. //sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error)
  1807. //sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
  1808. //sys Setdomainname(p []byte) (err error)
  1809. //sys Sethostname(p []byte) (err error)
  1810. //sysnb Setpgid(pid int, pgid int) (err error)
  1811. //sysnb Setsid() (pid int, err error)
  1812. //sysnb Settimeofday(tv *Timeval) (err error)
  1813. //sys Setns(fd int, nstype int) (err error)
  1814. //go:linkname syscall_prlimit syscall.prlimit
  1815. func syscall_prlimit(pid, resource int, newlimit, old *syscall.Rlimit) error
  1816. func Prlimit(pid, resource int, newlimit, old *Rlimit) error {
  1817. // Just call the syscall version, because as of Go 1.21
  1818. // it will affect starting a new process.
  1819. return syscall_prlimit(pid, resource, (*syscall.Rlimit)(newlimit), (*syscall.Rlimit)(old))
  1820. }
  1821. // PrctlRetInt performs a prctl operation specified by option and further
  1822. // optional arguments arg2 through arg5 depending on option. It returns a
  1823. // non-negative integer that is returned by the prctl syscall.
  1824. func PrctlRetInt(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (int, error) {
  1825. ret, _, err := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
  1826. if err != 0 {
  1827. return 0, err
  1828. }
  1829. return int(ret), nil
  1830. }
  1831. func Setuid(uid int) (err error) {
  1832. return syscall.Setuid(uid)
  1833. }
  1834. func Setgid(gid int) (err error) {
  1835. return syscall.Setgid(gid)
  1836. }
  1837. func Setreuid(ruid, euid int) (err error) {
  1838. return syscall.Setreuid(ruid, euid)
  1839. }
  1840. func Setregid(rgid, egid int) (err error) {
  1841. return syscall.Setregid(rgid, egid)
  1842. }
  1843. func Setresuid(ruid, euid, suid int) (err error) {
  1844. return syscall.Setresuid(ruid, euid, suid)
  1845. }
  1846. func Setresgid(rgid, egid, sgid int) (err error) {
  1847. return syscall.Setresgid(rgid, egid, sgid)
  1848. }
  1849. // SetfsgidRetGid sets fsgid for current thread and returns previous fsgid set.
  1850. // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability.
  1851. // If the call fails due to other reasons, current fsgid will be returned.
  1852. func SetfsgidRetGid(gid int) (int, error) {
  1853. return setfsgid(gid)
  1854. }
  1855. // SetfsuidRetUid sets fsuid for current thread and returns previous fsuid set.
  1856. // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability
  1857. // If the call fails due to other reasons, current fsuid will be returned.
  1858. func SetfsuidRetUid(uid int) (int, error) {
  1859. return setfsuid(uid)
  1860. }
  1861. func Setfsgid(gid int) error {
  1862. _, err := setfsgid(gid)
  1863. return err
  1864. }
  1865. func Setfsuid(uid int) error {
  1866. _, err := setfsuid(uid)
  1867. return err
  1868. }
  1869. func Signalfd(fd int, sigmask *Sigset_t, flags int) (newfd int, err error) {
  1870. return signalfd(fd, sigmask, _C__NSIG/8, flags)
  1871. }
  1872. //sys Setpriority(which int, who int, prio int) (err error)
  1873. //sys Setxattr(path string, attr string, data []byte, flags int) (err error)
  1874. //sys signalfd(fd int, sigmask *Sigset_t, maskSize uintptr, flags int) (newfd int, err error) = SYS_SIGNALFD4
  1875. //sys Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error)
  1876. //sys Sync()
  1877. //sys Syncfs(fd int) (err error)
  1878. //sysnb Sysinfo(info *Sysinfo_t) (err error)
  1879. //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
  1880. //sysnb TimerfdCreate(clockid int, flags int) (fd int, err error)
  1881. //sysnb TimerfdGettime(fd int, currValue *ItimerSpec) (err error)
  1882. //sysnb TimerfdSettime(fd int, flags int, newValue *ItimerSpec, oldValue *ItimerSpec) (err error)
  1883. //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
  1884. //sysnb Times(tms *Tms) (ticks uintptr, err error)
  1885. //sysnb Umask(mask int) (oldmask int)
  1886. //sysnb Uname(buf *Utsname) (err error)
  1887. //sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
  1888. //sys Unshare(flags int) (err error)
  1889. //sys write(fd int, p []byte) (n int, err error)
  1890. //sys exitThread(code int) (err error) = SYS_EXIT
  1891. //sys readv(fd int, iovs []Iovec) (n int, err error) = SYS_READV
  1892. //sys writev(fd int, iovs []Iovec) (n int, err error) = SYS_WRITEV
  1893. //sys preadv(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PREADV
  1894. //sys pwritev(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PWRITEV
  1895. //sys preadv2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PREADV2
  1896. //sys pwritev2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PWRITEV2
  1897. // minIovec is the size of the small initial allocation used by
  1898. // Readv, Writev, etc.
  1899. //
  1900. // This small allocation gets stack allocated, which lets the
  1901. // common use case of len(iovs) <= minIovs avoid more expensive
  1902. // heap allocations.
  1903. const minIovec = 8
  1904. // appendBytes converts bs to Iovecs and appends them to vecs.
  1905. func appendBytes(vecs []Iovec, bs [][]byte) []Iovec {
  1906. for _, b := range bs {
  1907. var v Iovec
  1908. v.SetLen(len(b))
  1909. if len(b) > 0 {
  1910. v.Base = &b[0]
  1911. } else {
  1912. v.Base = (*byte)(unsafe.Pointer(&_zero))
  1913. }
  1914. vecs = append(vecs, v)
  1915. }
  1916. return vecs
  1917. }
  1918. // offs2lohi splits offs into its low and high order bits.
  1919. func offs2lohi(offs int64) (lo, hi uintptr) {
  1920. const longBits = SizeofLong * 8
  1921. return uintptr(offs), uintptr(uint64(offs) >> (longBits - 1) >> 1) // two shifts to avoid false positive in vet
  1922. }
  1923. func Readv(fd int, iovs [][]byte) (n int, err error) {
  1924. iovecs := make([]Iovec, 0, minIovec)
  1925. iovecs = appendBytes(iovecs, iovs)
  1926. n, err = readv(fd, iovecs)
  1927. readvRacedetect(iovecs, n, err)
  1928. return n, err
  1929. }
  1930. func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) {
  1931. iovecs := make([]Iovec, 0, minIovec)
  1932. iovecs = appendBytes(iovecs, iovs)
  1933. lo, hi := offs2lohi(offset)
  1934. n, err = preadv(fd, iovecs, lo, hi)
  1935. readvRacedetect(iovecs, n, err)
  1936. return n, err
  1937. }
  1938. func Preadv2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) {
  1939. iovecs := make([]Iovec, 0, minIovec)
  1940. iovecs = appendBytes(iovecs, iovs)
  1941. lo, hi := offs2lohi(offset)
  1942. n, err = preadv2(fd, iovecs, lo, hi, flags)
  1943. readvRacedetect(iovecs, n, err)
  1944. return n, err
  1945. }
  1946. func readvRacedetect(iovecs []Iovec, n int, err error) {
  1947. if !raceenabled {
  1948. return
  1949. }
  1950. for i := 0; n > 0 && i < len(iovecs); i++ {
  1951. m := min(int(iovecs[i].Len), n)
  1952. n -= m
  1953. if m > 0 {
  1954. raceWriteRange(unsafe.Pointer(iovecs[i].Base), m)
  1955. }
  1956. }
  1957. if err == nil {
  1958. raceAcquire(unsafe.Pointer(&ioSync))
  1959. }
  1960. }
  1961. func Writev(fd int, iovs [][]byte) (n int, err error) {
  1962. iovecs := make([]Iovec, 0, minIovec)
  1963. iovecs = appendBytes(iovecs, iovs)
  1964. if raceenabled {
  1965. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1966. }
  1967. n, err = writev(fd, iovecs)
  1968. writevRacedetect(iovecs, n)
  1969. return n, err
  1970. }
  1971. func Pwritev(fd int, iovs [][]byte, offset int64) (n int, err error) {
  1972. iovecs := make([]Iovec, 0, minIovec)
  1973. iovecs = appendBytes(iovecs, iovs)
  1974. if raceenabled {
  1975. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1976. }
  1977. lo, hi := offs2lohi(offset)
  1978. n, err = pwritev(fd, iovecs, lo, hi)
  1979. writevRacedetect(iovecs, n)
  1980. return n, err
  1981. }
  1982. func Pwritev2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) {
  1983. iovecs := make([]Iovec, 0, minIovec)
  1984. iovecs = appendBytes(iovecs, iovs)
  1985. if raceenabled {
  1986. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1987. }
  1988. lo, hi := offs2lohi(offset)
  1989. n, err = pwritev2(fd, iovecs, lo, hi, flags)
  1990. writevRacedetect(iovecs, n)
  1991. return n, err
  1992. }
  1993. func writevRacedetect(iovecs []Iovec, n int) {
  1994. if !raceenabled {
  1995. return
  1996. }
  1997. for i := 0; n > 0 && i < len(iovecs); i++ {
  1998. m := min(int(iovecs[i].Len), n)
  1999. n -= m
  2000. if m > 0 {
  2001. raceReadRange(unsafe.Pointer(iovecs[i].Base), m)
  2002. }
  2003. }
  2004. }
  2005. // mmap varies by architecture; see syscall_linux_*.go.
  2006. //sys munmap(addr uintptr, length uintptr) (err error)
  2007. //sys mremap(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (xaddr uintptr, err error)
  2008. //sys Madvise(b []byte, advice int) (err error)
  2009. //sys Mprotect(b []byte, prot int) (err error)
  2010. //sys Mlock(b []byte) (err error)
  2011. //sys Mlockall(flags int) (err error)
  2012. //sys Msync(b []byte, flags int) (err error)
  2013. //sys Munlock(b []byte) (err error)
  2014. //sys Munlockall() (err error)
  2015. const (
  2016. mremapFixed = MREMAP_FIXED
  2017. mremapDontunmap = MREMAP_DONTUNMAP
  2018. mremapMaymove = MREMAP_MAYMOVE
  2019. )
  2020. // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
  2021. // using the specified flags.
  2022. func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
  2023. var p unsafe.Pointer
  2024. if len(iovs) > 0 {
  2025. p = unsafe.Pointer(&iovs[0])
  2026. }
  2027. n, _, errno := Syscall6(SYS_VMSPLICE, uintptr(fd), uintptr(p), uintptr(len(iovs)), uintptr(flags), 0, 0)
  2028. if errno != 0 {
  2029. return 0, syscall.Errno(errno)
  2030. }
  2031. return int(n), nil
  2032. }
  2033. func isGroupMember(gid int) bool {
  2034. groups, err := Getgroups()
  2035. if err != nil {
  2036. return false
  2037. }
  2038. return slices.Contains(groups, gid)
  2039. }
  2040. func isCapDacOverrideSet() bool {
  2041. hdr := CapUserHeader{Version: LINUX_CAPABILITY_VERSION_3}
  2042. data := [2]CapUserData{}
  2043. err := Capget(&hdr, &data[0])
  2044. return err == nil && data[0].Effective&(1<<CAP_DAC_OVERRIDE) != 0
  2045. }
  2046. //sys faccessat(dirfd int, path string, mode uint32) (err error)
  2047. //sys Faccessat2(dirfd int, path string, mode uint32, flags int) (err error)
  2048. func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
  2049. if flags == 0 {
  2050. return faccessat(dirfd, path, mode)
  2051. }
  2052. if err := Faccessat2(dirfd, path, mode, flags); err != ENOSYS && err != EPERM {
  2053. return err
  2054. }
  2055. // The Linux kernel faccessat system call does not take any flags.
  2056. // The glibc faccessat implements the flags itself; see
  2057. // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/faccessat.c;hb=HEAD
  2058. // Because people naturally expect syscall.Faccessat to act
  2059. // like C faccessat, we do the same.
  2060. if flags & ^(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
  2061. return EINVAL
  2062. }
  2063. var st Stat_t
  2064. if err := Fstatat(dirfd, path, &st, flags&AT_SYMLINK_NOFOLLOW); err != nil {
  2065. return err
  2066. }
  2067. mode &= 7
  2068. if mode == 0 {
  2069. return nil
  2070. }
  2071. var uid int
  2072. if flags&AT_EACCESS != 0 {
  2073. uid = Geteuid()
  2074. if uid != 0 && isCapDacOverrideSet() {
  2075. // If CAP_DAC_OVERRIDE is set, file access check is
  2076. // done by the kernel in the same way as for root
  2077. // (see generic_permission() in the Linux sources).
  2078. uid = 0
  2079. }
  2080. } else {
  2081. uid = Getuid()
  2082. }
  2083. if uid == 0 {
  2084. if mode&1 == 0 {
  2085. // Root can read and write any file.
  2086. return nil
  2087. }
  2088. if st.Mode&0111 != 0 {
  2089. // Root can execute any file that anybody can execute.
  2090. return nil
  2091. }
  2092. return EACCES
  2093. }
  2094. var fmode uint32
  2095. if uint32(uid) == st.Uid {
  2096. fmode = (st.Mode >> 6) & 7
  2097. } else {
  2098. var gid int
  2099. if flags&AT_EACCESS != 0 {
  2100. gid = Getegid()
  2101. } else {
  2102. gid = Getgid()
  2103. }
  2104. if uint32(gid) == st.Gid || isGroupMember(int(st.Gid)) {
  2105. fmode = (st.Mode >> 3) & 7
  2106. } else {
  2107. fmode = st.Mode & 7
  2108. }
  2109. }
  2110. if fmode&mode == mode {
  2111. return nil
  2112. }
  2113. return EACCES
  2114. }
  2115. //sys nameToHandleAt(dirFD int, pathname string, fh *fileHandle, mountID *_C_int, flags int) (err error) = SYS_NAME_TO_HANDLE_AT
  2116. //sys openByHandleAt(mountFD int, fh *fileHandle, flags int) (fd int, err error) = SYS_OPEN_BY_HANDLE_AT
  2117. // fileHandle is the argument to nameToHandleAt and openByHandleAt. We
  2118. // originally tried to generate it via unix/linux/types.go with "type
  2119. // fileHandle C.struct_file_handle" but that generated empty structs
  2120. // for mips64 and mips64le. Instead, hard code it for now (it's the
  2121. // same everywhere else) until the mips64 generator issue is fixed.
  2122. type fileHandle struct {
  2123. Bytes uint32
  2124. Type int32
  2125. }
  2126. // FileHandle represents the C struct file_handle used by
  2127. // name_to_handle_at (see NameToHandleAt) and open_by_handle_at (see
  2128. // OpenByHandleAt).
  2129. type FileHandle struct {
  2130. *fileHandle
  2131. }
  2132. // NewFileHandle constructs a FileHandle.
  2133. func NewFileHandle(handleType int32, handle []byte) FileHandle {
  2134. const hdrSize = unsafe.Sizeof(fileHandle{})
  2135. buf := make([]byte, hdrSize+uintptr(len(handle)))
  2136. copy(buf[hdrSize:], handle)
  2137. fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
  2138. fh.Type = handleType
  2139. fh.Bytes = uint32(len(handle))
  2140. return FileHandle{fh}
  2141. }
  2142. func (fh *FileHandle) Size() int { return int(fh.fileHandle.Bytes) }
  2143. func (fh *FileHandle) Type() int32 { return fh.fileHandle.Type }
  2144. func (fh *FileHandle) Bytes() []byte {
  2145. n := fh.Size()
  2146. if n == 0 {
  2147. return nil
  2148. }
  2149. return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type))+4)), n)
  2150. }
  2151. // NameToHandleAt wraps the name_to_handle_at system call; it obtains
  2152. // a handle for a path name.
  2153. func NameToHandleAt(dirfd int, path string, flags int) (handle FileHandle, mountID int, err error) {
  2154. var mid _C_int
  2155. // Try first with a small buffer, assuming the handle will
  2156. // only be 32 bytes.
  2157. size := uint32(32 + unsafe.Sizeof(fileHandle{}))
  2158. didResize := false
  2159. for {
  2160. buf := make([]byte, size)
  2161. fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
  2162. fh.Bytes = size - uint32(unsafe.Sizeof(fileHandle{}))
  2163. err = nameToHandleAt(dirfd, path, fh, &mid, flags)
  2164. if err == EOVERFLOW {
  2165. if didResize {
  2166. // We shouldn't need to resize more than once
  2167. return
  2168. }
  2169. didResize = true
  2170. size = fh.Bytes + uint32(unsafe.Sizeof(fileHandle{}))
  2171. continue
  2172. }
  2173. if err != nil {
  2174. return
  2175. }
  2176. return FileHandle{fh}, int(mid), nil
  2177. }
  2178. }
  2179. // OpenByHandleAt wraps the open_by_handle_at system call; it opens a
  2180. // file via a handle as previously returned by NameToHandleAt.
  2181. func OpenByHandleAt(mountFD int, handle FileHandle, flags int) (fd int, err error) {
  2182. return openByHandleAt(mountFD, handle.fileHandle, flags)
  2183. }
  2184. // Klogset wraps the sys_syslog system call; it sets console_loglevel to
  2185. // the value specified by arg and passes a dummy pointer to bufp.
  2186. func Klogset(typ int, arg int) (err error) {
  2187. var p unsafe.Pointer
  2188. _, _, errno := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(p), uintptr(arg))
  2189. if errno != 0 {
  2190. return errnoErr(errno)
  2191. }
  2192. return nil
  2193. }
  2194. // RemoteIovec is Iovec with the pointer replaced with an integer.
  2195. // It is used for ProcessVMReadv and ProcessVMWritev, where the pointer
  2196. // refers to a location in a different process' address space, which
  2197. // would confuse the Go garbage collector.
  2198. type RemoteIovec struct {
  2199. Base uintptr
  2200. Len int
  2201. }
  2202. //sys ProcessVMReadv(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_READV
  2203. //sys ProcessVMWritev(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_WRITEV
  2204. //sys PidfdOpen(pid int, flags int) (fd int, err error) = SYS_PIDFD_OPEN
  2205. //sys PidfdGetfd(pidfd int, targetfd int, flags int) (fd int, err error) = SYS_PIDFD_GETFD
  2206. //sys PidfdSendSignal(pidfd int, sig Signal, info *Siginfo, flags int) (err error) = SYS_PIDFD_SEND_SIGNAL
  2207. //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error)
  2208. //sys shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error)
  2209. //sys shmdt(addr uintptr) (err error)
  2210. //sys shmget(key int, size int, flag int) (id int, err error)
  2211. //sys getitimer(which int, currValue *Itimerval) (err error)
  2212. //sys setitimer(which int, newValue *Itimerval, oldValue *Itimerval) (err error)
  2213. // MakeItimerval creates an Itimerval from interval and value durations.
  2214. func MakeItimerval(interval, value time.Duration) Itimerval {
  2215. return Itimerval{
  2216. Interval: NsecToTimeval(interval.Nanoseconds()),
  2217. Value: NsecToTimeval(value.Nanoseconds()),
  2218. }
  2219. }
  2220. // A value which may be passed to the which parameter for Getitimer and
  2221. // Setitimer.
  2222. type ItimerWhich int
  2223. // Possible which values for Getitimer and Setitimer.
  2224. const (
  2225. ItimerReal ItimerWhich = ITIMER_REAL
  2226. ItimerVirtual ItimerWhich = ITIMER_VIRTUAL
  2227. ItimerProf ItimerWhich = ITIMER_PROF
  2228. )
  2229. // Getitimer wraps getitimer(2) to return the current value of the timer
  2230. // specified by which.
  2231. func Getitimer(which ItimerWhich) (Itimerval, error) {
  2232. var it Itimerval
  2233. if err := getitimer(int(which), &it); err != nil {
  2234. return Itimerval{}, err
  2235. }
  2236. return it, nil
  2237. }
  2238. // Setitimer wraps setitimer(2) to arm or disarm the timer specified by which.
  2239. // It returns the previous value of the timer.
  2240. //
  2241. // If the Itimerval argument is the zero value, the timer will be disarmed.
  2242. func Setitimer(which ItimerWhich, it Itimerval) (Itimerval, error) {
  2243. var prev Itimerval
  2244. if err := setitimer(int(which), &it, &prev); err != nil {
  2245. return Itimerval{}, err
  2246. }
  2247. return prev, nil
  2248. }
  2249. //sysnb rtSigprocmask(how int, set *Sigset_t, oldset *Sigset_t, sigsetsize uintptr) (err error) = SYS_RT_SIGPROCMASK
  2250. func PthreadSigmask(how int, set, oldset *Sigset_t) error {
  2251. if oldset != nil {
  2252. // Explicitly clear in case Sigset_t is larger than _C__NSIG.
  2253. *oldset = Sigset_t{}
  2254. }
  2255. return rtSigprocmask(how, set, oldset, _C__NSIG/8)
  2256. }
  2257. //sysnb getresuid(ruid *_C_int, euid *_C_int, suid *_C_int)
  2258. //sysnb getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int)
  2259. func Getresuid() (ruid, euid, suid int) {
  2260. var r, e, s _C_int
  2261. getresuid(&r, &e, &s)
  2262. return int(r), int(e), int(s)
  2263. }
  2264. func Getresgid() (rgid, egid, sgid int) {
  2265. var r, e, s _C_int
  2266. getresgid(&r, &e, &s)
  2267. return int(r), int(e), int(s)
  2268. }
  2269. // Pselect is a wrapper around the Linux pselect6 system call.
  2270. // This version does not modify the timeout argument.
  2271. func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
  2272. // Per https://man7.org/linux/man-pages/man2/select.2.html#NOTES,
  2273. // The Linux pselect6() system call modifies its timeout argument.
  2274. // [Not modifying the argument] is the behavior required by POSIX.1-2001.
  2275. var mutableTimeout *Timespec
  2276. if timeout != nil {
  2277. mutableTimeout = new(Timespec)
  2278. *mutableTimeout = *timeout
  2279. }
  2280. // The final argument of the pselect6() system call is not a
  2281. // sigset_t * pointer, but is instead a structure
  2282. var kernelMask *sigset_argpack
  2283. if sigmask != nil {
  2284. wordBits := 32 << (^uintptr(0) >> 63) // see math.intSize
  2285. // A sigset stores one bit per signal,
  2286. // offset by 1 (because signal 0 does not exist).
  2287. // So the number of words needed is ⌈__C_NSIG - 1 / wordBits⌉.
  2288. sigsetWords := (_C__NSIG - 1 + wordBits - 1) / (wordBits)
  2289. sigsetBytes := uintptr(sigsetWords * (wordBits / 8))
  2290. kernelMask = &sigset_argpack{
  2291. ss: sigmask,
  2292. ssLen: sigsetBytes,
  2293. }
  2294. }
  2295. return pselect6(nfd, r, w, e, mutableTimeout, kernelMask)
  2296. }
  2297. //sys schedSetattr(pid int, attr *SchedAttr, flags uint) (err error)
  2298. //sys schedGetattr(pid int, attr *SchedAttr, size uint, flags uint) (err error)
  2299. // SchedSetAttr is a wrapper for sched_setattr(2) syscall.
  2300. // https://man7.org/linux/man-pages/man2/sched_setattr.2.html
  2301. func SchedSetAttr(pid int, attr *SchedAttr, flags uint) error {
  2302. if attr == nil {
  2303. return EINVAL
  2304. }
  2305. attr.Size = SizeofSchedAttr
  2306. return schedSetattr(pid, attr, flags)
  2307. }
  2308. // SchedGetAttr is a wrapper for sched_getattr(2) syscall.
  2309. // https://man7.org/linux/man-pages/man2/sched_getattr.2.html
  2310. func SchedGetAttr(pid int, flags uint) (*SchedAttr, error) {
  2311. attr := &SchedAttr{}
  2312. if err := schedGetattr(pid, attr, SizeofSchedAttr, flags); err != nil {
  2313. return nil, err
  2314. }
  2315. return attr, nil
  2316. }
  2317. //sys Cachestat(fd uint, crange *CachestatRange, cstat *Cachestat_t, flags uint) (err error)
  2318. //sys Mseal(b []byte, flags uint) (err error)