1 /*
2  * Copyright (c) 2016-2021 Free Software Foundation, Inc.
3  *
4  * This file is part of libwget.
5  *
6  * Libwget is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Libwget is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with libwget.  If not, see <https://www.gnu.org/licenses/>.
18  *
19  *
20  * IP address helper routines
21  *
22  */
23 
24 #include <config.h>
25 
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 
29 #include <wget.h>
30 #include "private.h"
31 
32 /**
33  * \file
34  * \brief IP address functions
35  * \defgroup libwget-ip IP address functions
36  * @{
37  *
38  * Routines to check IP address formats.
39  */
40 
41 /**
42  * \param[in] host Host/IP string
43  * \param[in] family IP address family
44  * \return
45  * 1 if \p host matches is of \p family<br>
46  * 0 if \p host does not match \p family<br>
47  *
48  * This functions checks if \p host matches the given \p family or not.
49  */
wget_ip_is_family(const char * host,int family)50 bool wget_ip_is_family(const char *host, int family)
51 {
52 	struct sockaddr_storage dst;
53 
54 	if (!host)
55 		return 0;
56 
57 	switch (family) {
58 	case WGET_NET_FAMILY_IPV4:
59 		return inet_pton(AF_INET, host, (struct in_addr *) &dst);
60 	case WGET_NET_FAMILY_IPV6:
61 		return inet_pton(AF_INET6, host, (struct in6_addr *) &dst);
62 	default:
63 		return 0;
64 	}
65 }
66 
67 /* Not finished, currently not needed
68 int wget_ip_is_ip(const char *addr)
69 {
70 	if (!addr)
71 		return 0;
72 
73 	return wget_ip_is_family(addr, WGET_NET_FAMILY_IPV4) || wget_ip_is_family(addr, WGET_NET_FAMILY_IPV6);
74 }
75 
76 int wget_ip_parse_cidr(const char *s, wget_network_addr_t *addr)
77 {
78 	if (!s)
79 		return -1;
80 
81 	const char *p;
82 	int mask_bits = 32;
83 	uint32_t mask = 0xFFFFFFFF;
84 
85 	if ((p = strchr(s, "/"))) {
86 		if ((c_isdigit(p[1]) && p[2] == 0)
87 			|| (p[1] >= '1' && p[1] <= '3' && isdigit(p[2]) && p[3] == 0))
88 		{
89 			mask_bits = atoi(p + 1);
90 
91 			if (mask_bits > 32)
92 				return -1;
93 
94 			if (mask_bits == 0)
95 				mask = 0;
96 			else if (mask_bits < 32)
97 				mask = mask << (32 - mask_bits);
98 		} else
99 			return -1;
100 	}
101 
102 	return wget_ip_is_family(addr, WGET_NET_FAMILY_IPV4) || wget_ip_is_family(addr, WGET_NET_FAMILY_IPV6);
103 }
104 */
105 
106 /**@}*/
107