github.com/containerd/Containerd@v1.4.13/sys/socket_unix.go (about) 1 // +build !windows 2 3 /* 4 Copyright The containerd Authors. 5 6 Licensed under the Apache License, Version 2.0 (the "License"); 7 you may not use this file except in compliance with the License. 8 You may obtain a copy of the License at 9 10 http://www.apache.org/licenses/LICENSE-2.0 11 12 Unless required by applicable law or agreed to in writing, software 13 distributed under the License is distributed on an "AS IS" BASIS, 14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 See the License for the specific language governing permissions and 16 limitations under the License. 17 */ 18 19 package sys 20 21 import ( 22 "net" 23 "os" 24 "path/filepath" 25 26 "github.com/pkg/errors" 27 "golang.org/x/sys/unix" 28 ) 29 30 // CreateUnixSocket creates a unix socket and returns the listener 31 func CreateUnixSocket(path string) (net.Listener, error) { 32 // BSDs have a 104 limit 33 if len(path) > 104 { 34 return nil, errors.Errorf("%q: unix socket path too long (> 104)", path) 35 } 36 if err := os.MkdirAll(filepath.Dir(path), 0660); err != nil { 37 return nil, err 38 } 39 if err := unix.Unlink(path); err != nil && !os.IsNotExist(err) { 40 return nil, err 41 } 42 return net.Listen("unix", path) 43 } 44 45 // GetLocalListener returns a listener out of a unix socket. 46 func GetLocalListener(path string, uid, gid int) (net.Listener, error) { 47 // Ensure parent directory is created 48 if err := mkdirAs(filepath.Dir(path), uid, gid); err != nil { 49 return nil, err 50 } 51 52 l, err := CreateUnixSocket(path) 53 if err != nil { 54 return l, err 55 } 56 57 if err := os.Chmod(path, 0660); err != nil { 58 l.Close() 59 return nil, err 60 } 61 62 if err := os.Chown(path, uid, gid); err != nil { 63 l.Close() 64 return nil, err 65 } 66 67 return l, nil 68 } 69 70 func mkdirAs(path string, uid, gid int) error { 71 if _, err := os.Stat(path); !os.IsNotExist(err) { 72 return err 73 } 74 75 if err := os.MkdirAll(path, 0770); err != nil { 76 return err 77 } 78 79 return os.Chown(path, uid, gid) 80 }