netlink: clean up sockets, close files
authorPaul Donald <newtwen+github@gmail.com>
Tue, 30 Dec 2025 15:13:29 +0000 (16:13 +0100)
committerÁlvaro Fernández Rojas <noltari@gmail.com>
Sat, 10 Jan 2026 09:45:22 +0000 (10:45 +0100)
Sockets are handled for most usage paths, except for shutdown. Handle
those at shutdown.

Signed-off-by: Paul Donald <newtwen+github@gmail.com>
Link: https://github.com/openwrt/odhcpd/pull/367
Signed-off-by: Álvaro Fernández Rojas <noltari@gmail.com>
src/netlink.c
src/router.c

index d58e45273ef7f761f828f220efadeff6e5949cd4..247347691c3d7d2961209e33941879fcb2d08e2a 100644 (file)
@@ -53,6 +53,29 @@ static struct event_socket rtnl_event = {
        .sock_bufsize = 133120,
 };
 
+/* Shut down and free netlink sockets/registration. Safe to call multiple times. */
+static void netlink_shutdown(void)
+{
+       /* Deregister event and free the event socket */
+       if (rtnl_event.sock) {
+               odhcpd_deregister(&rtnl_event.ev);
+
+               if (rtnl_event.ev.uloop.fd >= 0) {
+                       close(rtnl_event.ev.uloop.fd);
+                       rtnl_event.ev.uloop.fd = -1;
+               }
+
+               nl_socket_free(rtnl_event.sock);
+               rtnl_event.sock = NULL;
+       }
+
+       /* Free the primary rtnl socket */
+       if (rtnl_socket) {
+               nl_socket_free(rtnl_socket);
+               rtnl_socket = NULL;
+       }
+}
+
 int netlink_init(void)
 {
        rtnl_socket = create_socket(NETLINK_ROUTE);
@@ -85,19 +108,12 @@ int netlink_init(void)
 
        odhcpd_register(&rtnl_event.ev);
 
+       atexit(netlink_shutdown);
+
        return 0;
 
 err:
-       if (rtnl_socket) {
-               nl_socket_free(rtnl_socket);
-               rtnl_socket = NULL;
-       }
-
-       if (rtnl_event.sock) {
-               nl_socket_free(rtnl_event.sock);
-               rtnl_event.sock = NULL;
-               rtnl_event.ev.uloop.fd = -1;
-       }
+       netlink_shutdown();
 
        return -1;
 }
index 6a1d9cba3492213bc49e08ff28a4dcff681ad9d5..731a6dc02f17492d368122d2e72d89f38460c2c3 100644 (file)
@@ -45,6 +45,15 @@ static FILE *fp_route = NULL;
 
 #define TIME_LEFT(t1, now) ((t1) != UINT32_MAX ? (t1) - (now) : UINT32_MAX)
 
+/* Shutdown helper: close fp_route if open. Safe to call multiple times. */
+static void router_shutdown(void)
+{
+       if (fp_route) {
+               fclose(fp_route);
+               fp_route = NULL;
+       }
+}
+
 int router_init(void)
 {
        int ret = 0;
@@ -60,11 +69,11 @@ int router_init(void)
                ret = -1;
        }
 
+       atexit(router_shutdown);
+
 out:
-       if (ret < 0 && fp_route) {
-               fclose(fp_route);
-               fp_route = NULL;
-       }
+       if (ret < 0)
+               router_shutdown();
 
        return ret;
 }