syscall_linux.go 68 KB

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