25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

354 lines
8.7 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. "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. switch runtime.GOOS {
  81. case "dragonfly":
  82. // TODO(jsing): Figure out why sendmsg is returning EINVAL.
  83. t.Skip("skipping test on dragonfly")
  84. case "solaris":
  85. // TODO(aram): Figure out why ReadMsgUnix is returning empty message.
  86. t.Skip("skipping test on solaris, see issue 7402")
  87. }
  88. if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
  89. passFDChild()
  90. return
  91. }
  92. tempDir, err := ioutil.TempDir("", "TestPassFD")
  93. if err != nil {
  94. t.Fatal(err)
  95. }
  96. defer os.RemoveAll(tempDir)
  97. fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
  98. if err != nil {
  99. t.Fatalf("Socketpair: %v", err)
  100. }
  101. defer unix.Close(fds[0])
  102. defer unix.Close(fds[1])
  103. writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
  104. readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
  105. defer writeFile.Close()
  106. defer readFile.Close()
  107. cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
  108. cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
  109. if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
  110. cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
  111. }
  112. cmd.ExtraFiles = []*os.File{writeFile}
  113. out, err := cmd.CombinedOutput()
  114. if len(out) > 0 || err != nil {
  115. t.Fatalf("child process: %q, %v", out, err)
  116. }
  117. c, err := net.FileConn(readFile)
  118. if err != nil {
  119. t.Fatalf("FileConn: %v", err)
  120. }
  121. defer c.Close()
  122. uc, ok := c.(*net.UnixConn)
  123. if !ok {
  124. t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
  125. }
  126. buf := make([]byte, 32) // expect 1 byte
  127. oob := make([]byte, 32) // expect 24 bytes
  128. closeUnix := time.AfterFunc(5*time.Second, func() {
  129. t.Logf("timeout reading from unix socket")
  130. uc.Close()
  131. })
  132. _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
  133. closeUnix.Stop()
  134. scms, err := unix.ParseSocketControlMessage(oob[:oobn])
  135. if err != nil {
  136. t.Fatalf("ParseSocketControlMessage: %v", err)
  137. }
  138. if len(scms) != 1 {
  139. t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
  140. }
  141. scm := scms[0]
  142. gotFds, err := unix.ParseUnixRights(&scm)
  143. if err != nil {
  144. t.Fatalf("unix.ParseUnixRights: %v", err)
  145. }
  146. if len(gotFds) != 1 {
  147. t.Fatalf("wanted 1 fd; got %#v", gotFds)
  148. }
  149. f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
  150. defer f.Close()
  151. got, err := ioutil.ReadAll(f)
  152. want := "Hello from child process!\n"
  153. if string(got) != want {
  154. t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
  155. }
  156. }
  157. // passFDChild is the child process used by TestPassFD.
  158. func passFDChild() {
  159. defer os.Exit(0)
  160. // Look for our fd. It should be fd 3, but we work around an fd leak
  161. // bug here (http://golang.org/issue/2603) to let it be elsewhere.
  162. var uc *net.UnixConn
  163. for fd := uintptr(3); fd <= 10; fd++ {
  164. f := os.NewFile(fd, "unix-conn")
  165. var ok bool
  166. netc, _ := net.FileConn(f)
  167. uc, ok = netc.(*net.UnixConn)
  168. if ok {
  169. break
  170. }
  171. }
  172. if uc == nil {
  173. fmt.Println("failed to find unix fd")
  174. return
  175. }
  176. // Make a file f to send to our parent process on uc.
  177. // We make it in tempDir, which our parent will clean up.
  178. flag.Parse()
  179. tempDir := flag.Arg(0)
  180. f, err := ioutil.TempFile(tempDir, "")
  181. if err != nil {
  182. fmt.Printf("TempFile: %v", err)
  183. return
  184. }
  185. f.Write([]byte("Hello from child process!\n"))
  186. f.Seek(0, 0)
  187. rights := unix.UnixRights(int(f.Fd()))
  188. dummyByte := []byte("x")
  189. n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
  190. if err != nil {
  191. fmt.Printf("WriteMsgUnix: %v", err)
  192. return
  193. }
  194. if n != 1 || oobn != len(rights) {
  195. fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
  196. return
  197. }
  198. }
  199. // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
  200. // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
  201. func TestUnixRightsRoundtrip(t *testing.T) {
  202. testCases := [...][][]int{
  203. {{42}},
  204. {{1, 2}},
  205. {{3, 4, 5}},
  206. {{}},
  207. {{1, 2}, {3, 4, 5}, {}, {7}},
  208. }
  209. for _, testCase := range testCases {
  210. b := []byte{}
  211. var n int
  212. for _, fds := range testCase {
  213. // Last assignment to n wins
  214. n = len(b) + unix.CmsgLen(4*len(fds))
  215. b = append(b, unix.UnixRights(fds...)...)
  216. }
  217. // Truncate b
  218. b = b[:n]
  219. scms, err := unix.ParseSocketControlMessage(b)
  220. if err != nil {
  221. t.Fatalf("ParseSocketControlMessage: %v", err)
  222. }
  223. if len(scms) != len(testCase) {
  224. t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
  225. }
  226. for i, scm := range scms {
  227. gotFds, err := unix.ParseUnixRights(&scm)
  228. if err != nil {
  229. t.Fatalf("ParseUnixRights: %v", err)
  230. }
  231. wantFds := testCase[i]
  232. if len(gotFds) != len(wantFds) {
  233. t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
  234. }
  235. for j, fd := range gotFds {
  236. if fd != wantFds[j] {
  237. t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
  238. }
  239. }
  240. }
  241. }
  242. }
  243. func TestRlimit(t *testing.T) {
  244. var rlimit, zero unix.Rlimit
  245. err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
  246. if err != nil {
  247. t.Fatalf("Getrlimit: save failed: %v", err)
  248. }
  249. if zero == rlimit {
  250. t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
  251. }
  252. set := rlimit
  253. set.Cur = set.Max - 1
  254. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
  255. if err != nil {
  256. t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
  257. }
  258. var get unix.Rlimit
  259. err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
  260. if err != nil {
  261. t.Fatalf("Getrlimit: get failed: %v", err)
  262. }
  263. set = rlimit
  264. set.Cur = set.Max - 1
  265. if set != get {
  266. // Seems like Darwin requires some privilege to
  267. // increase the soft limit of rlimit sandbox, though
  268. // Setrlimit never reports an error.
  269. switch runtime.GOOS {
  270. case "darwin":
  271. default:
  272. t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
  273. }
  274. }
  275. err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
  276. if err != nil {
  277. t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
  278. }
  279. }
  280. func TestSeekFailure(t *testing.T) {
  281. _, err := unix.Seek(-1, 0, 0)
  282. if err == nil {
  283. t.Fatalf("Seek(-1, 0, 0) did not fail")
  284. }
  285. str := err.Error() // used to crash on Linux
  286. t.Logf("Seek: %v", str)
  287. if str == "" {
  288. t.Fatalf("Seek(-1, 0, 0) return error with empty message")
  289. }
  290. }
  291. func TestDup(t *testing.T) {
  292. file, err := ioutil.TempFile("", "TestDup")
  293. if err != nil {
  294. t.Fatalf("Tempfile failed: %v", err)
  295. }
  296. defer os.Remove(file.Name())
  297. defer file.Close()
  298. f := int(file.Fd())
  299. newFd, err := unix.Dup(f)
  300. if err != nil {
  301. t.Fatalf("Dup: %v", err)
  302. }
  303. err = unix.Dup2(newFd, newFd+1)
  304. if err != nil {
  305. t.Fatalf("Dup2: %v", err)
  306. }
  307. b1 := []byte("Test123")
  308. b2 := make([]byte, 7)
  309. _, err = unix.Write(newFd+1, b1)
  310. if err != nil {
  311. t.Fatalf("Write to dup2 fd failed: %v", err)
  312. }
  313. _, err = unix.Seek(f, 0, 0)
  314. _, err = unix.Read(f, b2)
  315. if err != nil {
  316. t.Fatalf("Read back failed: %v", err)
  317. }
  318. if string(b1) != string(b2) {
  319. t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
  320. }
  321. }