X-Git-Url: http://git.archive.openwrt.org/?p=project%2Fnetifd.git;a=blobdiff_plain;f=utils.c;fp=utils.c;h=986cee96e147f062f24bb03a527716d71b57d8c3;hp=65109d7b262ef82837dbfb2912922c4f036a3956;hb=1ada8cef980df7871b12ed230c789eb28f6cb047;hpb=fe8a6dd2991d54c3eb84cb12764c1316d19bac4e diff --git a/utils.c b/utils.c index 65109d7..986cee9 100644 --- a/utils.c +++ b/utils.c @@ -15,6 +15,9 @@ #include #include "utils.h" +#include +#include + void __vlist_simple_init(struct vlist_simple_tree *tree, int offset) { @@ -66,3 +69,63 @@ vlist_simple_flush_all(struct vlist_simple_tree *tree) tree->version = -1; vlist_simple_flush(tree); } + +unsigned int +parse_netmask_string(const char *str, bool v6) +{ + struct in_addr addr; + unsigned int ret; + char *err = NULL; + + if (!strchr(str, '.')) { + ret = strtoul(str, &err, 0); + if (err && *err) + goto error; + + return ret; + } + + if (v6) + goto error; + + if (inet_aton(str, &addr) != 1) + goto error; + + return 32 - fls(~(ntohl(addr.s_addr))); + +error: + return ~0; +} + +bool +split_netmask(char *str, unsigned int *netmask, bool v6) +{ + char *delim = strchr(str, '/'); + + if (delim) { + *(delim++) = 0; + + *netmask = parse_netmask_string(delim, v6); + } + return true; +} + +int +parse_ip_and_netmask(int af, const char *str, void *addr, unsigned int *netmask) +{ + char *astr = alloca(strlen(str) + 1); + + strcpy(astr, str); + if (!split_netmask(astr, netmask, af == AF_INET6)) + return 0; + + if (af == AF_INET6) { + if (*netmask > 128) + return 0; + } else { + if (*netmask > 32) + return 0; + } + + return inet_pton(af, astr, addr); +}