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