syscall_linux.go 71 KB

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