Skip to content

Commit

Permalink
feat: add handling for unspecified IPs in connect function
Browse files Browse the repository at this point in the history
Added a utility function to set loopback addresses for unspecified IPv4 and IPv6 addresses during socket connection attempts.
This ensures proper handling of "0.0.0.0" and "::" addresses.
  • Loading branch information
rinor committed Sep 26, 2024
1 parent 974607f commit d07a726
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/net/netsyscall.c
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ static sysreturn sock_read_bh_internal(netsock s, struct msghdr *msg, int flags,
s->sock.fd, ctx, iov, length, flags, bqflags, err);
assert(s->sock.type == SOCK_STREAM || s->sock.type == SOCK_DGRAM);

if ((s->sock.type == SOCK_STREAM && s->info.tcp.state != TCP_SOCK_OPEN) ||
if ((s->sock.type == SOCK_STREAM && s->info.tcp.state != TCP_SOCK_OPEN) ||
(s->sock.type == SOCK_DGRAM && s->info.udp.state == UDP_SOCK_SHUTDOWN)) {
rv = 0;
goto out_unlock;
Expand Down Expand Up @@ -1247,7 +1247,7 @@ static sysreturn netsock_shutdown(struct sock *sock, int how)
rv = -ENOTCONN;
goto out;
}

rv = 0;
out:
/* Wake up any blockers waiting on the socket */
Expand Down Expand Up @@ -1684,6 +1684,19 @@ static inline sysreturn connect_tcp(netsock s, const ip_addr_t* address,
return rv;
}

static inline void set_loopback_if_any(ip_addr_t *ipaddr)
{
if (ipaddr->type == IPADDR_TYPE_V4) {
// Check if the IPv4 address is "0.0.0.0"
if (ip4_addr_isany(ip_2_ip4(ipaddr)))
ip4_addr_set_loopback(ip_2_ip4(ipaddr)); // "127.0.0.1"
} else if (ipaddr->type == IPADDR_TYPE_V6) {
// Check if the IPv6 address is "::"
if (ip6_addr_isany(ip_2_ip6(ipaddr)))
ip6_addr_set_loopback(ip_2_ip6(ipaddr)); // "::1"
}
}

static sysreturn netsock_connect(struct sock *sock, struct sockaddr *addr,
socklen_t addrlen)
{
Expand All @@ -1710,9 +1723,11 @@ static sysreturn netsock_connect(struct sock *sock, struct sockaddr *addr,
msg_warn("attempt to connect on listening socket fd = %d; ignored\n", sock->fd);
ret = -EINVAL;
} else {
set_loopback_if_any(&ipaddr);
ret = connect_tcp(s, &ipaddr, port);
}
} else if (s->sock.type == SOCK_DGRAM) {
set_loopback_if_any(&ipaddr);
/* Set remote endpoint */
ret = lwip_to_errno(udp_connect(s->info.udp.lw, &ipaddr, port));
} else {
Expand Down

0 comments on commit d07a726

Please sign in to comment.