You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

658 lines
15 KiB

  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. "syscall"
  16. "testing"
  17. "time"
  18. "golang.org/x/sys/unix"
  19. )
  20. // Tests that below functions, structures and constants are consistent
  21. // on all Unix-like systems.
  22. func _() {
  23. // program scheduling priority functions and constants
  24. var (
  25. _ func(int, int, int) error = unix.Setpriority
  26. _ func(int, int) (int, error) = unix.Getpriority
  27. )
  28. const (
  29. _ int = unix.PRIO_USER
  30. _ int = unix.PRIO_PROCESS
  31. _ int = unix.PRIO_PGRP
  32. )
  33. // termios constants
  34. const (
  35. _ int = unix.TCIFLUSH
  36. _ int = unix.TCIOFLUSH
  37. _ int = unix.TCOFLUSH
  38. )
  39. // fcntl file locking structure and constants
  40. var (
  41. _ = unix.Flock_t{
  42. Type: int16(0),
  43. Whence: int16(0),
  44. Start: int64(0),
  45. Len: int64(0),
  46. Pid: int32(0),
  47. }
  48. )
  49. const (
  50. _ = unix.F_GETLK
  51. _ = unix.F_SETLK
  52. _ = unix.F_SETLKW
  53. )
  54. }
  55. func TestErrnoSignalName(t *testing.T) {
  56. testErrors := []struct {
  57. num syscall.Errno
  58. name string
  59. }{
  60. {syscall.EPERM, "EPERM"},
  61. {syscall.EINVAL, "EINVAL"},
  62. {syscall.ENOENT, "ENOENT"},
  63. }
  64. for _, te := range testErrors {
  65. t.Run(fmt.Sprintf("%d/%s", te.num, te.name), func(t *testing.T) {
  66. e := unix.ErrnoName(te.num)
  67. if e != te.name {
  68. t.Errorf("ErrnoName(%d) returned %s, want %s", te.num, e, te.name)
  69. }
  70. })
  71. }
  72. testSignals := []struct {
  73. num syscall.Signal
  74. name string
  75. }{
  76. {syscall.SIGHUP, "SIGHUP"},
  77. {syscall.SIGPIPE, "SIGPIPE"},
  78. {syscall.SIGSEGV, "SIGSEGV"},
  79. }
  80. for _, ts := range testSignals {
  81. t.Run(fmt.Sprintf("%d/%s", ts.num, ts.name), func(t *testing.T) {
  82. s := unix.SignalName(ts.num)
  83. if s != ts.name {
  84. t.Errorf("SignalName(%d) returned %s, want %s", ts.num, s, ts.name)
  85. }
  86. })
  87. }
  88. }
  89. func TestFcntlInt(t *testing.T) {
  90. t.Parallel()
  91. file, err := ioutil.TempFile("", "TestFnctlInt")
  92. if err != nil {
  93. t.Fatal(err)
  94. }
  95. defer os.Remove(file.Name())
  96. defer file.Close()
  97. f := file.Fd()
  98. flags, err := unix.FcntlInt(f, unix.F_GETFD, 0)
  99. if err != nil {
  100. t.Fatal(err)
  101. }
  102. if flags&unix.FD_CLOEXEC == 0 {
  103. t.Errorf("flags %#x do not include FD_CLOEXEC", flags)
  104. }
  105. }
  106. // TestFcntlFlock tests whether the file locking structure matches
  107. // the calling convention of each kernel.
  108. func TestFcntlFlock(t *testing.T) {
  109. name := filepath.Join(os.TempDir(), "TestFcntlFlock")
  110. fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
  111. if err != nil {
  112. t.Fatalf("Open failed: %v", err)
  113. }
  114. defer unix.Unlink(name)
  115. defer unix.Close(fd)
  116. flock := unix.Flock_t{
  117. Type: unix.F_RDLCK,
  118. Start: 0, Len: 0, Whence: 1,
  119. }
  120. if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
  121. t.Fatalf("FcntlFlock failed: %v", err)
  122. }
  123. }
  124. // TestPassFD tests passing a file descriptor over a Unix socket.
  125. //
  126. // This test involved both a parent and child process. The parent
  127. // process is invoked as a normal test, with "go test", which then
  128. // runs the child process by running the current test binary with args
  129. // "-test.run=^TestPassFD$" and an environment variable used to signal
  130. // that the test should become the child process instead.
  131. func TestPassFD(t *testing.T) {
  132. if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
  133. t.Skip("cannot exec subprocess on iOS, skipping test")
  134. }
  135. if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  136. passFDChild()
  137. return
  138. }
  139. tempDir, err := ioutil.TempDir("", "TestPassFD")
  140. if err != nil {
  141. t.Fatal(err)
  142. }
  143. defer os.RemoveAll(tempDir)
  144. fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
  145. if err != nil {
  146. t.Fatalf("Socketpair: %v", err)
  147. }
  148. defer unix.Close(fds[0])
  149. defer unix.Close(fds[1])
  150. writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
  151. readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
  152. defer writeFile.Close()
  153. defer readFile.Close()
  154. cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
  155. cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
  156. if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
  157. cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
  158. }
  159. cmd.ExtraFiles = []*os.File{writeFile}
  160. out, err := cmd.CombinedOutput()
  161. if len(out) > 0 || err != nil {
  162. t.Fatalf("child process: %q, %v", out, err)
  163. }
  164. c, err := net.FileConn(readFile)
  165. if err != nil {
  166. t.Fatalf("FileConn: %v", err)
  167. }
  168. defer c.Close()
  169. uc, ok := c.(*net.UnixConn)
  170. if !ok {
  171. t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
  172. }
  173. buf := make([]byte, 32) // expect 1 byte
  174. oob := make([]byte, 32) // expect 24 bytes
  175. closeUnix := time.AfterFunc(5*time.Second, func() {
  176. t.Logf("timeout reading from unix socket")
  177. uc.Close()
  178. })
  179. _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
  180. if err != nil {
  181. t.Fatalf("ReadMsgUnix: %v", err)
  182. }
  183. closeUnix.Stop()
  184. scms, err := unix.ParseSocketControlMessage(oob[:oobn])
  185. if err != nil {
  186. t.Fatalf("ParseSocketControlMessage: %v", err)
  187. }
  188. if len(scms) != 1 {
  189. t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
  190. }
  191. scm := scms[0]
  192. gotFds, err := unix.ParseUnixRights(&scm)
  193. if err != nil {
  194. t.Fatalf("unix.ParseUnixRights: %v", err)
  195. }
  196. if len(gotFds) != 1 {
  197. t.Fatalf("wanted 1 fd; got %#v", gotFds)
  198. }
  199. f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
  200. defer f.Close()
  201. got, err := ioutil.ReadAll(f)
  202. want := "Hello from child process!\n"
  203. if string(got) != want {
  204. t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
  205. }
  206. }
  207. // passFDChild is the child process used by TestPassFD.
  208. func passFDChild() {
  209. defer os.Exit(0)
  210. // Look for our fd. It should be fd 3, but we work around an fd leak
  211. // bug here (http://golang.org/issue/2603) to let it be elsewhere.
  212. var uc *net.UnixConn
  213. for fd := uintptr(3); fd <= 10; fd++ {
  214. f := os.NewFile(fd, "unix-conn")
  215. var ok bool
  216. netc, _ := net.FileConn(f)
  217. uc, ok = netc.(*net.UnixConn)
  218. if ok {
  219. break
  220. }
  221. }
  222. if uc == nil {
  223. fmt.Println("failed to find unix fd")
  224. return
  225. }
  226. // Make a file f to send to our parent process on uc.
  227. // We make it in tempDir, which our parent will clean up.
  228. flag.Parse()
  229. tempDir := flag.Arg(0)
  230. f, err := ioutil.TempFile(tempDir, "")
  231. if err != nil {
  232. fmt.Printf("TempFile: %v", err)
  233. return
  234. }
  235. f.Write([]byte("Hello from child process!\n"))
  236. f.Seek(0, 0)
  237. rights := unix.UnixRights(int(f.Fd()))
  238. dummyByte := []byte("x")
  239. n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
  240. if err != nil {
  241. fmt.Printf("WriteMsgUnix: %v", err)
  242. return
  243. }
  244. if n != 1 || oobn != len(rights) {
  245. fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
  246. return
  247. }
  248. }
  249. // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
  250. // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
  251. func TestUnixRightsRoundtrip(t *testing.T) {
  252. testCases := [...][][]int{
  253. {{42}},
  254. {{1, 2}},
  255. {{3, 4, 5}},
  256. {{}},
  257. {{1, 2}, {3, 4, 5}, {}, {7}},
  258. }
  259. for _, testCase := range testCases {
  260. b := []byte{}
  261. var n int
  262. for _, fds := range testCase {
  263. // Last assignment to n wins
  264. n = len(b) + unix.CmsgLen(4*len(fds))
  265. b = append(b, unix.UnixRights(fds...)...)
  266. }
  267. // Truncate b
  268. b = b[:n]
  269. scms, err := unix.ParseSocketControlMessage(b)
  270. if err != nil {
  271. t.Fatalf("ParseSocketControlMessage: %v", err)
  272. }
  273. if len(scms) != len(testCase) {
  274. t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
  275. }
  276. for i, scm := range scms {
  277. gotFds, err := unix.ParseUnixRights(&scm)
  278. if err != nil {
  279. t.Fatalf("ParseUnixRights: %v", err)
  280. }
  281. wantFds := testCase[i]
  282. if len(gotFds) != len(wantFds) {
  283. t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
  284. }
  285. for j, fd := range gotFds {
  286. if fd != wantFds[j] {
  287. t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
  288. }
  289. }
  290. }
  291. }
  292. }
  293. func TestRlimit(t *testing.T) {
  294. var rlimit, zero unix.Rlimit
  295. err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
  296. if err != nil {
  297. t.Fatalf("Getrlimit: save failed: %v", err)
  298. }
  299. if zero == rlimit {
  300. t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
  301. }
  302. set := rlimit
  303. set.Cur = set.Max - 1
  304. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
  305. if err != nil {
  306. t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
  307. }
  308. var get unix.Rlimit
  309. err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
  310. if err != nil {
  311. t.Fatalf("Getrlimit: get failed: %v", err)
  312. }
  313. set = rlimit
  314. set.Cur = set.Max - 1
  315. if set != get {
  316. // Seems like Darwin requires some privilege to
  317. // increase the soft limit of rlimit sandbox, though
  318. // Setrlimit never reports an error.
  319. switch runtime.GOOS {
  320. case "darwin":
  321. default:
  322. t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
  323. }
  324. }
  325. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
  326. if err != nil {
  327. t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
  328. }
  329. }
  330. func TestSeekFailure(t *testing.T) {
  331. _, err := unix.Seek(-1, 0, 0)
  332. if err == nil {
  333. t.Fatalf("Seek(-1, 0, 0) did not fail")
  334. }
  335. str := err.Error() // used to crash on Linux
  336. t.Logf("Seek: %v", str)
  337. if str == "" {
  338. t.Fatalf("Seek(-1, 0, 0) return error with empty message")
  339. }
  340. }
  341. func TestDup(t *testing.T) {
  342. file, err := ioutil.TempFile("", "TestDup")
  343. if err != nil {
  344. t.Fatalf("Tempfile failed: %v", err)
  345. }
  346. defer os.Remove(file.Name())
  347. defer file.Close()
  348. f := int(file.Fd())
  349. newFd, err := unix.Dup(f)
  350. if err != nil {
  351. t.Fatalf("Dup: %v", err)
  352. }
  353. err = unix.Dup2(newFd, newFd+1)
  354. if err != nil {
  355. t.Fatalf("Dup2: %v", err)
  356. }
  357. b1 := []byte("Test123")
  358. b2 := make([]byte, 7)
  359. _, err = unix.Write(newFd+1, b1)
  360. if err != nil {
  361. t.Fatalf("Write to dup2 fd failed: %v", err)
  362. }
  363. _, err = unix.Seek(f, 0, 0)
  364. if err != nil {
  365. t.Fatalf("Seek failed: %v", err)
  366. }
  367. _, err = unix.Read(f, b2)
  368. if err != nil {
  369. t.Fatalf("Read back failed: %v", err)
  370. }
  371. if string(b1) != string(b2) {
  372. t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
  373. }
  374. }
  375. func TestPoll(t *testing.T) {
  376. if runtime.GOOS == "android" ||
  377. (runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")) {
  378. t.Skip("mkfifo syscall is not available on android and iOS, skipping test")
  379. }
  380. f, cleanup := mktmpfifo(t)
  381. defer cleanup()
  382. const timeout = 100
  383. ok := make(chan bool, 1)
  384. go func() {
  385. select {
  386. case <-time.After(10 * timeout * time.Millisecond):
  387. t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
  388. case <-ok:
  389. }
  390. }()
  391. fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
  392. n, err := unix.Poll(fds, timeout)
  393. ok <- true
  394. if err != nil {
  395. t.Errorf("Poll: unexpected error: %v", err)
  396. return
  397. }
  398. if n != 0 {
  399. t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
  400. return
  401. }
  402. }
  403. func TestGetwd(t *testing.T) {
  404. fd, err := os.Open(".")
  405. if err != nil {
  406. t.Fatalf("Open .: %s", err)
  407. }
  408. defer fd.Close()
  409. // These are chosen carefully not to be symlinks on a Mac
  410. // (unlike, say, /var, /etc)
  411. dirs := []string{"/", "/usr/bin"}
  412. switch runtime.GOOS {
  413. case "android":
  414. dirs = []string{"/", "/system/bin"}
  415. case "darwin":
  416. switch runtime.GOARCH {
  417. case "arm", "arm64":
  418. d1, err := ioutil.TempDir("", "d1")
  419. if err != nil {
  420. t.Fatalf("TempDir: %v", err)
  421. }
  422. d2, err := ioutil.TempDir("", "d2")
  423. if err != nil {
  424. t.Fatalf("TempDir: %v", err)
  425. }
  426. dirs = []string{d1, d2}
  427. }
  428. }
  429. oldwd := os.Getenv("PWD")
  430. for _, d := range dirs {
  431. err = os.Chdir(d)
  432. if err != nil {
  433. t.Fatalf("Chdir: %v", err)
  434. }
  435. pwd, err := unix.Getwd()
  436. if err != nil {
  437. t.Fatalf("Getwd in %s: %s", d, err)
  438. }
  439. os.Setenv("PWD", oldwd)
  440. err = fd.Chdir()
  441. if err != nil {
  442. // We changed the current directory and cannot go back.
  443. // Don't let the tests continue; they'll scribble
  444. // all over some other directory.
  445. fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err)
  446. os.Exit(1)
  447. }
  448. if pwd != d {
  449. t.Fatalf("Getwd returned %q want %q", pwd, d)
  450. }
  451. }
  452. }
  453. func TestFstatat(t *testing.T) {
  454. defer chtmpdir(t)()
  455. touch(t, "file1")
  456. var st1 unix.Stat_t
  457. err := unix.Stat("file1", &st1)
  458. if err != nil {
  459. t.Fatalf("Stat: %v", err)
  460. }
  461. var st2 unix.Stat_t
  462. err = unix.Fstatat(unix.AT_FDCWD, "file1", &st2, 0)
  463. if err != nil {
  464. t.Fatalf("Fstatat: %v", err)
  465. }
  466. if st1 != st2 {
  467. t.Errorf("Fstatat: returned stat does not match Stat")
  468. }
  469. err = os.Symlink("file1", "symlink1")
  470. if err != nil {
  471. t.Fatal(err)
  472. }
  473. err = unix.Lstat("symlink1", &st1)
  474. if err != nil {
  475. t.Fatalf("Lstat: %v", err)
  476. }
  477. err = unix.Fstatat(unix.AT_FDCWD, "symlink1", &st2, unix.AT_SYMLINK_NOFOLLOW)
  478. if err != nil {
  479. t.Fatalf("Fstatat: %v", err)
  480. }
  481. if st1 != st2 {
  482. t.Errorf("Fstatat: returned stat does not match Lstat")
  483. }
  484. }
  485. func TestFchmodat(t *testing.T) {
  486. defer chtmpdir(t)()
  487. touch(t, "file1")
  488. err := os.Symlink("file1", "symlink1")
  489. if err != nil {
  490. t.Fatal(err)
  491. }
  492. mode := os.FileMode(0444)
  493. err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), 0)
  494. if err != nil {
  495. t.Fatalf("Fchmodat: unexpected error: %v", err)
  496. }
  497. fi, err := os.Stat("file1")
  498. if err != nil {
  499. t.Fatal(err)
  500. }
  501. if fi.Mode() != mode {
  502. t.Errorf("Fchmodat: failed to change file mode: expected %v, got %v", mode, fi.Mode())
  503. }
  504. mode = os.FileMode(0644)
  505. didChmodSymlink := true
  506. err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), unix.AT_SYMLINK_NOFOLLOW)
  507. if err != nil {
  508. if (runtime.GOOS == "android" || runtime.GOOS == "linux" || runtime.GOOS == "solaris") && err == unix.EOPNOTSUPP {
  509. // Linux and Illumos don't support flags != 0
  510. didChmodSymlink = false
  511. } else {
  512. t.Fatalf("Fchmodat: unexpected error: %v", err)
  513. }
  514. }
  515. if !didChmodSymlink {
  516. // Didn't change mode of the symlink. On Linux, the permissions
  517. // of a symbolic link are always 0777 according to symlink(7)
  518. mode = os.FileMode(0777)
  519. }
  520. var st unix.Stat_t
  521. err = unix.Lstat("symlink1", &st)
  522. if err != nil {
  523. t.Fatal(err)
  524. }
  525. got := os.FileMode(st.Mode & 0777)
  526. if got != mode {
  527. t.Errorf("Fchmodat: failed to change symlink mode: expected %v, got %v", mode, got)
  528. }
  529. }
  530. func TestMkdev(t *testing.T) {
  531. major := uint32(42)
  532. minor := uint32(7)
  533. dev := unix.Mkdev(major, minor)
  534. if unix.Major(dev) != major {
  535. t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
  536. }
  537. if unix.Minor(dev) != minor {
  538. t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
  539. }
  540. }
  541. // mktmpfifo creates a temporary FIFO and provides a cleanup function.
  542. func mktmpfifo(t *testing.T) (*os.File, func()) {
  543. err := unix.Mkfifo("fifo", 0666)
  544. if err != nil {
  545. t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
  546. }
  547. f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
  548. if err != nil {
  549. os.Remove("fifo")
  550. t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
  551. }
  552. return f, func() {
  553. f.Close()
  554. os.Remove("fifo")
  555. }
  556. }
  557. // utilities taken from os/os_test.go
  558. func touch(t *testing.T, name string) {
  559. f, err := os.Create(name)
  560. if err != nil {
  561. t.Fatal(err)
  562. }
  563. if err := f.Close(); err != nil {
  564. t.Fatal(err)
  565. }
  566. }
  567. // chtmpdir changes the working directory to a new temporary directory and
  568. // provides a cleanup function. Used when PWD is read-only.
  569. func chtmpdir(t *testing.T) func() {
  570. oldwd, err := os.Getwd()
  571. if err != nil {
  572. t.Fatalf("chtmpdir: %v", err)
  573. }
  574. d, err := ioutil.TempDir("", "test")
  575. if err != nil {
  576. t.Fatalf("chtmpdir: %v", err)
  577. }
  578. if err := os.Chdir(d); err != nil {
  579. t.Fatalf("chtmpdir: %v", err)
  580. }
  581. return func() {
  582. if err := os.Chdir(oldwd); err != nil {
  583. t.Fatalf("chtmpdir: %v", err)
  584. }
  585. os.RemoveAll(d)
  586. }
  587. }