aboutsummaryrefslogtreecommitdiffstats
path: root/ipc/uapi_unix.go
diff options
context:
space:
mode:
authorDavid Crawshaw <crawshaw@tailscale.com>2020-05-02 16:28:33 +1000
committerJason A. Donenfeld <Jason@zx2c4.com>2020-05-02 02:05:41 -0600
commitbc77de2acaebe8589193e621933aa42783926aad (patch)
treec68f2b153ce679edf542d1e5d109472909efce8e /ipc/uapi_unix.go
parentipc: remove unnecessary error check (diff)
downloadwireguard-go-bc77de2acaebe8589193e621933aa42783926aad.tar.xz
wireguard-go-bc77de2acaebe8589193e621933aa42783926aad.zip
ipc: deduplicate some unix-specific code
Cleans up and splits out UAPIOpen to its own file. Signed-off-by: David Crawshaw <crawshaw@tailscale.com> [zx2c4: changed const to var for socketDirectory] Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Diffstat (limited to 'ipc/uapi_unix.go')
-rw-r--r--ipc/uapi_unix.go63
1 files changed, 63 insertions, 0 deletions
diff --git a/ipc/uapi_unix.go b/ipc/uapi_unix.go
new file mode 100644
index 0000000..a59c390
--- /dev/null
+++ b/ipc/uapi_unix.go
@@ -0,0 +1,63 @@
+// +build linux darwin freebsd openbsd
+
+/* SPDX-License-Identifier: MIT
+ *
+ * Copyright (C) 2017-2019 WireGuard LLC. All Rights Reserved.
+ */
+
+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)
+)
+
+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) {
+ if err := os.MkdirAll(socketDirectory, 0755); err != nil {
+ return nil, err
+ }
+
+ socketPath := sockPath(name)
+ addr, err := net.ResolveUnixAddr("unix", socketPath)
+ if err != nil {
+ return nil, err
+ }
+
+ oldUmask := unix.Umask(0077)
+ 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()
+}