Created
June 9, 2025 12:28
-
-
Save ochaton/12218d0c19253b917a7b3879ad614eb2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func listenUnix(socket_path string) (*net.UnixListener, error) { | |
addr, err := net.ResolveUnixAddr("unix", socket_path) | |
if err != nil { | |
return nil, err | |
} | |
fi, err := os.Lstat(socket_path) | |
switch { | |
case os.IsNotExist(err): | |
return net.ListenUnix("unix", addr) | |
case err != nil: | |
return nil, &os.PathError{Op: "lstat", Path: socket_path, Err: err} | |
case fi.Mode()&os.ModeSocket == 0: // is not a socket | |
return nil, &os.PathError{Op: "lstat", Path: socket_path, Err: os.ErrInvalid} | |
default: | |
// Check that noone listens on the socket. | |
conn, err := net.DialUnix("unix", nil, addr) | |
if err == nil { | |
conn.Close() | |
return nil, &net.OpError{Net: "unix", Op: "listen", Source: nil, Addr: addr, Err: os.ErrExist} | |
} | |
nerr := err.(*net.OpError) | |
if nerr.Op != "dial" || nerr.Net != "unix" || nerr.Err == nil { | |
return nil, err | |
} | |
if _, ok := nerr.Err.(*os.SyscallError); ok { | |
// remove socket | |
err := os.Remove(socket_path) | |
if err != nil { | |
return nil, &os.PathError{Op: "remove", Path: socket_path, Err: err} | |
} | |
} | |
} | |
return net.ListenUnix("unix", addr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment