xref: /illumos-gate/usr/src/cmd/ypcmd/stdhosts.c (revision d362b749)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"	/* SMI4.1 1.7  */
27 
28 #include <stdio.h>
29 #include <ndbm.h>
30 #include <netdb.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <errno.h>
38 
39 /*
40  * Filter to convert both IPv4 and IPv6 addresses from /etc/hosts file.
41  */
42 
43 /*
44  * Size of buffer for input lines. Add two bytes on input for newline
45  * and terminating NULL. Note that the practical limit for data
46  * storage in ndbm is (PBLKSIZ - 3 * sizeof (short)). Though this
47  * differs from spec 1170 the common industry implementation does
48  * conform to this slightly lower limit.
49  */
50 
51 #define	OUTPUTSIZ (PBLKSIZ - 3 * sizeof (short))
52 #define	INPUTSIZ (OUTPUTSIZ + 2)
53 
54 static int ipv4 = -1;
55 static char *cmd;
56 int warning = 0;
57 
58 static void verify_and_output(const char *key, char *value, int lineno);
59 
60 void
61 usage()
62 {
63 	fprintf(stderr, "stdhosts [-w] [-n] [in-file]\n");
64 	fprintf(stderr, "\t-w\tprint malformed warning messages.\n");
65 	exit(1);
66 }
67 
68 int
69 main(argc, argv)
70 	char **argv;
71 {
72 	char line[INPUTSIZ];
73 	char adr[INPUTSIZ];
74 	char nadr[INET6_ADDRSTRLEN]; /* Contains normalised address */
75 	const char *nadrp;	/* Pointer to the normalised address */
76 	char *trailer;
77 	char *commentp;		/* Pointer to comment character '#' */
78 	int c;
79 	FILE *fp;
80 	int lineno = 0;		/* Input line counter */
81 	struct in_addr in;	/* Used for normalising the IPv4 address */
82 	struct in6_addr in6;	/* Used for normalising the IPv6 address */
83 	char *fgetsp;		/* Holds return value for fgets() calls */
84 	int endoffile = 0;	/* Set when end of file reached */
85 
86 	if (cmd = strrchr(argv[0], '/'))
87 		++cmd;
88 	else
89 		cmd = argv[0];
90 
91 	while ((c = getopt(argc, argv, "v:wn")) != -1) {
92 		switch (c) {
93 		case 'w':	/* Send warning messages to stderr */
94 			warning = 1;
95 			break;
96 		case 'n':
97 			ipv4 = 0;
98 			break;
99 		default:
100 			usage();
101 			exit(1);
102 		}
103 	}
104 
105 	if (optind < argc) {
106 		fp = fopen(argv[optind], "r");
107 		if (fp == NULL) {
108 			fprintf(stderr, "%s: can't open %s\n",
109 			    cmd, argv[optind]);
110 			exit(1);
111 		}
112 	} else
113 		fp = stdin;
114 
115 	while (!endoffile &&
116 	    (fgetsp = fgets(line, sizeof (line), fp)) != NULL) {
117 		lineno++;
118 
119 		/* Check for comments */
120 		if ((commentp = strchr(line, '#')) != NULL) {
121 			if ((line[strlen(line) - 1] != '\n') &&
122 			    (strlen(line) >= (sizeof (line) - 1))) {
123 				/*
124 				 * Discard the remainder of the line
125 				 * until the newline or EOF, then
126 				 * continue to parse the line. Use
127 				 * adr[] rather then line[] to
128 				 * preserve the contents of line[].
129 				 */
130 				while ((fgetsp = fgets(adr, sizeof (adr),
131 				    fp)) != NULL) {
132 					if (adr[strlen(adr) - 1] == '\n')
133 						break;
134 				}
135 				if (fgetsp == NULL)
136 					endoffile = 1;
137 			}
138 			/* Terminate line[] at the comment character */
139 			*commentp = '\0';
140 		} else if ((line[strlen(line) - 1] != '\n') &&
141 		    (strlen(line) >= (sizeof (line) - 1))) {
142 			/*
143 			 * Catch long lines but not if this is a short
144 			 * line with no '\n' at the end of the input.
145 			 */
146 			if (warning)
147 				fprintf(stderr,
148 				    "%s: Warning: more than %d "
149 				    "bytes on line %d, ignored\n",
150 				    cmd, sizeof (line) - 2, lineno);
151 			/*
152 			 * Discard the remaining lines until the
153 			 * newline or EOF.
154 			 */
155 			while ((fgetsp = fgets(line, sizeof (line),
156 			    fp)) != NULL)
157 				if (line[strlen(line) - 1] == '\n')
158 					break;
159 			if (fgetsp == NULL)
160 				endoffile = 1;
161 			continue;
162 		}
163 
164 		if (sscanf(line, "%s", adr) != 1) { /* Blank line, ignore */
165 			continue;
166 		}
167 
168 		if ((trailer = strpbrk(line, " \t")) == NULL) {
169 			if (warning)
170 				fprintf(stderr,
171 				    "%s: Warning: no host names on line %d, "
172 				    "ignored\n", cmd, lineno);
173 			continue;
174 		}
175 
176 		/*
177 		 * check for valid addresses
178 		 *
179 		 * Attempt an ipv4 conversion, this accepts all valid
180 		 * ipv4 addresses including:
181 		 *	d
182 		 *	d.d
183 		 *	d.d.d
184 		 * Unfortunately inet_pton() doesn't recognise these.
185 		 */
186 
187 		in.s_addr = inet_addr(adr);
188 		if (-1 != (int)in.s_addr) {
189 			/*
190 			 * It's safe not to check return of NULL as
191 			 * nadrp is checked for validity later.
192 			 */
193 			nadrp = inet_ntop(AF_INET, &in, nadr, sizeof (nadr));
194 		} else {
195 			nadrp = NULL; /* Not a valid IPv4 address */
196 		}
197 
198 		if (nadrp == NULL) {
199 			if (inet_pton(AF_INET6, adr, &in6) == 1) {
200 				nadrp = inet_ntop(AF_INET6, &in6,
201 				    nadr, sizeof (nadr));
202 			}
203 			if (nadrp == NULL) { /* Invalid IPv6 too */
204 				if (warning)
205 					fprintf(stderr,
206 					    "%s: Warning: malformed"
207 					    " address on"
208 					    " line %d, ignored\n",
209 					    cmd, lineno);
210 				continue;
211 			} else if (ipv4) {
212 				continue; /* Ignore valid IPv6  */
213 			}
214 		}
215 
216 		verify_and_output(nadrp, trailer, lineno);
217 
218 	}	/* while */
219 	return (0);
220 	/* NOTREACHED */
221 }
222 
223 /*
224  * verify_and_output
225  *
226  * Builds and verifies the output key and value string
227  *
228  * It makes sure these rules are followed:
229  *	key + separator + value <= OUTPUTSIZ (for ndbm)
230  *	names <= MAXALIASES + 1, ie one canonical name + MAXALIASES aliases
231  * It will also ignore everything after a '#' comment character
232  */
233 static void
234 verify_and_output(const char *key, char *value, int lineno)
235 {
236 	char *p;			/* General char pointer */
237 	char *endp;			/* Points to the NULL at the end */
238 	char *namep;			/* First character of a name */
239 	char tmpbuf[OUTPUTSIZ+1];	/* Buffer before writing out */
240 	char *tmpbufp = tmpbuf;		/* Current point in output string */
241 	int n = 0;			/* Length of output */
242 	int names = 0;			/* Number of names found */
243 	int namelen;			/* Length of the name */
244 
245 	if (key) {		/* Just in case key is NULL */
246 		n = strlen(key);
247 		if (n > OUTPUTSIZ) {
248 			if (warning)
249 				fprintf(stderr,
250 				    "%s: address too long on "
251 				    "line %d, line discarded\n",
252 				    cmd, lineno);
253 			return;
254 		}
255 		memcpy(tmpbufp, key, n+1); /* Plus the '\0' */
256 		tmpbufp += n;
257 	}
258 
259 	if (value) {		/* Just in case value is NULL */
260 		p = value;
261 		if ((endp = strchr(value, '#')) == 0)	/* Ignore # comments */
262 			endp = p + strlen(p);		/* Or endp = EOL */
263 		do {
264 			/*
265 			 * Skip white space. Type conversion is
266 			 * necessary to avoid unfortunate effects of
267 			 * 8-bit characters appearing negative.
268 			 */
269 			while ((p < endp) && isspace((unsigned char)*p))
270 				p++;
271 
272 			if (p == endp)	/* End of the string */
273 				break;
274 
275 			names++;
276 			if (names > (MAXALIASES+1)) { /* cname + MAXALIASES */
277 				if (warning)
278 					fprintf(stderr,
279 					    "%s: Warning: too many "
280 					    "host names on line %d, "
281 					    "truncating\n",
282 					    cmd, lineno);
283 				break;
284 			}
285 
286 			namep = p;
287 			while ((p < endp) && !isspace((unsigned char)*p))
288 				p++;
289 
290 			namelen = p - namep;
291 			n += namelen + 1; /* single white space + name */
292 			*p = '\0';	   /* Terminate the name string */
293 			if (n > OUTPUTSIZ) {
294 				if (warning)
295 					fprintf(stderr,
296 					    "%s: Warning: %d byte ndbm limit "
297 					    "reached on line %d, truncating\n",
298 					    cmd, OUTPUTSIZ, lineno);
299 				break;
300 			}
301 
302 			if (names == 1) /* First space is a '\t' */
303 				*tmpbufp++ = '\t';
304 			else
305 				*tmpbufp++ = ' ';
306 
307 			memcpy(tmpbufp, namep, namelen+1); /* Plus the '\0' */
308 			tmpbufp += namelen;
309 
310 			if (p < endp)
311 				p++;	/* Skip the added NULL */
312 
313 		} while (p < endp);
314 	}
315 
316 	if (names > 0) {
317 		fputs(tmpbuf, stdout);
318 		fputc('\n', stdout);
319 	} else {
320 		if (warning)
321 			fprintf(stderr,
322 			    "%s: Warning: no host names on line %d, "
323 			    "ignored\n", cmd, lineno);
324 	}
325 }
326