2020-07-08 00:15:37 +00:00
|
|
|
//go:build linux || darwin || freebsd || openbsd || netbsd
|
2020-05-02 06:28:33 +00:00
|
|
|
|
|
|
|
/* SPDX-License-Identifier: MIT
|
|
|
|
*
|
2021-01-28 16:52:15 +00:00
|
|
|
* Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.
|
2020-05-02 06:28:33 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
package ipc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
IpcErrorIO = -int64(unix.EIO)
|
|
|
|
IpcErrorProtocol = -int64(unix.EPROTO)
|
|
|
|
IpcErrorInvalid = -int64(unix.EINVAL)
|
|
|
|
IpcErrorPortInUse = -int64(unix.EADDRINUSE)
|
2021-01-25 17:21:51 +00:00
|
|
|
IpcErrorUnknown = -55 // ENOANO
|
2020-05-02 06:28:33 +00:00
|
|
|
)
|
|
|
|
|
2020-06-22 00:41:19 +00:00
|
|
|
// socketDirectory is variable because it is modified by a linker
|
|
|
|
// flag in wireguard-android.
|
2020-05-02 06:28:33 +00:00
|
|
|
var socketDirectory = "/var/run/wireguard"
|
|
|
|
|
|
|
|
func sockPath(iface string) string {
|
|
|
|
return fmt.Sprintf("%s/%s.sock", socketDirectory, iface)
|
|
|
|
}
|
|
|
|
|
|
|
|
func UAPIOpen(name string) (*os.File, error) {
|
2021-12-09 16:55:50 +00:00
|
|
|
if err := os.MkdirAll(socketDirectory, 0o755); err != nil {
|
2020-05-02 06:28:33 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
socketPath := sockPath(name)
|
|
|
|
addr, err := net.ResolveUnixAddr("unix", socketPath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-12-09 16:55:50 +00:00
|
|
|
oldUmask := unix.Umask(0o077)
|
2020-05-02 06:28:33 +00:00
|
|
|
defer unix.Umask(oldUmask)
|
|
|
|
|
|
|
|
listener, err := net.ListenUnix("unix", addr)
|
|
|
|
if err == nil {
|
|
|
|
return listener.File()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Test socket, if not in use cleanup and try again.
|
|
|
|
if _, err := net.Dial("unix", socketPath); err == nil {
|
|
|
|
return nil, errors.New("unix socket in use")
|
|
|
|
}
|
|
|
|
if err := os.Remove(socketPath); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
listener, err = net.ListenUnix("unix", addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return listener.File()
|
|
|
|
}
|