From c2f03da27c3726907f540dcbe75a35d71b03ee2c Mon Sep 17 00:00:00 2001 From: Remi NGUYEN VAN Date: Sun, 21 Mar 2021 14:30:38 +0000 Subject: Add NDK API for getprocnetwork The API is the getter couterpart for setprocnetwork. Use it in NetworkUtils so that the NDK API can be the source of truth for the process network. Bug: 171540887 Test: atest CtsNetTestCases Tests in change I311b58585033c2ca50ce5477ea9cd94b6f127507 Merged-In: Ie8f68cf1fa57deddb63324c1abf3d6fd5b0ef500 Change-Id: If37c1480e8a6fe22ce0340858fcde052e8770923 --- native/android/net.c | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) (limited to 'native/android/net.c') diff --git a/native/android/net.c b/native/android/net.c index a8104fc23041..d4b888845b27 100644 --- a/native/android/net.c +++ b/native/android/net.c @@ -22,12 +22,13 @@ #include #include +// This value MUST be kept in sync with the corresponding value in +// the android.net.Network#getNetworkHandle() implementation. +static const uint32_t kHandleMagic = 0xcafed00d; +static const uint32_t kHandleMagicSize = 32; static int getnetidfromhandle(net_handle_t handle, unsigned *netid) { static const uint32_t k32BitMask = 0xffffffff; - // This value MUST be kept in sync with the corresponding value in - // the android.net.Network#getNetworkHandle() implementation. - static const uint32_t kHandleMagic = 0xcafed00d; // Check for minimum acceptable version of the API in the low bits. if (handle != NETWORK_UNSPECIFIED && @@ -41,6 +42,12 @@ static int getnetidfromhandle(net_handle_t handle, unsigned *netid) { return 1; } +static net_handle_t gethandlefromnetid(unsigned netid) { + if (netid == NETID_UNSET) { + return NETWORK_UNSPECIFIED; + } + return (((net_handle_t) netid) << kHandleMagicSize) | kHandleMagic; +} int android_setsocknetwork(net_handle_t network, int fd) { unsigned netid; @@ -72,6 +79,17 @@ int android_setprocnetwork(net_handle_t network) { return rval; } +int android_getprocnetwork(net_handle_t *network) { + if (network == NULL) { + errno = EINVAL; + return -1; + } + + unsigned netid = getNetworkForProcess(); + *network = gethandlefromnetid(netid); + return 0; +} + int android_getaddrinfofornetwork(net_handle_t network, const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res) { -- cgit v1.2.3-59-g8ed1b