本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1931 lines
56KB

  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. func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
  1070. var msg Msghdr
  1071. var rsa RawSockaddrAny
  1072. msg.Name = (*byte)(unsafe.Pointer(&rsa))
  1073. msg.Namelen = uint32(SizeofSockaddrAny)
  1074. var iov Iovec
  1075. if len(p) > 0 {
  1076. iov.Base = &p[0]
  1077. iov.SetLen(len(p))
  1078. }
  1079. var dummy byte
  1080. if len(oob) > 0 {
  1081. if len(p) == 0 {
  1082. var sockType int
  1083. sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  1084. if err != nil {
  1085. return
  1086. }
  1087. // receive at least one normal byte
  1088. if sockType != SOCK_DGRAM {
  1089. iov.Base = &dummy
  1090. iov.SetLen(1)
  1091. }
  1092. }
  1093. msg.Control = &oob[0]
  1094. msg.SetControllen(len(oob))
  1095. }
  1096. msg.Iov = &iov
  1097. msg.Iovlen = 1
  1098. if n, err = recvmsg(fd, &msg, flags); err != nil {
  1099. return
  1100. }
  1101. oobn = int(msg.Controllen)
  1102. recvflags = int(msg.Flags)
  1103. // source address is only specified if the socket is unconnected
  1104. if rsa.Addr.Family != AF_UNSPEC {
  1105. from, err = anyToSockaddr(fd, &rsa)
  1106. }
  1107. return
  1108. }
  1109. func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
  1110. _, err = SendmsgN(fd, p, oob, to, flags)
  1111. return
  1112. }
  1113. func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
  1114. var ptr unsafe.Pointer
  1115. var salen _Socklen
  1116. if to != nil {
  1117. var err error
  1118. ptr, salen, err = to.sockaddr()
  1119. if err != nil {
  1120. return 0, err
  1121. }
  1122. }
  1123. var msg Msghdr
  1124. msg.Name = (*byte)(ptr)
  1125. msg.Namelen = uint32(salen)
  1126. var iov Iovec
  1127. if len(p) > 0 {
  1128. iov.Base = &p[0]
  1129. iov.SetLen(len(p))
  1130. }
  1131. var dummy byte
  1132. if len(oob) > 0 {
  1133. if len(p) == 0 {
  1134. var sockType int
  1135. sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  1136. if err != nil {
  1137. return 0, err
  1138. }
  1139. // send at least one normal byte
  1140. if sockType != SOCK_DGRAM {
  1141. iov.Base = &dummy
  1142. iov.SetLen(1)
  1143. }
  1144. }
  1145. msg.Control = &oob[0]
  1146. msg.SetControllen(len(oob))
  1147. }
  1148. msg.Iov = &iov
  1149. msg.Iovlen = 1
  1150. if n, err = sendmsg(fd, &msg, flags); err != nil {
  1151. return 0, err
  1152. }
  1153. if len(oob) > 0 && len(p) == 0 {
  1154. n = 0
  1155. }
  1156. return n, nil
  1157. }
  1158. // BindToDevice binds the socket associated with fd to device.
  1159. func BindToDevice(fd int, device string) (err error) {
  1160. return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
  1161. }
  1162. //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
  1163. func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
  1164. // The peek requests are machine-size oriented, so we wrap it
  1165. // to retrieve arbitrary-length data.
  1166. // The ptrace syscall differs from glibc's ptrace.
  1167. // Peeks returns the word in *data, not as the return value.
  1168. var buf [SizeofPtr]byte
  1169. // Leading edge. PEEKTEXT/PEEKDATA don't require aligned
  1170. // access (PEEKUSER warns that it might), but if we don't
  1171. // align our reads, we might straddle an unmapped page
  1172. // boundary and not get the bytes leading up to the page
  1173. // boundary.
  1174. n := 0
  1175. if addr%SizeofPtr != 0 {
  1176. err = ptrace(req, pid, addr-addr%SizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
  1177. if err != nil {
  1178. return 0, err
  1179. }
  1180. n += copy(out, buf[addr%SizeofPtr:])
  1181. out = out[n:]
  1182. }
  1183. // Remainder.
  1184. for len(out) > 0 {
  1185. // We use an internal buffer to guarantee alignment.
  1186. // It's not documented if this is necessary, but we're paranoid.
  1187. err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
  1188. if err != nil {
  1189. return n, err
  1190. }
  1191. copied := copy(out, buf[0:])
  1192. n += copied
  1193. out = out[copied:]
  1194. }
  1195. return n, nil
  1196. }
  1197. func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
  1198. return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
  1199. }
  1200. func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
  1201. return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
  1202. }
  1203. func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
  1204. return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
  1205. }
  1206. func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
  1207. // As for ptracePeek, we need to align our accesses to deal
  1208. // with the possibility of straddling an invalid page.
  1209. // Leading edge.
  1210. n := 0
  1211. if addr%SizeofPtr != 0 {
  1212. var buf [SizeofPtr]byte
  1213. err = ptrace(peekReq, pid, addr-addr%SizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
  1214. if err != nil {
  1215. return 0, err
  1216. }
  1217. n += copy(buf[addr%SizeofPtr:], data)
  1218. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  1219. err = ptrace(pokeReq, pid, addr-addr%SizeofPtr, word)
  1220. if err != nil {
  1221. return 0, err
  1222. }
  1223. data = data[n:]
  1224. }
  1225. // Interior.
  1226. for len(data) > SizeofPtr {
  1227. word := *((*uintptr)(unsafe.Pointer(&data[0])))
  1228. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  1229. if err != nil {
  1230. return n, err
  1231. }
  1232. n += SizeofPtr
  1233. data = data[SizeofPtr:]
  1234. }
  1235. // Trailing edge.
  1236. if len(data) > 0 {
  1237. var buf [SizeofPtr]byte
  1238. err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
  1239. if err != nil {
  1240. return n, err
  1241. }
  1242. copy(buf[0:], data)
  1243. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  1244. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  1245. if err != nil {
  1246. return n, err
  1247. }
  1248. n += len(data)
  1249. }
  1250. return n, nil
  1251. }
  1252. func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
  1253. return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
  1254. }
  1255. func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
  1256. return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
  1257. }
  1258. func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) {
  1259. return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data)
  1260. }
  1261. func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
  1262. return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
  1263. }
  1264. func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
  1265. return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
  1266. }
  1267. func PtraceSetOptions(pid int, options int) (err error) {
  1268. return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
  1269. }
  1270. func PtraceGetEventMsg(pid int) (msg uint, err error) {
  1271. var data _C_long
  1272. err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
  1273. msg = uint(data)
  1274. return
  1275. }
  1276. func PtraceCont(pid int, signal int) (err error) {
  1277. return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
  1278. }
  1279. func PtraceSyscall(pid int, signal int) (err error) {
  1280. return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
  1281. }
  1282. func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
  1283. func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
  1284. func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
  1285. //sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
  1286. func Reboot(cmd int) (err error) {
  1287. return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
  1288. }
  1289. func direntIno(buf []byte) (uint64, bool) {
  1290. return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
  1291. }
  1292. func direntReclen(buf []byte) (uint64, bool) {
  1293. return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
  1294. }
  1295. func direntNamlen(buf []byte) (uint64, bool) {
  1296. reclen, ok := direntReclen(buf)
  1297. if !ok {
  1298. return 0, false
  1299. }
  1300. return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
  1301. }
  1302. //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
  1303. func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
  1304. // Certain file systems get rather angry and EINVAL if you give
  1305. // them an empty string of data, rather than NULL.
  1306. if data == "" {
  1307. return mount(source, target, fstype, flags, nil)
  1308. }
  1309. datap, err := BytePtrFromString(data)
  1310. if err != nil {
  1311. return err
  1312. }
  1313. return mount(source, target, fstype, flags, datap)
  1314. }
  1315. func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
  1316. if raceenabled {
  1317. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1318. }
  1319. return sendfile(outfd, infd, offset, count)
  1320. }
  1321. // Sendto
  1322. // Recvfrom
  1323. // Socketpair
  1324. /*
  1325. * Direct access
  1326. */
  1327. //sys Acct(path string) (err error)
  1328. //sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
  1329. //sys Adjtimex(buf *Timex) (state int, err error)
  1330. //sys Capget(hdr *CapUserHeader, data *CapUserData) (err error)
  1331. //sys Capset(hdr *CapUserHeader, data *CapUserData) (err error)
  1332. //sys Chdir(path string) (err error)
  1333. //sys Chroot(path string) (err error)
  1334. //sys ClockGetres(clockid int32, res *Timespec) (err error)
  1335. //sys ClockGettime(clockid int32, time *Timespec) (err error)
  1336. //sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error)
  1337. //sys Close(fd int) (err error)
  1338. //sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
  1339. //sys DeleteModule(name string, flags int) (err error)
  1340. //sys Dup(oldfd int) (fd int, err error)
  1341. //sys Dup3(oldfd int, newfd int, flags int) (err error)
  1342. //sysnb EpollCreate1(flag int) (fd int, err error)
  1343. //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
  1344. //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
  1345. //sys Exit(code int) = SYS_EXIT_GROUP
  1346. //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
  1347. //sys Fchdir(fd int) (err error)
  1348. //sys Fchmod(fd int, mode uint32) (err error)
  1349. //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
  1350. //sys fcntl(fd int, cmd int, arg int) (val int, err error)
  1351. //sys Fdatasync(fd int) (err error)
  1352. //sys Fgetxattr(fd int, attr string, dest []byte) (sz int, err error)
  1353. //sys FinitModule(fd int, params string, flags int) (err error)
  1354. //sys Flistxattr(fd int, dest []byte) (sz int, err error)
  1355. //sys Flock(fd int, how int) (err error)
  1356. //sys Fremovexattr(fd int, attr string) (err error)
  1357. //sys Fsetxattr(fd int, attr string, dest []byte, flags int) (err error)
  1358. //sys Fsync(fd int) (err error)
  1359. //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
  1360. //sysnb Getpgid(pid int) (pgid int, err error)
  1361. func Getpgrp() (pid int) {
  1362. pid, _ = Getpgid(0)
  1363. return
  1364. }
  1365. //sysnb Getpid() (pid int)
  1366. //sysnb Getppid() (ppid int)
  1367. //sys Getpriority(which int, who int) (prio int, err error)
  1368. //sys Getrandom(buf []byte, flags int) (n int, err error)
  1369. //sysnb Getrusage(who int, rusage *Rusage) (err error)
  1370. //sysnb Getsid(pid int) (sid int, err error)
  1371. //sysnb Gettid() (tid int)
  1372. //sys Getxattr(path string, attr string, dest []byte) (sz int, err error)
  1373. //sys InitModule(moduleImage []byte, params string) (err error)
  1374. //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
  1375. //sysnb InotifyInit1(flags int) (fd int, err error)
  1376. //sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
  1377. //sysnb Kill(pid int, sig syscall.Signal) (err error)
  1378. //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
  1379. //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
  1380. //sys Listxattr(path string, dest []byte) (sz int, err error)
  1381. //sys Llistxattr(path string, dest []byte) (sz int, err error)
  1382. //sys Lremovexattr(path string, attr string) (err error)
  1383. //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error)
  1384. //sys MemfdCreate(name string, flags int) (fd int, err error)
  1385. //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
  1386. //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
  1387. //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
  1388. //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error)
  1389. //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
  1390. //sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64
  1391. //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
  1392. //sys Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) = SYS_PSELECT6
  1393. //sys read(fd int, p []byte) (n int, err error)
  1394. //sys Removexattr(path string, attr string) (err error)
  1395. //sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error)
  1396. //sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
  1397. //sys Setdomainname(p []byte) (err error)
  1398. //sys Sethostname(p []byte) (err error)
  1399. //sysnb Setpgid(pid int, pgid int) (err error)
  1400. //sysnb Setsid() (pid int, err error)
  1401. //sysnb Settimeofday(tv *Timeval) (err error)
  1402. //sys Setns(fd int, nstype int) (err error)
  1403. // issue 1435.
  1404. // On linux Setuid and Setgid only affects the current thread, not the process.
  1405. // This does not match what most callers expect so we must return an error
  1406. // here rather than letting the caller think that the call succeeded.
  1407. func Setuid(uid int) (err error) {
  1408. return EOPNOTSUPP
  1409. }
  1410. func Setgid(uid int) (err error) {
  1411. return EOPNOTSUPP
  1412. }
  1413. func Signalfd(fd int, sigmask *Sigset_t, flags int) (newfd int, err error) {
  1414. return signalfd(fd, sigmask, _C__NSIG/8, flags)
  1415. }
  1416. //sys Setpriority(which int, who int, prio int) (err error)
  1417. //sys Setxattr(path string, attr string, data []byte, flags int) (err error)
  1418. //sys signalfd(fd int, sigmask *Sigset_t, maskSize uintptr, flags int) (newfd int, err error) = SYS_SIGNALFD4
  1419. //sys Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error)
  1420. //sys Sync()
  1421. //sys Syncfs(fd int) (err error)
  1422. //sysnb Sysinfo(info *Sysinfo_t) (err error)
  1423. //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
  1424. //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
  1425. //sysnb Times(tms *Tms) (ticks uintptr, err error)
  1426. //sysnb Umask(mask int) (oldmask int)
  1427. //sysnb Uname(buf *Utsname) (err error)
  1428. //sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
  1429. //sys Unshare(flags int) (err error)
  1430. //sys write(fd int, p []byte) (n int, err error)
  1431. //sys exitThread(code int) (err error) = SYS_EXIT
  1432. //sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
  1433. //sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
  1434. // mmap varies by architecture; see syscall_linux_*.go.
  1435. //sys munmap(addr uintptr, length uintptr) (err error)
  1436. var mapper = &mmapper{
  1437. active: make(map[*byte][]byte),
  1438. mmap: mmap,
  1439. munmap: munmap,
  1440. }
  1441. func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
  1442. return mapper.Mmap(fd, offset, length, prot, flags)
  1443. }
  1444. func Munmap(b []byte) (err error) {
  1445. return mapper.Munmap(b)
  1446. }
  1447. //sys Madvise(b []byte, advice int) (err error)
  1448. //sys Mprotect(b []byte, prot int) (err error)
  1449. //sys Mlock(b []byte) (err error)
  1450. //sys Mlockall(flags int) (err error)
  1451. //sys Msync(b []byte, flags int) (err error)
  1452. //sys Munlock(b []byte) (err error)
  1453. //sys Munlockall() (err error)
  1454. // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
  1455. // using the specified flags.
  1456. func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
  1457. var p unsafe.Pointer
  1458. if len(iovs) > 0 {
  1459. p = unsafe.Pointer(&iovs[0])
  1460. }
  1461. n, _, errno := Syscall6(SYS_VMSPLICE, uintptr(fd), uintptr(p), uintptr(len(iovs)), uintptr(flags), 0, 0)
  1462. if errno != 0 {
  1463. return 0, syscall.Errno(errno)
  1464. }
  1465. return int(n), nil
  1466. }
  1467. //sys faccessat(dirfd int, path string, mode uint32) (err error)
  1468. func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
  1469. if flags & ^(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
  1470. return EINVAL
  1471. }
  1472. // The Linux kernel faccessat system call does not take any flags.
  1473. // The glibc faccessat implements the flags itself; see
  1474. // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/faccessat.c;hb=HEAD
  1475. // Because people naturally expect syscall.Faccessat to act
  1476. // like C faccessat, we do the same.
  1477. if flags == 0 {
  1478. return faccessat(dirfd, path, mode)
  1479. }
  1480. var st Stat_t
  1481. if err := Fstatat(dirfd, path, &st, flags&AT_SYMLINK_NOFOLLOW); err != nil {
  1482. return err
  1483. }
  1484. mode &= 7
  1485. if mode == 0 {
  1486. return nil
  1487. }
  1488. var uid int
  1489. if flags&AT_EACCESS != 0 {
  1490. uid = Geteuid()
  1491. } else {
  1492. uid = Getuid()
  1493. }
  1494. if uid == 0 {
  1495. if mode&1 == 0 {
  1496. // Root can read and write any file.
  1497. return nil
  1498. }
  1499. if st.Mode&0111 != 0 {
  1500. // Root can execute any file that anybody can execute.
  1501. return nil
  1502. }
  1503. return EACCES
  1504. }
  1505. var fmode uint32
  1506. if uint32(uid) == st.Uid {
  1507. fmode = (st.Mode >> 6) & 7
  1508. } else {
  1509. var gid int
  1510. if flags&AT_EACCESS != 0 {
  1511. gid = Getegid()
  1512. } else {
  1513. gid = Getgid()
  1514. }
  1515. if uint32(gid) == st.Gid {
  1516. fmode = (st.Mode >> 3) & 7
  1517. } else {
  1518. fmode = st.Mode & 7
  1519. }
  1520. }
  1521. if fmode&mode == mode {
  1522. return nil
  1523. }
  1524. return EACCES
  1525. }
  1526. //sys nameToHandleAt(dirFD int, pathname string, fh *fileHandle, mountID *_C_int, flags int) (err error) = SYS_NAME_TO_HANDLE_AT
  1527. //sys openByHandleAt(mountFD int, fh *fileHandle, flags int) (fd int, err error) = SYS_OPEN_BY_HANDLE_AT
  1528. // fileHandle is the argument to nameToHandleAt and openByHandleAt. We
  1529. // originally tried to generate it via unix/linux/types.go with "type
  1530. // fileHandle C.struct_file_handle" but that generated empty structs
  1531. // for mips64 and mips64le. Instead, hard code it for now (it's the
  1532. // same everywhere else) until the mips64 generator issue is fixed.
  1533. type fileHandle struct {
  1534. Bytes uint32
  1535. Type int32
  1536. }
  1537. // FileHandle represents the C struct file_handle used by
  1538. // name_to_handle_at (see NameToHandleAt) and open_by_handle_at (see
  1539. // OpenByHandleAt).
  1540. type FileHandle struct {
  1541. *fileHandle
  1542. }
  1543. // NewFileHandle constructs a FileHandle.
  1544. func NewFileHandle(handleType int32, handle []byte) FileHandle {
  1545. const hdrSize = unsafe.Sizeof(fileHandle{})
  1546. buf := make([]byte, hdrSize+uintptr(len(handle)))
  1547. copy(buf[hdrSize:], handle)
  1548. fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
  1549. fh.Type = handleType
  1550. fh.Bytes = uint32(len(handle))
  1551. return FileHandle{fh}
  1552. }
  1553. func (fh *FileHandle) Size() int { return int(fh.fileHandle.Bytes) }
  1554. func (fh *FileHandle) Type() int32 { return fh.fileHandle.Type }
  1555. func (fh *FileHandle) Bytes() []byte {
  1556. n := fh.Size()
  1557. if n == 0 {
  1558. return nil
  1559. }
  1560. return (*[1 << 30]byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type)) + 4))[:n:n]
  1561. }
  1562. // NameToHandleAt wraps the name_to_handle_at system call; it obtains
  1563. // a handle for a path name.
  1564. func NameToHandleAt(dirfd int, path string, flags int) (handle FileHandle, mountID int, err error) {
  1565. var mid _C_int
  1566. // Try first with a small buffer, assuming the handle will
  1567. // only be 32 bytes.
  1568. size := uint32(32 + unsafe.Sizeof(fileHandle{}))
  1569. didResize := false
  1570. for {
  1571. buf := make([]byte, size)
  1572. fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
  1573. fh.Bytes = size - uint32(unsafe.Sizeof(fileHandle{}))
  1574. err = nameToHandleAt(dirfd, path, fh, &mid, flags)
  1575. if err == EOVERFLOW {
  1576. if didResize {
  1577. // We shouldn't need to resize more than once
  1578. return
  1579. }
  1580. didResize = true
  1581. size = fh.Bytes + uint32(unsafe.Sizeof(fileHandle{}))
  1582. continue
  1583. }
  1584. if err != nil {
  1585. return
  1586. }
  1587. return FileHandle{fh}, int(mid), nil
  1588. }
  1589. }
  1590. // OpenByHandleAt wraps the open_by_handle_at system call; it opens a
  1591. // file via a handle as previously returned by NameToHandleAt.
  1592. func OpenByHandleAt(mountFD int, handle FileHandle, flags int) (fd int, err error) {
  1593. return openByHandleAt(mountFD, handle.fileHandle, flags)
  1594. }
  1595. /*
  1596. * Unimplemented
  1597. */
  1598. // AfsSyscall
  1599. // Alarm
  1600. // ArchPrctl
  1601. // Brk
  1602. // ClockNanosleep
  1603. // ClockSettime
  1604. // Clone
  1605. // EpollCtlOld
  1606. // EpollPwait
  1607. // EpollWaitOld
  1608. // Execve
  1609. // Fork
  1610. // Futex
  1611. // GetKernelSyms
  1612. // GetMempolicy
  1613. // GetRobustList
  1614. // GetThreadArea
  1615. // Getitimer
  1616. // Getpmsg
  1617. // IoCancel
  1618. // IoDestroy
  1619. // IoGetevents
  1620. // IoSetup
  1621. // IoSubmit
  1622. // IoprioGet
  1623. // IoprioSet
  1624. // KexecLoad
  1625. // LookupDcookie
  1626. // Mbind
  1627. // MigratePages
  1628. // Mincore
  1629. // ModifyLdt
  1630. // Mount
  1631. // MovePages
  1632. // MqGetsetattr
  1633. // MqNotify
  1634. // MqOpen
  1635. // MqTimedreceive
  1636. // MqTimedsend
  1637. // MqUnlink
  1638. // Mremap
  1639. // Msgctl
  1640. // Msgget
  1641. // Msgrcv
  1642. // Msgsnd
  1643. // Nfsservctl
  1644. // Personality
  1645. // Pselect6
  1646. // Ptrace
  1647. // Putpmsg
  1648. // Quotactl
  1649. // Readahead
  1650. // Readv
  1651. // RemapFilePages
  1652. // RestartSyscall
  1653. // RtSigaction
  1654. // RtSigpending
  1655. // RtSigprocmask
  1656. // RtSigqueueinfo
  1657. // RtSigreturn
  1658. // RtSigsuspend
  1659. // RtSigtimedwait
  1660. // SchedGetPriorityMax
  1661. // SchedGetPriorityMin
  1662. // SchedGetparam
  1663. // SchedGetscheduler
  1664. // SchedRrGetInterval
  1665. // SchedSetparam
  1666. // SchedYield
  1667. // Security
  1668. // Semctl
  1669. // Semget
  1670. // Semop
  1671. // Semtimedop
  1672. // SetMempolicy
  1673. // SetRobustList
  1674. // SetThreadArea
  1675. // SetTidAddress
  1676. // Shmat
  1677. // Shmctl
  1678. // Shmdt
  1679. // Shmget
  1680. // Sigaltstack
  1681. // Swapoff
  1682. // Swapon
  1683. // Sysfs
  1684. // TimerCreate
  1685. // TimerDelete
  1686. // TimerGetoverrun
  1687. // TimerGettime
  1688. // TimerSettime
  1689. // Timerfd
  1690. // Tkill (obsolete)
  1691. // Tuxcall
  1692. // Umount2
  1693. // Uselib
  1694. // Utimensat
  1695. // Vfork
  1696. // Vhangup
  1697. // Vserver
  1698. // Waitid
  1699. // _Sysctl
上海开阖软件有限公司 沪ICP备12045867号-1