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.

syscall_linux.go 73KB

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