github.com/sylabs/singularity/v4@v4.1.3/pkg/util/unix/socket_test.go (about) 1 // Copyright (c) 2019, Sylabs Inc. All rights reserved. 2 // This software is licensed under a 3-clause BSD license. Please consult the 3 // LICENSE.md file distributed with the sources of this project regarding your 4 // rights to use or distribute this software. 5 6 package unix 7 8 import ( 9 "math/rand" 10 "os" 11 "path/filepath" 12 "testing" 13 "time" 14 15 "github.com/sylabs/singularity/v4/internal/pkg/test" 16 ) 17 18 func init() { 19 // TODO - go 1.20 initializes seed randomly by default, so can drop this 20 // deprecated call in future. 21 rand.Seed(time.Now().UnixNano()) //nolint:staticcheck 22 } 23 24 var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") 25 26 func randSeq(n int) string { 27 b := make([]rune, n) 28 for i := range b { 29 //#nosec G404 30 b[i] = letters[rand.Intn(len(letters))] 31 } 32 return string(b) 33 } 34 35 func TestCreateSocket(t *testing.T) { 36 test.DropPrivilege(t) 37 defer test.ResetPrivilege(t) 38 39 paths := []string{ 40 filepath.Join(os.TempDir(), randSeq(10), "socket"), // short path 41 filepath.Join(os.TempDir(), randSeq(100), "socket"), // long path 42 } 43 44 for _, path := range paths { 45 syncCh := make(chan bool, 1) 46 47 dir := filepath.Dir(path) 48 os.Mkdir(dir, 0o700) 49 50 defer os.RemoveAll(dir) 51 52 // create socket and returns listener 53 ln, err := CreateSocket(path) 54 if err != nil { 55 t.Fatal(err) 56 } 57 58 // accept connection and test if received data are correct 59 go func() { 60 buf := make([]byte, 4) 61 62 conn, err := ln.Accept() 63 if err != nil { 64 t.Error(err) 65 } 66 n, err := conn.Read(buf) 67 if err != nil { 68 t.Error(err) 69 } 70 if n != 4 { 71 t.Error() 72 } 73 if string(buf) != "send" { 74 t.Errorf("unexpected data returned: %s", string(buf)) 75 } 76 syncCh <- true 77 }() 78 79 // open / write / close to socket path 80 if err := WriteSocket(path, []byte("send")); err != nil { 81 t.Error(err) 82 } 83 84 <-syncCh 85 86 // close socket implies to delete file automatically 87 os.Chdir(dir) 88 ln.Close() 89 90 // socket file is deleted by net package at close 91 if err := os.Remove(path); err == nil { 92 t.Errorf("unexpected success during socket removal") 93 } 94 } 95 }