浏览代码

Fix memory and resource leaks in udp_create_server_socket( ) (#1714)

### Describe

Hi,

Fixes resource and memory leaks in `udp_create_server_socket()` by
ensuring that the socket file descriptor (`udp_fd`) and dynamically
allocated memory (`server_addr`) are properly released on failure.

Specifically, if `addr_bind()`, `event_new()`, or `event_add()` fails,
the function now closes the socket and frees memory to prevent leaks.

### Expected Behavior

On any failure during socket binding or event registration, both
`udp_fd` and `server_addr` should be released to avoid leaking system
resources.

### Actual Behavior

Previously, if `addr_bind()`, `event_new()`, or `event_add()` failed,
the function would return early without closing the socket or freeing
memory, causing file descriptor and heap memory leaks.

This patch addresses overlooked memory and resource cleanup on failure
paths, improving server stability through targeted and essential
changes.

Thanks for reviewing.

Co-authored-by: Gustavo Garcia <[email protected]>
lhywk 3 月之前
父节点
当前提交
5ab95e1a5a
共有 1 个文件被更改,包括 15 次插入2 次删除
  1. 15 2
      src/apps/peer/udpserver.c

+ 15 - 2
src/apps/peer/udpserver.c

@@ -105,7 +105,7 @@ static int udp_create_server_socket(server_type *const server, const char *const
   set_sock_buf_size(udp_fd, UR_SERVER_SOCK_BUF_SIZE);
 
   if (addr_bind(udp_fd, server_addr, 1, 1, UDP_SOCKET) < 0) {
-    return -1;
+    goto cleanup;
   }
 
   socket_set_nonblocking(udp_fd);
@@ -113,13 +113,26 @@ static int udp_create_server_socket(server_type *const server, const char *const
   struct event *udp_ev =
       event_new(server->event_base, udp_fd, EV_READ | EV_PERSIST, udp_server_input_handler, server_addr);
 
-  event_add(udp_ev, NULL);
+  if (udp_ev == NULL) {
+    TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Failed to create new event in udp_create_server_socket\n");
+    goto cleanup;
+  }
+
+  if (event_add(udp_ev, NULL) < 0) {
+    event_free(udp_ev);
+    goto cleanup;
+  }
 
   if (server->verbose) {
     TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "End\n");
   }
 
   return 0;
+
+cleanup:
+  socket_closesocket(udp_fd);
+  free(server_addr);
+  return -1;
 }
 
 static server_type *init_server(int verbose, const char *ifname, char **local_addresses, size_t las, int port) {