From b7f370c0143567f9f475c12ddadb5910b9eb74b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20=C5=BBenczykowski?= Date: Wed, 6 May 2020 13:36:55 -0700 Subject: [PATCH] libnetutils/packet.c - fix a socket leak on bind error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit and clean up the code a little bit while at it. Test: builds, atest Bug: 155297277 Signed-off-by: Maciej Żenczykowski Change-Id: I01a10e36f852cde1b93a91f95b51294a434885ab --- libnetutils/packet.c | 25 +++++++++++-------------- libnetutils/packet.h | 4 +++- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/libnetutils/packet.c b/libnetutils/packet.c index 9ecdd4f4e..2debc282f 100644 --- a/libnetutils/packet.c +++ b/libnetutils/packet.c @@ -37,25 +37,22 @@ #include "dhcpmsg.h" -int fatal(); +int fatal(const char*); -int open_raw_socket(const char *ifname __attribute__((unused)), uint8_t *hwaddr, int if_index) -{ - int s; - struct sockaddr_ll bindaddr; +int open_raw_socket(const char* ifname __unused, uint8_t hwaddr[ETH_ALEN], int if_index) { + int s = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP)); + if (s < 0) return fatal("socket(PF_PACKET)"); - if((s = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) { - return fatal("socket(PF_PACKET)"); - } - - memset(&bindaddr, 0, sizeof(bindaddr)); - bindaddr.sll_family = AF_PACKET; - bindaddr.sll_protocol = htons(ETH_P_IP); - bindaddr.sll_halen = ETH_ALEN; + struct sockaddr_ll bindaddr = { + .sll_family = AF_PACKET, + .sll_protocol = htons(ETH_P_IP), + .sll_ifindex = if_index, + .sll_halen = ETH_ALEN, + }; memcpy(bindaddr.sll_addr, hwaddr, ETH_ALEN); - bindaddr.sll_ifindex = if_index; if (bind(s, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) { + close(s); return fatal("Cannot bind raw socket to interface"); } diff --git a/libnetutils/packet.h b/libnetutils/packet.h index aade392df..66186fcba 100644 --- a/libnetutils/packet.h +++ b/libnetutils/packet.h @@ -17,7 +17,9 @@ #ifndef _WIFI_PACKET_H_ #define _WIFI_PACKET_H_ -int open_raw_socket(const char *ifname, uint8_t *hwaddr, int if_index); +#include + +int open_raw_socket(const char* ifname, uint8_t hwaddr[ETH_ALEN], int if_index); int send_packet(int s, int if_index, struct dhcp_msg *msg, int size, uint32_t saddr, uint32_t daddr, uint32_t sport, uint32_t dport); int receive_packet(int s, struct dhcp_msg *msg);