syscall_linux.go 67 KB

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