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 74KB

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