1/*	$NetBSD: getaddrinfo.c,v 1.4 2014/04/22 02:23:03 ginsbach Exp $	*/
2
3/*-
4 * Copyright (c) 2013 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Taylor R. Campbell.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#include <sys/types.h>
33#include <sys/socket.h>
34
35#include <assert.h>
36#include <err.h>
37#include <errno.h>
38#include <limits.h>
39#include <netdb.h>
40#include <stdbool.h>
41#include <stdint.h>
42#include <stdlib.h>
43#include <stdio.h>
44#include <string.h>
45#include <unistd.h>
46#include <util.h>
47
48#include "tables.h"
49
50static void	usage(void) __dead;
51static void	printaddrinfo(struct addrinfo *);
52static bool	parse_af(const char *, int *);
53static bool	parse_protocol(const char *, int *);
54static bool	parse_socktype(const char *, int *);
55static bool	parse_numeric_tabular(const char *, int *, const char *const *,
56		    size_t);
57
58int
59main(int argc, char **argv)
60{
61	static const struct addrinfo zero_addrinfo;
62	struct addrinfo hints = zero_addrinfo;
63	struct addrinfo *addrinfo;
64	const char *hostname = NULL, *service = NULL;
65	int ch;
66	int error;
67
68	setprogname(argv[0]);
69
70	hints.ai_family = AF_UNSPEC;
71	hints.ai_socktype = 0;
72	hints.ai_protocol = 0;
73	hints.ai_flags = 0;
74
75	while ((ch = getopt(argc, argv, "cf:nNp:Ps:t:")) != -1) {
76		switch (ch) {
77		case 'c':
78			hints.ai_flags |= AI_CANONNAME;
79			break;
80
81		case 'f':
82			if (!parse_af(optarg, &hints.ai_family)) {
83				warnx("invalid address family: %s", optarg);
84				usage();
85			}
86			break;
87
88		case 'n':
89			hints.ai_flags |= AI_NUMERICHOST;
90			break;
91
92		case 'N':
93			hints.ai_flags |= AI_NUMERICSERV;
94			break;
95
96		case 's':
97			service = optarg;
98			break;
99
100		case 'p':
101			if (!parse_protocol(optarg, &hints.ai_protocol)) {
102				warnx("invalid protocol: %s", optarg);
103				usage();
104			}
105			break;
106
107		case 'P':
108			hints.ai_flags |= AI_PASSIVE;
109			break;
110
111		case 't':
112			if (!parse_socktype(optarg, &hints.ai_socktype)) {
113				warnx("invalid socket type: %s", optarg);
114				usage();
115			}
116			break;
117
118		case '?':
119		default:
120			usage();
121		}
122	}
123
124	argc -= optind;
125	argv += optind;
126
127	if (!((argc == 1) || ((argc == 0) && (hints.ai_flags & AI_PASSIVE))))
128		usage();
129	if (argc == 1)
130		hostname = argv[0];
131
132	if (service != NULL) {
133		char *p;
134
135		if ((p = strchr(service, '/')) != NULL) {
136			if (hints.ai_protocol != 0) {
137				warnx("protocol already specified");
138				usage();
139			}
140			*p = '\0';
141			p++;
142
143			if (!parse_protocol(p, &hints.ai_protocol)) {
144				warnx("invalid protocol: %s", p);
145				usage();
146			}
147		}
148	}
149
150	error = getaddrinfo(hostname, service, &hints, &addrinfo);
151	if (error)
152		errx(1, "%s", gai_strerror(error));
153
154	if ((hints.ai_flags & AI_CANONNAME) && (addrinfo != NULL)) {
155		if (printf("canonname %s\n", addrinfo->ai_canonname) < 0)
156			err(1, "printf");
157	}
158
159	printaddrinfo(addrinfo);
160
161	freeaddrinfo(addrinfo);
162
163	return 0;
164}
165
166static void __dead
167usage(void)
168{
169
170	(void)fprintf(stderr, "Usage: %s", getprogname());
171	(void)fprintf(stderr,
172	    " [-f <family>] [-p <protocol>] [-t <socktype>] [-s <service>]\n");
173	(void)fprintf(stderr, "   [-cnNP] [<hostname>]\n");
174	exit(1);
175}
176
177static bool
178parse_af(const char *string, int *afp)
179{
180
181	return parse_numeric_tabular(string, afp, address_families,
182	    __arraycount(address_families));
183}
184
185static bool
186parse_protocol(const char *string, int *protop)
187{
188	struct protoent *protoent;
189	char *end;
190	long value;
191
192	errno = 0;
193	value = strtol(string, &end, 0);
194	if ((string[0] == '\0') || (*end != '\0'))
195		goto numeric_failed;
196	if ((errno == ERANGE) && ((value == LONG_MAX) || (value == LONG_MIN)))
197		goto numeric_failed;
198	if ((value > INT_MAX) || (value < INT_MIN))
199		goto numeric_failed;
200
201	*protop = value;
202	return true;
203
204numeric_failed:
205	protoent = getprotobyname(string);
206	if (protoent == NULL)
207		goto protoent_failed;
208
209	*protop = protoent->p_proto;
210	return true;
211
212protoent_failed:
213	return false;
214}
215
216static bool
217parse_socktype(const char *string, int *typep)
218{
219
220	return parse_numeric_tabular(string, typep, socket_types,
221	    __arraycount(socket_types));
222}
223
224static bool
225parse_numeric_tabular(const char *string, int *valuep,
226    const char *const *table, size_t n)
227{
228	char *end;
229	long value;
230	size_t i;
231
232	assert((uintmax_t)n <= (uintmax_t)INT_MAX);
233
234	errno = 0;
235	value = strtol(string, &end, 0);
236	if ((string[0] == '\0') || (*end != '\0'))
237		goto numeric_failed;
238	if ((errno == ERANGE) && ((value == LONG_MAX) || (value == LONG_MIN)))
239		goto numeric_failed;
240	if ((value > INT_MAX) || (value < INT_MIN))
241		goto numeric_failed;
242
243	*valuep = value;
244	return true;
245
246numeric_failed:
247	for (i = 0; i < n; i++)
248		if ((table[i] != NULL) && (strcmp(string, table[i]) == 0))
249			break;
250	if (i == n)
251		goto table_failed;
252	*valuep = i;
253	return true;
254
255table_failed:
256	return false;
257}
258
259static void
260printaddrinfo(struct addrinfo *addrinfo)
261{
262	struct addrinfo *ai;
263	char buf[1024];
264	int n;
265	struct protoent *protoent;
266
267	for (ai = addrinfo; ai != NULL; ai = ai->ai_next) {
268		/* Print the socket type.  */
269		if ((ai->ai_socktype >= 0) &&
270		    ((size_t)ai->ai_socktype < __arraycount(socket_types)) &&
271		    (socket_types[ai->ai_socktype] != NULL))
272			n = printf("%s", socket_types[ai->ai_socktype]);
273		else
274			n = printf("%d", ai->ai_socktype);
275		if (n < 0)
276			err(1, "printf");
277
278		/* Print the address family.  */
279		if ((ai->ai_family >= 0) &&
280		    ((size_t)ai->ai_family < __arraycount(address_families)) &&
281		    (address_families[ai->ai_family] != NULL))
282			n = printf(" %s", address_families[ai->ai_family]);
283		else
284			n = printf(" %d", ai->ai_family);
285		if (n < 0)
286			err(1, "printf");
287
288		/* Print the protocol number.  */
289		protoent = getprotobynumber(ai->ai_protocol);
290		if (protoent == NULL)
291			n = printf(" %d", ai->ai_protocol);
292		else
293			n = printf(" %s", protoent->p_name);
294		if (n < 0)
295			err(1, "printf");
296
297		/* Format the sockaddr.  */
298		switch (ai->ai_family) {
299		case AF_INET:
300		case AF_INET6:
301			n = sockaddr_snprintf(buf, sizeof(buf), " %a %p",
302			    ai->ai_addr);
303			break;
304
305		default:
306			n = sockaddr_snprintf(buf, sizeof(buf),
307			    "%a %p %I %F %R %S", ai->ai_addr);
308		}
309
310		/*
311		 * Check for sockaddr_snprintf failure.
312		 *
313		 * XXX sockaddr_snprintf's error reporting is botched
314		 * -- man page says it sets errno, but if getnameinfo
315		 * fails, errno is not where it reports the error...
316		 */
317		if (n < 0) {
318			warnx("sockaddr_snprintf failed");
319			continue;
320		}
321		if (sizeof(buf) <= (size_t)n)
322			warnx("truncated sockaddr_snprintf output");
323
324		/* Print the formatted sockaddr.  */
325		if (printf("%s\n", buf) < 0)
326			err(1, "printf");
327	}
328}
329