Skip to content

IPv6 APIs don't work if the address is provided as a string #330

@fcelda

Description

@fcelda

IPv6 address parsing from a string is generally broken. It affects bind, connect, and send.

Here is a reproducer:

auto udp = loop->resource<uvw::udp_handle>();
int r = udp->bind("::1", 5300);
assert(r == 0); // fails

I tracked it down to the address conversion in uvw:

uvw/src/uvw/util.ipp

Lines 58 to 69 in 1ba38ea

UVW_INLINE sockaddr ip_addr(const char *addr, unsigned int port) {
// explicitly cast to avoid `-Wsign-conversion` warnings
// libuv internally just casts to an `unsigned short` anyway
auto signed_port = static_cast<int>(port);
if(sockaddr_in addr_in; uv_ip4_addr(addr, signed_port, &addr_in) == 0) {
return reinterpret_cast<const sockaddr &>(addr_in);
} else if(sockaddr_in6 addr_in6; uv_ip6_addr(addr, signed_port, &addr_in6) == 0) {
return reinterpret_cast<const sockaddr &>(addr_in6);
}
return {};
}

The interface of the function is wrong because the sockaddr structure is not designed to be copied directly. The POSIX socket functions use pointer of this type in their interfaces but the pointer has to point to an actual socket structure that can hold the particular address type.

The above randomly works for IPv4 (at least on my machine) because sockaddr and sockaddr_in are the same size (16 bytes). However, sockaddr_in6 is larger (28 bytes). As a result, when parsing an IPv6 address, this function creates an incomplete socket address. It will also cause out-of-bound memory access later when used in the socket API.

I think there are a few alternatives, but all of them will require changing this uvw API:

  • There is sockaddr_storage in POSIX that is guaranteed to fit any socket address types. The function could use that as the return type. However, type type is quite large (128 bytes for me) because it has to fix AF_UNIX address as well.
  • Given that this functionality is restricted to IPv4 and IPv6, some custom union type with sockaddr_in and sockaddr_in6 might do the job as well.
  • Alternatively the target address structure has to be provided by the caller as pointer.

If you tell me what is your preferred solution, I can make a PR with the proposed fix.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions