syscall_unix_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. // +build darwin dragonfly freebsd linux netbsd openbsd solaris
  5. package unix_test
  6. import (
  7. "flag"
  8. "fmt"
  9. "io/ioutil"
  10. "net"
  11. "os"
  12. "os/exec"
  13. "path/filepath"
  14. "runtime"
  15. "testing"
  16. "time"
  17. "golang.org/x/sys/unix"
  18. )
  19. // Tests that below functions, structures and constants are consistent
  20. // on all Unix-like systems.
  21. func _() {
  22. // program scheduling priority functions and constants
  23. var (
  24. _ func(int, int, int) error = unix.Setpriority
  25. _ func(int, int) (int, error) = unix.Getpriority
  26. )
  27. const (
  28. _ int = unix.PRIO_USER
  29. _ int = unix.PRIO_PROCESS
  30. _ int = unix.PRIO_PGRP
  31. )
  32. // termios constants
  33. const (
  34. _ int = unix.TCIFLUSH
  35. _ int = unix.TCIOFLUSH
  36. _ int = unix.TCOFLUSH
  37. )
  38. // fcntl file locking structure and constants
  39. var (
  40. _ = unix.Flock_t{
  41. Type: int16(0),
  42. Whence: int16(0),
  43. Start: int64(0),
  44. Len: int64(0),
  45. Pid: int32(0),
  46. }
  47. )
  48. const (
  49. _ = unix.F_GETLK
  50. _ = unix.F_SETLK
  51. _ = unix.F_SETLKW
  52. )
  53. }
  54. // TestFcntlFlock tests whether the file locking structure matches
  55. // the calling convention of each kernel.
  56. func TestFcntlFlock(t *testing.T) {
  57. name := filepath.Join(os.TempDir(), "TestFcntlFlock")
  58. fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
  59. if err != nil {
  60. t.Fatalf("Open failed: %v", err)
  61. }
  62. defer unix.Unlink(name)
  63. defer unix.Close(fd)
  64. flock := unix.Flock_t{
  65. Type: unix.F_RDLCK,
  66. Start: 0, Len: 0, Whence: 1,
  67. }
  68. if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
  69. t.Fatalf("FcntlFlock failed: %v", err)
  70. }
  71. }
  72. // TestPassFD tests passing a file descriptor over a Unix socket.
  73. //
  74. // This test involved both a parent and child process. The parent
  75. // process is invoked as a normal test, with "go test", which then
  76. // runs the child process by running the current test binary with args
  77. // "-test.run=^TestPassFD$" and an environment variable used to signal
  78. // that the test should become the child process instead.
  79. func TestPassFD(t *testing.T) {
  80. if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  81. passFDChild()
  82. return
  83. }
  84. tempDir, err := ioutil.TempDir("", "TestPassFD")
  85. if err != nil {
  86. t.Fatal(err)
  87. }
  88. defer os.RemoveAll(tempDir)
  89. fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
  90. if err != nil {
  91. t.Fatalf("Socketpair: %v", err)
  92. }
  93. defer unix.Close(fds[0])
  94. defer unix.Close(fds[1])
  95. writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
  96. readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
  97. defer writeFile.Close()
  98. defer readFile.Close()
  99. cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
  100. cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
  101. if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
  102. cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
  103. }
  104. cmd.ExtraFiles = []*os.File{writeFile}
  105. out, err := cmd.CombinedOutput()
  106. if len(out) > 0 || err != nil {
  107. t.Fatalf("child process: %q, %v", out, err)
  108. }
  109. c, err := net.FileConn(readFile)
  110. if err != nil {
  111. t.Fatalf("FileConn: %v", err)
  112. }
  113. defer c.Close()
  114. uc, ok := c.(*net.UnixConn)
  115. if !ok {
  116. t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
  117. }
  118. buf := make([]byte, 32) // expect 1 byte
  119. oob := make([]byte, 32) // expect 24 bytes
  120. closeUnix := time.AfterFunc(5*time.Second, func() {
  121. t.Logf("timeout reading from unix socket")
  122. uc.Close()
  123. })
  124. _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
  125. if err != nil {
  126. t.Fatalf("ReadMsgUnix: %v", err)
  127. }
  128. closeUnix.Stop()
  129. scms, err := unix.ParseSocketControlMessage(oob[:oobn])
  130. if err != nil {
  131. t.Fatalf("ParseSocketControlMessage: %v", err)
  132. }
  133. if len(scms) != 1 {
  134. t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
  135. }
  136. scm := scms[0]
  137. gotFds, err := unix.ParseUnixRights(&scm)
  138. if err != nil {
  139. t.Fatalf("unix.ParseUnixRights: %v", err)
  140. }
  141. if len(gotFds) != 1 {
  142. t.Fatalf("wanted 1 fd; got %#v", gotFds)
  143. }
  144. f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
  145. defer f.Close()
  146. got, err := ioutil.ReadAll(f)
  147. want := "Hello from child process!\n"
  148. if string(got) != want {
  149. t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
  150. }
  151. }
  152. // passFDChild is the child process used by TestPassFD.
  153. func passFDChild() {
  154. defer os.Exit(0)
  155. // Look for our fd. It should be fd 3, but we work around an fd leak
  156. // bug here (http://golang.org/issue/2603) to let it be elsewhere.
  157. var uc *net.UnixConn
  158. for fd := uintptr(3); fd <= 10; fd++ {
  159. f := os.NewFile(fd, "unix-conn")
  160. var ok bool
  161. netc, _ := net.FileConn(f)
  162. uc, ok = netc.(*net.UnixConn)
  163. if ok {
  164. break
  165. }
  166. }
  167. if uc == nil {
  168. fmt.Println("failed to find unix fd")
  169. return
  170. }
  171. // Make a file f to send to our parent process on uc.
  172. // We make it in tempDir, which our parent will clean up.
  173. flag.Parse()
  174. tempDir := flag.Arg(0)
  175. f, err := ioutil.TempFile(tempDir, "")
  176. if err != nil {
  177. fmt.Printf("TempFile: %v", err)
  178. return
  179. }
  180. f.Write([]byte("Hello from child process!\n"))
  181. f.Seek(0, 0)
  182. rights := unix.UnixRights(int(f.Fd()))
  183. dummyByte := []byte("x")
  184. n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
  185. if err != nil {
  186. fmt.Printf("WriteMsgUnix: %v", err)
  187. return
  188. }
  189. if n != 1 || oobn != len(rights) {
  190. fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
  191. return
  192. }
  193. }
  194. // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
  195. // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
  196. func TestUnixRightsRoundtrip(t *testing.T) {
  197. testCases := [...][][]int{
  198. {{42}},
  199. {{1, 2}},
  200. {{3, 4, 5}},
  201. {{}},
  202. {{1, 2}, {3, 4, 5}, {}, {7}},
  203. }
  204. for _, testCase := range testCases {
  205. b := []byte{}
  206. var n int
  207. for _, fds := range testCase {
  208. // Last assignment to n wins
  209. n = len(b) + unix.CmsgLen(4*len(fds))
  210. b = append(b, unix.UnixRights(fds...)...)
  211. }
  212. // Truncate b
  213. b = b[:n]
  214. scms, err := unix.ParseSocketControlMessage(b)
  215. if err != nil {
  216. t.Fatalf("ParseSocketControlMessage: %v", err)
  217. }
  218. if len(scms) != len(testCase) {
  219. t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
  220. }
  221. for i, scm := range scms {
  222. gotFds, err := unix.ParseUnixRights(&scm)
  223. if err != nil {
  224. t.Fatalf("ParseUnixRights: %v", err)
  225. }
  226. wantFds := testCase[i]
  227. if len(gotFds) != len(wantFds) {
  228. t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
  229. }
  230. for j, fd := range gotFds {
  231. if fd != wantFds[j] {
  232. t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
  233. }
  234. }
  235. }
  236. }
  237. }
  238. func TestRlimit(t *testing.T) {
  239. var rlimit, zero unix.Rlimit
  240. err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
  241. if err != nil {
  242. t.Fatalf("Getrlimit: save failed: %v", err)
  243. }
  244. if zero == rlimit {
  245. t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
  246. }
  247. set := rlimit
  248. set.Cur = set.Max - 1
  249. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
  250. if err != nil {
  251. t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
  252. }
  253. var get unix.Rlimit
  254. err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
  255. if err != nil {
  256. t.Fatalf("Getrlimit: get failed: %v", err)
  257. }
  258. set = rlimit
  259. set.Cur = set.Max - 1
  260. if set != get {
  261. // Seems like Darwin requires some privilege to
  262. // increase the soft limit of rlimit sandbox, though
  263. // Setrlimit never reports an error.
  264. switch runtime.GOOS {
  265. case "darwin":
  266. default:
  267. t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
  268. }
  269. }
  270. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
  271. if err != nil {
  272. t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
  273. }
  274. }
  275. func TestSeekFailure(t *testing.T) {
  276. _, err := unix.Seek(-1, 0, 0)
  277. if err == nil {
  278. t.Fatalf("Seek(-1, 0, 0) did not fail")
  279. }
  280. str := err.Error() // used to crash on Linux
  281. t.Logf("Seek: %v", str)
  282. if str == "" {
  283. t.Fatalf("Seek(-1, 0, 0) return error with empty message")
  284. }
  285. }
  286. func TestDup(t *testing.T) {
  287. file, err := ioutil.TempFile("", "TestDup")
  288. if err != nil {
  289. t.Fatalf("Tempfile failed: %v", err)
  290. }
  291. defer os.Remove(file.Name())
  292. defer file.Close()
  293. f := int(file.Fd())
  294. newFd, err := unix.Dup(f)
  295. if err != nil {
  296. t.Fatalf("Dup: %v", err)
  297. }
  298. err = unix.Dup2(newFd, newFd+1)
  299. if err != nil {
  300. t.Fatalf("Dup2: %v", err)
  301. }
  302. b1 := []byte("Test123")
  303. b2 := make([]byte, 7)
  304. _, err = unix.Write(newFd+1, b1)
  305. if err != nil {
  306. t.Fatalf("Write to dup2 fd failed: %v", err)
  307. }
  308. _, err = unix.Seek(f, 0, 0)
  309. if err != nil {
  310. t.Fatalf("Seek failed: %v", err)
  311. }
  312. _, err = unix.Read(f, b2)
  313. if err != nil {
  314. t.Fatalf("Read back failed: %v", err)
  315. }
  316. if string(b1) != string(b2) {
  317. t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
  318. }
  319. }
  320. func TestPoll(t *testing.T) {
  321. f, cleanup := mktmpfifo(t)
  322. defer cleanup()
  323. const timeout = 100
  324. ok := make(chan bool, 1)
  325. go func() {
  326. select {
  327. case <-time.After(10 * timeout * time.Millisecond):
  328. t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
  329. case <-ok:
  330. }
  331. }()
  332. fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
  333. n, err := unix.Poll(fds, timeout)
  334. ok <- true
  335. if err != nil {
  336. t.Errorf("Poll: unexpected error: %v", err)
  337. return
  338. }
  339. if n != 0 {
  340. t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
  341. return
  342. }
  343. }
  344. func TestGetwd(t *testing.T) {
  345. fd, err := os.Open(".")
  346. if err != nil {
  347. t.Fatalf("Open .: %s", err)
  348. }
  349. // These are chosen carefully not to be symlinks on a Mac
  350. // (unlike, say, /var, /etc)
  351. dirs := []string{"/", "/usr/bin"}
  352. if runtime.GOOS == "darwin" {
  353. switch runtime.GOARCH {
  354. case "arm", "arm64":
  355. d1, err := ioutil.TempDir("", "d1")
  356. if err != nil {
  357. t.Fatalf("TempDir: %v", err)
  358. }
  359. d2, err := ioutil.TempDir("", "d2")
  360. if err != nil {
  361. t.Fatalf("TempDir: %v", err)
  362. }
  363. dirs = []string{d1, d2}
  364. }
  365. }
  366. oldwd := os.Getenv("PWD")
  367. for _, d := range dirs {
  368. err = os.Chdir(d)
  369. if err != nil {
  370. t.Fatalf("Chdir: %v", err)
  371. }
  372. pwd, err1 := unix.Getwd()
  373. os.Setenv("PWD", oldwd)
  374. err2 := fd.Chdir()
  375. if err2 != nil {
  376. // We changed the current directory and cannot go back.
  377. // Don't let the tests continue; they'll scribble
  378. // all over some other directory.
  379. fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err2)
  380. os.Exit(1)
  381. }
  382. if err != nil {
  383. fd.Close()
  384. t.Fatalf("Chdir %s: %s", d, err)
  385. }
  386. if err1 != nil {
  387. fd.Close()
  388. t.Fatalf("Getwd in %s: %s", d, err1)
  389. }
  390. if pwd != d {
  391. fd.Close()
  392. t.Fatalf("Getwd returned %q want %q", pwd, d)
  393. }
  394. }
  395. fd.Close()
  396. }
  397. // mktmpfifo creates a temporary FIFO and provides a cleanup function.
  398. func mktmpfifo(t *testing.T) (*os.File, func()) {
  399. err := unix.Mkfifo("fifo", 0666)
  400. if err != nil {
  401. t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
  402. }
  403. f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
  404. if err != nil {
  405. os.Remove("fifo")
  406. t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
  407. }
  408. return f, func() {
  409. f.Close()
  410. os.Remove("fifo")
  411. }
  412. }