Debian Codegraph @

libgo/go/syscall/syscall_unix_test.go

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