syscall_linux.go 69 KB

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