diff --git a/src/tun_freebsd.c b/src/tun_freebsd.c index 03981cee8..39508d19d 100644 --- a/src/tun_freebsd.c +++ b/src/tun_freebsd.c @@ -1,6 +1,7 @@ // tun_freebsd.c - FreeBSD TUN/TAP implementation // Uses /dev/tun device with ioctl #if defined(__FreeBSD__) +#include // SIOCIFDESTROY #include "tun_if.h" #include "../lib/debug_config.h" #include @@ -292,9 +293,35 @@ int tun_platform_init(struct tun_if* tun, const char* ifname, const char* ip_str } // Platform-specific cleanup for FreeBSD void tun_platform_cleanup(struct tun_if* tun) { + if (!tun) return; + if (tun->fd >= 0) { close(tun->fd); tun->fd = -1; + DEBUG_INFO(DEBUG_CATEGORY_TUN, "Closed TUN fd for %s", tun->ifname); + } + + if (tun->ifname[0] != '\0') { + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock >= 0) { + struct ifreq ifr = {0}; + strncpy(ifr.ifr_name, tun->ifname, IFNAMSIZ - 1); + ifr.ifr_name[IFNAMSIZ - 1] = '\0'; + + if (ioctl(sock, SIOCIFDESTROY, &ifr) < 0) { + // ENXIO / ENOENT = interface already gone (normal after close) + if (errno != ENXIO && errno != ENOENT) { + DEBUG_WARN(DEBUG_CATEGORY_TUN, + "SIOCIFDESTROY failed for %s: %s (errno=%d)", + tun->ifname, strerror(errno), errno); + } else { + DEBUG_DEBUG(DEBUG_CATEGORY_TUN, "TUN interface %s already destroyed", tun->ifname); + } + } else { + DEBUG_INFO(DEBUG_CATEGORY_TUN, "Successfully destroyed TUN interface %s", tun->ifname); + } + close(sock); + } } } // Platform-specific read for FreeBSD