diff options
-rw-r--r-- | cbits/tun-linux.c | 5 | ||||
-rw-r--r-- | cbits/tun-macos.c | 6 | ||||
-rw-r--r-- | src/Main.hs | 2 | ||||
-rw-r--r-- | src/Network/WireGuard/Foreign/Tun.hs | 14 |
4 files changed, 16 insertions, 11 deletions
diff --git a/cbits/tun-linux.c b/cbits/tun-linux.c index adbd7c2..202e60d 100644 --- a/cbits/tun-linux.c +++ b/cbits/tun-linux.c @@ -1,5 +1,6 @@ #include <string.h> +#include <errno.h> #include <fcntl.h> #include <linux/if_tun.h> #include <net/if.h> @@ -12,8 +13,10 @@ int tun_alloc(const char *dev_name, int threads, int *fds) { struct ifreq ifr; int fd, i; - if (!dev_name) + if (!dev_name) { + errno = EINVAL; return -1; + } memset(&ifr, 0, sizeof(ifr)); diff --git a/cbits/tun-macos.c b/cbits/tun-macos.c index 7d57350..839ffe9 100644 --- a/cbits/tun-macos.c +++ b/cbits/tun-macos.c @@ -21,6 +21,7 @@ #include <string.h> #include <sys/types.h> +#include <errno.h> #include <net/if_utun.h> #include <netinet/ip.h> #include <sys/ioctl.h> @@ -36,14 +37,17 @@ int tun_alloc(const char *dev_name, int threads, int *fds) { struct sockaddr_ctl sc; int fd, utun_num; - if (!dev_name || sscanf(dev_name, "utun%d", &utun_num) != 1) + if (!dev_name || sscanf(dev_name, "utun%d", &utun_num) != 1) { + errno = EINVAL; return -1; + } memset(&ctlInfo, 0, sizeof(ctlInfo)); if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name)) >= sizeof(ctlInfo.ctl_name)) { + errno = EINVAL; return -1; } diff --git a/src/Main.hs b/src/Main.hs index 29a2c30..29d4953 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -55,7 +55,7 @@ main = do let sockPath = runPath </> "wireguard" </> (intfName ++ ".sock") createDirectoryIfMissing False (takeDirectory sockPath) - fds <- maybe (die "failed to open device") return =<< openTun intfName =<< getNumCapabilities + fds <- openTun intfName =<< getNumCapabilities let runner daemon | foreground = daemon | otherwise = void $ forkProcess $ do diff --git a/src/Network/WireGuard/Foreign/Tun.hs b/src/Network/WireGuard/Foreign/Tun.hs index 2d0f929..3fdbbd4 100644 --- a/src/Network/WireGuard/Foreign/Tun.hs +++ b/src/Network/WireGuard/Foreign/Tun.hs @@ -14,17 +14,15 @@ import System.Posix.Types (Fd (..)) import Foreign import Foreign.C -openTun :: String -> Int -> IO (Maybe [Fd]) +openTun :: String -> Int -> IO [Fd] openTun intfName threads = withCString intfName $ \intf_name_c -> allocaArray threads $ \fds_c -> do - res <- tun_alloc_c intf_name_c (fromIntegral threads) fds_c -- TODO: handle exception - if res > 0 - then do - fds <- peekArray (fromIntegral res) fds_c - forM_ fds $ \fd -> setNonBlockingFD fd True - return (Just (map Fd fds)) - else return Nothing + res <- throwErrnoIfMinus1Retry "openTun" $ + tun_alloc_c intf_name_c (fromIntegral threads) fds_c + fds <- peekArray (fromIntegral res) fds_c + forM_ fds $ \fd -> setNonBlockingFD fd True + return (map Fd fds) tunReadBuf :: Fd -> Ptr Word8 -> CSize -> IO CSize tunReadBuf _fd _buf 0 = return 0 |