-
Notifications
You must be signed in to change notification settings - Fork 77
/
unixsock.go
39 lines (32 loc) · 917 Bytes
/
unixsock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//go:build !windows
// +build !windows
package utils
import (
"fmt"
"net"
"os"
)
// UnixSocketListen listens on a Unix socket, handling file locking and permissions.
func UnixSocketListen(filename string, permissions os.FileMode) (net.Listener, *FLock, error) {
lock, err := TryFLock(filename + ".lock")
if err != nil {
return nil, nil, fmt.Errorf("could not acquire lock on socket file: %s", err)
}
err = os.RemoveAll(filename)
if err != nil {
_ = lock.Unlock()
return nil, nil, fmt.Errorf("could not overwrite socket file: %s", err)
}
uli, err := net.Listen("unix", filename)
if err != nil {
_ = lock.Unlock()
return nil, nil, fmt.Errorf("could not listen on socket file: %s", err)
}
err = os.Chmod(filename, permissions)
if err != nil {
_ = uli.Close()
_ = lock.Unlock()
return nil, nil, fmt.Errorf("error setting socket file permissions: %s", err)
}
return uli, lock, nil
}