syscall_linux.go 69 KB

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