Use native netlink code instead of /sbin/ip to manipulate routes
Shelling out to /sbin/ip is slow, and more importantly it does
not preserve the error messages returned by the kernel when
adding or deleting a route fails. Instead, use netlink directly.
This change does not yet pass the errors back to CommandListener;
that is done in the next change in the series.
Change-Id: I5ad3c8583580857be6386a620ff5c4f3872d685b
diff --git a/server/NetdConstants.cpp b/server/NetdConstants.cpp
index ea31410..4823c91 100644
--- a/server/NetdConstants.cpp
+++ b/server/NetdConstants.cpp
@@ -15,6 +15,9 @@
*/
#include <fcntl.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <ctype.h>
@@ -170,3 +173,78 @@
return true;
}
+
+int parsePrefix(const char *prefix, uint8_t *family, void *address, int size, uint8_t *prefixlen) {
+ if (!prefix || !family || !address || !prefixlen) {
+ return -EFAULT;
+ }
+
+ // Find the '/' separating address from prefix length.
+ const char *slash = strchr(prefix, '/');
+ const char *prefixlenString = slash + 1;
+ if (!slash || !*prefixlenString)
+ return -EINVAL;
+
+ // Convert the prefix length to a uint8_t.
+ char *endptr;
+ unsigned templen;
+ templen = strtoul(prefixlenString, &endptr, 10);
+ if (*endptr || templen > 255) {
+ return -EINVAL;
+ }
+ *prefixlen = templen;
+
+ // Copy the address part of the prefix to a local buffer. We have to copy
+ // because inet_pton and getaddrinfo operate on null-terminated address
+ // strings, but prefix is const and has '/' after the address.
+ std::string addressString(prefix, slash - prefix);
+
+ // Parse the address.
+ addrinfo *res;
+ addrinfo hints = {
+ .ai_flags = AI_NUMERICHOST,
+ };
+ int ret = getaddrinfo(addressString.c_str(), NULL, &hints, &res);
+ if (ret || !res) {
+ return -EINVAL; // getaddrinfo return values are not errno values.
+ }
+
+ // Convert the address string to raw address bytes.
+ void *rawAddress;
+ int rawLength;
+ switch (res[0].ai_family) {
+ case AF_INET: {
+ if (*prefixlen > 32) {
+ return -EINVAL;
+ }
+ sockaddr_in *sin = (sockaddr_in *) res[0].ai_addr;
+ rawAddress = &sin->sin_addr;
+ rawLength = 4;
+ break;
+ }
+ case AF_INET6: {
+ if (*prefixlen > 128) {
+ return -EINVAL;
+ }
+ sockaddr_in6 *sin6 = (sockaddr_in6 *) res[0].ai_addr;
+ rawAddress = &sin6->sin6_addr;
+ rawLength = 16;
+ break;
+ }
+ default: {
+ freeaddrinfo(res);
+ return -EAFNOSUPPORT;
+ }
+ }
+
+ if (rawLength > size) {
+ freeaddrinfo(res);
+ return -ENOSPC;
+ }
+
+ *family = res[0].ai_family;
+ memcpy(address, rawAddress, rawLength);
+ freeaddrinfo(res);
+
+ return rawLength;
+}