Home | History | Annotate | Download | only in syscall
      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 // +build 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 	"io/ioutil"
     15 	"net"
     16 	"os"
     17 	"os/exec"
     18 	"path/filepath"
     19 	"runtime"
     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 			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.
     71 func TestFcntlFlock(t *testing.T) {
     72 	if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
     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, err := ioutil.TempDir("", "TestFcntlFlock")
     82 		if err != nil {
     83 			t.Fatalf("Failed to create temp dir: %v", err)
     84 		}
     85 		name := filepath.Join(tempDir, "TestFcntlFlock")
     86 		fd, err := syscall.Open(name, syscall.O_CREAT|syscall.O_RDWR|syscall.O_CLOEXEC, 0)
     87 		if err != nil {
     88 			t.Fatalf("Open failed: %v", err)
     89 		}
     90 		defer os.RemoveAll(tempDir)
     91 		defer syscall.Close(fd)
     92 		if err := syscall.Ftruncate(fd, 1<<20); err != nil {
     93 			t.Fatalf("Ftruncate(1<<20) failed: %v", err)
     94 		}
     95 		if err := syscall.FcntlFlock(uintptr(fd), syscall.F_SETLK, &flock); err != nil {
     96 			t.Fatalf("FcntlFlock(F_SETLK) failed: %v", err)
     97 		}
     98 		cmd := exec.Command(os.Args[0], "-test.run=^TestFcntlFlock$")
     99 		cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
    100 		cmd.ExtraFiles = []*os.File{os.NewFile(uintptr(fd), name)}
    101 		out, err := cmd.CombinedOutput()
    102 		if len(out) > 0 || err != nil {
    103 			t.Fatalf("child process: %q, %v", out, err)
    104 		}
    105 	} else {
    106 		// child
    107 		got := flock
    108 		// make sure the child lock is conflicting with the parent lock
    109 		got.Start--
    110 		got.Len++
    111 		if err := syscall.FcntlFlock(3, syscall.F_GETLK, &got); err != nil {
    112 			t.Fatalf("FcntlFlock(F_GETLK) failed: %v", err)
    113 		}
    114 		flock.Pid = int32(syscall.Getppid())
    115 		// Linux kernel always set Whence to 0
    116 		flock.Whence = 0
    117 		if got.Type == flock.Type && got.Start == flock.Start && got.Len == flock.Len && got.Pid == flock.Pid && got.Whence == flock.Whence {
    118 			os.Exit(0)
    119 		}
    120 		t.Fatalf("FcntlFlock got %v, want %v", got, flock)
    121 	}
    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 	testenv.MustHaveExec(t)
    133 
    134 	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
    135 		passFDChild()
    136 		return
    137 	}
    138 
    139 	tempDir, err := ioutil.TempDir("", "TestPassFD")
    140 	if err != nil {
    141 		t.Fatal(err)
    142 	}
    143 	defer os.RemoveAll(tempDir)
    144 
    145 	fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM, 0)
    146 	if err != nil {
    147 		t.Fatalf("Socketpair: %v", err)
    148 	}
    149 	defer syscall.Close(fds[0])
    150 	defer syscall.Close(fds[1])
    151 	writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
    152 	readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
    153 	defer writeFile.Close()
    154 	defer readFile.Close()
    155 
    156 	cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
    157 	cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
    158 	cmd.ExtraFiles = []*os.File{writeFile}
    159 
    160 	out, err := cmd.CombinedOutput()
    161 	if len(out) > 0 || err != nil {
    162 		t.Fatalf("child process: %q, %v", out, err)
    163 	}
    164 
    165 	c, err := net.FileConn(readFile)
    166 	if err != nil {
    167 		t.Fatalf("FileConn: %v", err)
    168 	}
    169 	defer c.Close()
    170 
    171 	uc, ok := c.(*net.UnixConn)
    172 	if !ok {
    173 		t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
    174 	}
    175 
    176 	buf := make([]byte, 32) // expect 1 byte
    177 	oob := make([]byte, 32) // expect 24 bytes
    178 	closeUnix := time.AfterFunc(5*time.Second, func() {
    179 		t.Logf("timeout reading from unix socket")
    180 		uc.Close()
    181 	})
    182 	_, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
    183 	if err != nil {
    184 		t.Fatalf("ReadMsgUnix: %v", err)
    185 	}
    186 	closeUnix.Stop()
    187 
    188 	scms, err := syscall.ParseSocketControlMessage(oob[:oobn])
    189 	if err != nil {
    190 		t.Fatalf("ParseSocketControlMessage: %v", err)
    191 	}
    192 	if len(scms) != 1 {
    193 		t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
    194 	}
    195 	scm := scms[0]
    196 	gotFds, err := syscall.ParseUnixRights(&scm)
    197 	if err != nil {
    198 		t.Fatalf("syscall.ParseUnixRights: %v", err)
    199 	}
    200 	if len(gotFds) != 1 {
    201 		t.Fatalf("wanted 1 fd; got %#v", gotFds)
    202 	}
    203 
    204 	f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
    205 	defer f.Close()
    206 
    207 	got, err := ioutil.ReadAll(f)
    208 	want := "Hello from child process!\n"
    209 	if string(got) != want {
    210 		t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
    211 	}
    212 }
    213 
    214 // passFDChild is the child process used by TestPassFD.
    215 func passFDChild() {
    216 	defer os.Exit(0)
    217 
    218 	// Look for our fd. It should be fd 3, but we work around an fd leak
    219 	// bug here (https://golang.org/issue/2603) to let it be elsewhere.
    220 	var uc *net.UnixConn
    221 	for fd := uintptr(3); fd <= 10; fd++ {
    222 		f := os.NewFile(fd, "unix-conn")
    223 		var ok bool
    224 		netc, _ := net.FileConn(f)
    225 		uc, ok = netc.(*net.UnixConn)
    226 		if ok {
    227 			break
    228 		}
    229 	}
    230 	if uc == nil {
    231 		fmt.Println("failed to find unix fd")
    232 		return
    233 	}
    234 
    235 	// Make a file f to send to our parent process on uc.
    236 	// We make it in tempDir, which our parent will clean up.
    237 	flag.Parse()
    238 	tempDir := flag.Arg(0)
    239 	f, err := ioutil.TempFile(tempDir, "")
    240 	if err != nil {
    241 		fmt.Printf("TempFile: %v", err)
    242 		return
    243 	}
    244 
    245 	f.Write([]byte("Hello from child process!\n"))
    246 	f.Seek(0, io.SeekStart)
    247 
    248 	rights := syscall.UnixRights(int(f.Fd()))
    249 	dummyByte := []byte("x")
    250 	n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
    251 	if err != nil {
    252 		fmt.Printf("WriteMsgUnix: %v", err)
    253 		return
    254 	}
    255 	if n != 1 || oobn != len(rights) {
    256 		fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
    257 		return
    258 	}
    259 }
    260 
    261 // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
    262 // and ParseUnixRights are able to successfully round-trip lists of file descriptors.
    263 func TestUnixRightsRoundtrip(t *testing.T) {
    264 	testCases := [...][][]int{
    265 		{{42}},
    266 		{{1, 2}},
    267 		{{3, 4, 5}},
    268 		{{}},
    269 		{{1, 2}, {3, 4, 5}, {}, {7}},
    270 	}
    271 	for _, testCase := range testCases {
    272 		b := []byte{}
    273 		var n int
    274 		for _, fds := range testCase {
    275 			// Last assignment to n wins
    276 			n = len(b) + syscall.CmsgLen(4*len(fds))
    277 			b = append(b, syscall.UnixRights(fds...)...)
    278 		}
    279 		// Truncate b
    280 		b = b[:n]
    281 
    282 		scms, err := syscall.ParseSocketControlMessage(b)
    283 		if err != nil {
    284 			t.Fatalf("ParseSocketControlMessage: %v", err)
    285 		}
    286 		if len(scms) != len(testCase) {
    287 			t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
    288 		}
    289 		for i, scm := range scms {
    290 			gotFds, err := syscall.ParseUnixRights(&scm)
    291 			if err != nil {
    292 				t.Fatalf("ParseUnixRights: %v", err)
    293 			}
    294 			wantFds := testCase[i]
    295 			if len(gotFds) != len(wantFds) {
    296 				t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
    297 			}
    298 			for j, fd := range gotFds {
    299 				if fd != wantFds[j] {
    300 					t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
    301 				}
    302 			}
    303 		}
    304 	}
    305 }
    306 
    307 func TestRlimit(t *testing.T) {
    308 	var rlimit, zero syscall.Rlimit
    309 	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit)
    310 	if err != nil {
    311 		t.Fatalf("Getrlimit: save failed: %v", err)
    312 	}
    313 	if zero == rlimit {
    314 		t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
    315 	}
    316 	set := rlimit
    317 	set.Cur = set.Max - 1
    318 	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &set)
    319 	if err != nil {
    320 		t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
    321 	}
    322 	var get syscall.Rlimit
    323 	err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &get)
    324 	if err != nil {
    325 		t.Fatalf("Getrlimit: get failed: %v", err)
    326 	}
    327 	set = rlimit
    328 	set.Cur = set.Max - 1
    329 	if set != get {
    330 		// Seems like Darwin requires some privilege to
    331 		// increase the soft limit of rlimit sandbox, though
    332 		// Setrlimit never reports an error.
    333 		switch runtime.GOOS {
    334 		case "darwin":
    335 		default:
    336 			t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
    337 		}
    338 	}
    339 	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit)
    340 	if err != nil {
    341 		t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
    342 	}
    343 }
    344 
    345 func TestSeekFailure(t *testing.T) {
    346 	_, err := syscall.Seek(-1, 0, io.SeekStart)
    347 	if err == nil {
    348 		t.Fatalf("Seek(-1, 0, 0) did not fail")
    349 	}
    350 	str := err.Error() // used to crash on Linux
    351 	t.Logf("Seek: %v", str)
    352 	if str == "" {
    353 		t.Fatalf("Seek(-1, 0, 0) return error with empty message")
    354 	}
    355 }
    356