xref: /freebsd/sbin/ipf/common/genmask.c (revision bc7512cc58af2e8bbe5bbf5ca0059b1daa1da897)
1 /*
2  * Copyright (C) 2012 by Darren Reed.
3  *
4  * See the IPFILTER.LICENCE file for details on licencing.
5  *
6  * $Id$
7  */
8 
9 #include "ipf.h"
10 
11 
12 int genmask(family, msk, mskp)
13 	int family;
14 	char *msk;
15 	i6addr_t *mskp;
16 {
17 	char *endptr = 0L;
18 	u_32_t addr;
19 	int bits;
20 
21 	if (strchr(msk, '.') || strchr(msk, 'x') || strchr(msk, ':')) {
22 		/* possibly of the form xxx.xxx.xxx.xxx
23 		 * or 0xYYYYYYYY */
24 		switch (family)
25 		{
26 #ifdef USE_INET6
27 		case AF_INET6 :
28 			if (inet_pton(AF_INET6, msk, &mskp->in4) != 1)
29 				return (-1);
30 			break;
31 #endif
32 		case AF_INET :
33 			if (inet_aton(msk, &mskp->in4) == 0)
34 				return (-1);
35 			break;
36 		default :
37 			return (-1);
38 			/*NOTREACHED*/
39 		}
40 	} else {
41 		/*
42 		 * set x most significant bits
43 		 */
44 		bits = (int)strtol(msk, &endptr, 0);
45 
46 		switch (family)
47 		{
48 		case AF_INET6 :
49 			if ((*endptr != '\0') || (bits < 0) || (bits > 128))
50 				return (-1);
51 			fill6bits(bits, mskp->i6);
52 			break;
53 		case AF_INET :
54 			if (*endptr != '\0' || bits > 32 || bits < 0)
55 				return (-1);
56 			if (bits == 0)
57 				addr = 0;
58 			else
59 				addr = htonl(0xffffffff << (32 - bits));
60 			mskp->in4.s_addr = addr;
61 			break;
62 		default :
63 			return (-1);
64 			/*NOTREACHED*/
65 		}
66 	}
67 	return (0);
68 }
69