socket_unix.go 1.9 KB

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