syscall_linux.go 57 KB

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