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