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