syscall_unix_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // Copyright 2013 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. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
  5. package syscall_test
  6. import (
  7. "flag"
  8. "fmt"
  9. "internal/testenv"
  10. "io"
  11. "net"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "runtime"
  16. "strconv"
  17. "syscall"
  18. "testing"
  19. "time"
  20. )
  21. // Tests that below functions, structures and constants are consistent
  22. // on all Unix-like systems.
  23. func _() {
  24. // program scheduling priority functions and constants
  25. var (
  26. _ func(int, int, int) error = syscall.Setpriority
  27. _ func(int, int) (int, error) = syscall.Getpriority
  28. )
  29. const (
  30. _ int = syscall.PRIO_USER
  31. _ int = syscall.PRIO_PROCESS
  32. _ int = syscall.PRIO_PGRP
  33. )
  34. // termios constants
  35. const (
  36. _ int = syscall.TCIFLUSH
  37. _ int = syscall.TCIOFLUSH
  38. _ int = syscall.TCOFLUSH
  39. )
  40. // fcntl file locking structure and constants
  41. var (
  42. _ = syscall.Flock_t{
  43. // Comment out the Type and Whence tests because
  44. // on the Hurd they are int32, not int16.
  45. // Type: int16(0),
  46. // Whence: int16(0),
  47. Start: int64(0),
  48. Len: int64(0),
  49. Pid: int32(0),
  50. }
  51. )
  52. const (
  53. _ = syscall.F_GETLK
  54. _ = syscall.F_SETLK
  55. _ = syscall.F_SETLKW
  56. )
  57. }
  58. // TestFcntlFlock tests whether the file locking structure matches
  59. // the calling convention of each kernel.
  60. // On some Linux systems, glibc uses another set of values for the
  61. // commands and translates them to the correct value that the kernel
  62. // expects just before the actual fcntl syscall. As Go uses raw
  63. // syscalls directly, it must use the real value, not the glibc value.
  64. // Thus this test also verifies that the Flock_t structure can be
  65. // roundtripped with F_SETLK and F_GETLK.
  66. func TestFcntlFlock(t *testing.T) {
  67. if runtime.GOOS == "ios" {
  68. t.Skip("skipping; no child processes allowed on iOS")
  69. }
  70. flock := syscall.Flock_t{
  71. Type: syscall.F_WRLCK,
  72. Start: 31415, Len: 271828, Whence: 1,
  73. }
  74. if os.Getenv("GO_WANT_HELPER_PROCESS") == "" {
  75. // parent
  76. tempDir := t.TempDir()
  77. name := filepath.Join(tempDir, "TestFcntlFlock")
  78. fd, err := syscall.Open(name, syscall.O_CREAT|syscall.O_RDWR|syscall.O_CLOEXEC, 0)
  79. if err != nil {
  80. t.Fatalf("Open failed: %v", err)
  81. }
  82. // f takes ownership of fd, and will close it.
  83. //
  84. // N.B. This defer is also necessary to keep f alive
  85. // while we use its fd, preventing its finalizer from
  86. // executing.
  87. f := os.NewFile(uintptr(fd), name)
  88. defer f.Close()
  89. if err := syscall.Ftruncate(int(f.Fd()), 1<<20); err != nil {
  90. t.Fatalf("Ftruncate(1<<20) failed: %v", err)
  91. }
  92. if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &flock); err != nil {
  93. t.Fatalf("FcntlFlock(F_SETLK) failed: %v", err)
  94. }
  95. cmd := exec.Command(os.Args[0], "-test.run=^TestFcntlFlock$")
  96. cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
  97. cmd.ExtraFiles = []*os.File{f}
  98. out, err := cmd.CombinedOutput()
  99. if len(out) > 0 || err != nil {
  100. t.Fatalf("child process: %q, %v", out, err)
  101. }
  102. } else {
  103. // child
  104. got := flock
  105. // make sure the child lock is conflicting with the parent lock
  106. got.Start--
  107. got.Len++
  108. if err := syscall.FcntlFlock(3, syscall.F_GETLK, &got); err != nil {
  109. t.Fatalf("FcntlFlock(F_GETLK) failed: %v", err)
  110. }
  111. flock.Pid = int32(syscall.Getppid())
  112. // Linux kernel always set Whence to 0
  113. flock.Whence = 0
  114. if got.Type == flock.Type && got.Start == flock.Start && got.Len == flock.Len && got.Pid == flock.Pid && got.Whence == flock.Whence {
  115. os.Exit(0)
  116. }
  117. t.Fatalf("FcntlFlock got %v, want %v", got, flock)
  118. }
  119. }
  120. // TestPassFD tests passing a file descriptor over a Unix socket.
  121. //
  122. // This test involved both a parent and child process. The parent
  123. // process is invoked as a normal test, with "go test", which then
  124. // runs the child process by running the current test binary with args
  125. // "-test.run=^TestPassFD$" and an environment variable used to signal
  126. // that the test should become the child process instead.
  127. func TestPassFD(t *testing.T) {
  128. testenv.MustHaveExec(t)
  129. if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  130. passFDChild()
  131. return
  132. }
  133. if runtime.GOOS == "aix" {
  134. // Unix network isn't properly working on AIX 7.2 with Technical Level < 2
  135. out, err := exec.Command("oslevel", "-s").Output()
  136. if err != nil {
  137. t.Skipf("skipping on AIX because oslevel -s failed: %v", err)
  138. }
  139. if len(out) < len("7200-XX-ZZ-YYMM") { // AIX 7.2, Tech Level XX, Service Pack ZZ, date YYMM
  140. t.Skip("skipping on AIX because oslevel -s hasn't the right length")
  141. }
  142. aixVer := string(out[:4])
  143. tl, err := strconv.Atoi(string(out[5:7]))
  144. if err != nil {
  145. t.Skipf("skipping on AIX because oslevel -s output cannot be parsed: %v", err)
  146. }
  147. if aixVer < "7200" || (aixVer == "7200" && tl < 2) {
  148. t.Skip("skipped on AIX versions previous to 7.2 TL 2")
  149. }
  150. }
  151. tempDir := t.TempDir()
  152. fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM, 0)
  153. if err != nil {
  154. t.Fatalf("Socketpair: %v", err)
  155. }
  156. writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
  157. readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
  158. defer writeFile.Close()
  159. defer readFile.Close()
  160. cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
  161. cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
  162. cmd.ExtraFiles = []*os.File{writeFile}
  163. out, err := cmd.CombinedOutput()
  164. if len(out) > 0 || err != nil {
  165. t.Fatalf("child process: %q, %v", out, err)
  166. }
  167. c, err := net.FileConn(readFile)
  168. if err != nil {
  169. t.Fatalf("FileConn: %v", err)
  170. }
  171. defer c.Close()
  172. uc, ok := c.(*net.UnixConn)
  173. if !ok {
  174. t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
  175. }
  176. buf := make([]byte, 32) // expect 1 byte
  177. oob := make([]byte, 32) // expect 24 bytes
  178. closeUnix := time.AfterFunc(5*time.Second, func() {
  179. t.Logf("timeout reading from unix socket")
  180. uc.Close()
  181. })
  182. _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
  183. if err != nil {
  184. t.Fatalf("ReadMsgUnix: %v", err)
  185. }
  186. closeUnix.Stop()
  187. scms, err := syscall.ParseSocketControlMessage(oob[:oobn])
  188. if err != nil {
  189. t.Fatalf("ParseSocketControlMessage: %v", err)
  190. }
  191. if len(scms) != 1 {
  192. t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
  193. }
  194. scm := scms[0]
  195. gotFds, err := syscall.ParseUnixRights(&scm)
  196. if err != nil {
  197. t.Fatalf("syscall.ParseUnixRights: %v", err)
  198. }
  199. if len(gotFds) != 1 {
  200. t.Fatalf("wanted 1 fd; got %#v", gotFds)
  201. }
  202. f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
  203. defer f.Close()
  204. got, err := io.ReadAll(f)
  205. want := "Hello from child process!\n"
  206. if string(got) != want {
  207. t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
  208. }
  209. }
  210. // passFDChild is the child process used by TestPassFD.
  211. func passFDChild() {
  212. defer os.Exit(0)
  213. // Look for our fd. It should be fd 3, but we work around an fd leak
  214. // bug here (https://golang.org/issue/2603) to let it be elsewhere.
  215. var uc *net.UnixConn
  216. for fd := uintptr(3); fd <= 10; fd++ {
  217. f := os.NewFile(fd, "unix-conn")
  218. var ok bool
  219. netc, _ := net.FileConn(f)
  220. uc, ok = netc.(*net.UnixConn)
  221. if ok {
  222. break
  223. }
  224. }
  225. if uc == nil {
  226. fmt.Println("failed to find unix fd")
  227. return
  228. }
  229. // Make a file f to send to our parent process on uc.
  230. // We make it in tempDir, which our parent will clean up.
  231. flag.Parse()
  232. tempDir := flag.Arg(0)
  233. f, err := os.CreateTemp(tempDir, "")
  234. if err != nil {
  235. fmt.Printf("TempFile: %v", err)
  236. return
  237. }
  238. // N.B. This defer is also necessary to keep f alive
  239. // while we use its fd, preventing its finalizer from
  240. // executing.
  241. defer f.Close()
  242. f.Write([]byte("Hello from child process!\n"))
  243. f.Seek(0, io.SeekStart)
  244. rights := syscall.UnixRights(int(f.Fd()))
  245. dummyByte := []byte("x")
  246. n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
  247. if err != nil {
  248. fmt.Printf("WriteMsgUnix: %v", err)
  249. return
  250. }
  251. if n != 1 || oobn != len(rights) {
  252. fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
  253. return
  254. }
  255. }
  256. // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
  257. // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
  258. func TestUnixRightsRoundtrip(t *testing.T) {
  259. testCases := [...][][]int{
  260. {{42}},
  261. {{1, 2}},
  262. {{3, 4, 5}},
  263. {{}},
  264. {{1, 2}, {3, 4, 5}, {}, {7}},
  265. }
  266. for _, testCase := range testCases {
  267. b := []byte{}
  268. var n int
  269. for _, fds := range testCase {
  270. // Last assignment to n wins
  271. n = len(b) + syscall.CmsgLen(4*len(fds))
  272. b = append(b, syscall.UnixRights(fds...)...)
  273. }
  274. // Truncate b
  275. b = b[:n]
  276. scms, err := syscall.ParseSocketControlMessage(b)
  277. if err != nil {
  278. t.Fatalf("ParseSocketControlMessage: %v", err)
  279. }
  280. if len(scms) != len(testCase) {
  281. t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
  282. }
  283. for i, scm := range scms {
  284. gotFds, err := syscall.ParseUnixRights(&scm)
  285. if err != nil {
  286. t.Fatalf("ParseUnixRights: %v", err)
  287. }
  288. wantFds := testCase[i]
  289. if len(gotFds) != len(wantFds) {
  290. t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
  291. }
  292. for j, fd := range gotFds {
  293. if fd != wantFds[j] {
  294. t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
  295. }
  296. }
  297. }
  298. }
  299. }
  300. func TestSeekFailure(t *testing.T) {
  301. _, err := syscall.Seek(-1, 0, io.SeekStart)
  302. if err == nil {
  303. t.Fatalf("Seek(-1, 0, 0) did not fail")
  304. }
  305. str := err.Error() // used to crash on Linux
  306. t.Logf("Seek: %v", str)
  307. if str == "" {
  308. t.Fatalf("Seek(-1, 0, 0) return error with empty message")
  309. }
  310. }
  311. func TestSetsockoptString(t *testing.T) {
  312. // should not panic on empty string, see issue #31277
  313. err := syscall.SetsockoptString(-1, 0, 0, "")
  314. if err == nil {
  315. t.Fatalf("SetsockoptString: did not fail")
  316. }
  317. }
  318. func TestENFILETemporary(t *testing.T) {
  319. if !syscall.ENFILE.Temporary() {
  320. t.Error("ENFILE is not treated as a temporary error")
  321. }
  322. }