xref: /freebsd/usr.bin/whois/whois.c (revision 7431dfd4580e850375fe5478d92ec770344db098)
1 /*
2  * Copyright (c) 1980, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1980, 1993\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35 
36 #if 0
37 #ifndef lint
38 static char sccsid[] = "@(#)whois.c	8.1 (Berkeley) 6/6/93";
39 #endif /* not lint */
40 #endif
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <sys/types.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <ctype.h>
50 #include <err.h>
51 #include <netdb.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <sysexits.h>
57 #include <unistd.h>
58 
59 #define	ABUSEHOST	"whois.abuse.net"
60 #define	NICHOST		"whois.crsnic.net"
61 #define	INICHOST	"whois.networksolutions.com"
62 #define	GNICHOST	"whois.nic.gov"
63 #define	ANICHOST	"whois.arin.net"
64 #define	LNICHOST	"whois.lacnic.net"
65 #define	KNICHOST	"whois.krnic.net"
66 #define	RNICHOST	"whois.ripe.net"
67 #define	PNICHOST	"whois.apnic.net"
68 #define	MNICHOST	"whois.ra.net"
69 #define	QNICHOST_TAIL	".whois-servers.net"
70 #define	BNICHOST	"whois.registro.br"
71 #define NORIDHOST	"whois.norid.no"
72 #define	IANAHOST	"whois.iana.org"
73 #define GERMNICHOST	"de.whois-servers.net"
74 #define FNICHOST	"whois.afrinic.net"
75 #define	DEFAULT_PORT	"whois"
76 #define	WHOIS_SERVER_ID	"Whois Server: "
77 #define	WHOIS_ORG_SERVER_ID	"Registrant Street1:Whois Server:"
78 
79 #define WHOIS_RECURSE		0x01
80 #define WHOIS_QUICK		0x02
81 
82 #define ishost(h) (isalnum((unsigned char)h) || h == '.' || h == '-')
83 
84 static const char *ip_whois[] = { LNICHOST, RNICHOST, PNICHOST, BNICHOST,
85 				  FNICHOST, NULL };
86 static const char *port = DEFAULT_PORT;
87 
88 static char *choose_server(char *);
89 static struct addrinfo *gethostinfo(char const *host, int exit_on_error);
90 static void s_asprintf(char **ret, const char *format, ...) __printflike(2, 3);
91 static void usage(void);
92 static void whois(const char *, const char *, int);
93 
94 int
95 main(int argc, char *argv[])
96 {
97 	const char *country, *host;
98 	char *qnichost;
99 	int ch, flags, use_qnichost;
100 
101 #ifdef	SOCKS
102 	SOCKSinit(argv[0]);
103 #endif
104 
105 	country = host = qnichost = NULL;
106 	flags = use_qnichost = 0;
107 	while ((ch = getopt(argc, argv, "aAbc:fgh:iIklmp:QrR6")) != -1) {
108 		switch (ch) {
109 		case 'a':
110 			host = ANICHOST;
111 			break;
112 		case 'A':
113 			host = PNICHOST;
114 			break;
115 		case 'b':
116 			host = ABUSEHOST;
117 			break;
118 		case 'c':
119 			country = optarg;
120 			break;
121 		case 'f':
122 			host = FNICHOST;
123 			break;
124 		case 'g':
125 			host = GNICHOST;
126 			break;
127 		case 'h':
128 			host = optarg;
129 			break;
130 		case 'i':
131 			host = INICHOST;
132 			break;
133 		case 'I':
134 			host = IANAHOST;
135 			break;
136 		case 'k':
137 			host = KNICHOST;
138 			break;
139 		case 'l':
140 			host = LNICHOST;
141 			break;
142 		case 'm':
143 			host = MNICHOST;
144 			break;
145 		case 'p':
146 			port = optarg;
147 			break;
148 		case 'Q':
149 			flags |= WHOIS_QUICK;
150 			break;
151 		case 'r':
152 			host = RNICHOST;
153 			break;
154 		case 'R':
155 			warnx("-R is deprecated; use '-c ru' instead");
156 			country = "ru";
157 			break;
158 		/* Remove in FreeBSD 10 */
159 		case '6':
160 			errx(EX_USAGE,
161 				"-6 is deprecated; use -[aAflr] instead");
162 			break;
163 		case '?':
164 		default:
165 			usage();
166 			/* NOTREACHED */
167 		}
168 	}
169 	argc -= optind;
170 	argv += optind;
171 
172 	if (!argc || (country != NULL && host != NULL))
173 		usage();
174 
175 	/*
176 	 * If no host or country is specified determine the top level domain
177 	 * from the query.  If the TLD is a number, query ARIN.  Otherwise, use
178 	 * TLD.whois-server.net.  If the domain does not contain '.', fall
179 	 * back to NICHOST.
180 	 */
181 	if (host == NULL && country == NULL) {
182 		if ((host = getenv("RA_SERVER")) == NULL) {
183 			use_qnichost = 1;
184 			host = NICHOST;
185 			if (!(flags & WHOIS_QUICK))
186 				flags |= WHOIS_RECURSE;
187 		}
188 	}
189 	while (argc-- > 0) {
190 		if (country != NULL) {
191 			s_asprintf(&qnichost, "%s%s", country, QNICHOST_TAIL);
192 			whois(*argv, qnichost, flags);
193 		} else if (use_qnichost)
194 			if ((qnichost = choose_server(*argv)) != NULL)
195 				whois(*argv, qnichost, flags);
196 		if (qnichost == NULL)
197 			whois(*argv, host, flags);
198 		free(qnichost);
199 		qnichost = NULL;
200 		argv++;
201 	}
202 	exit(0);
203 }
204 
205 /*
206  * This function will remove any trailing periods from domain, after which it
207  * returns a pointer to newly allocated memory containing the whois server to
208  * be queried, or a NULL if the correct server couldn't be determined.  The
209  * caller must remember to free(3) the allocated memory.
210  */
211 static char *
212 choose_server(char *domain)
213 {
214 	char *pos, *retval;
215 
216 	if (strchr(domain, ':')) {
217 		s_asprintf(&retval, "%s", ANICHOST);
218 		return (retval);
219 	}
220 	for (pos = strchr(domain, '\0'); pos > domain && *--pos == '.';)
221 		*pos = '\0';
222 	if (*domain == '\0')
223 		errx(EX_USAGE, "can't search for a null string");
224 	if (strlen(domain) > sizeof("-NORID")-1 &&
225 	    strcasecmp(domain + strlen(domain) - sizeof("-NORID") + 1,
226 		"-NORID") == 0) {
227 		s_asprintf(&retval, "%s", NORIDHOST);
228 		return (retval);
229 	}
230 	while (pos > domain && *pos != '.')
231 		--pos;
232 	if (pos <= domain)
233 		return (NULL);
234 	if (isdigit((unsigned char)*++pos))
235 		s_asprintf(&retval, "%s", ANICHOST);
236 	else
237 		s_asprintf(&retval, "%s%s", pos, QNICHOST_TAIL);
238 	return (retval);
239 }
240 
241 static struct addrinfo *
242 gethostinfo(char const *host, int exit_on_error)
243 {
244 	struct addrinfo hints, *res;
245 	int error;
246 
247 	memset(&hints, 0, sizeof(hints));
248 	hints.ai_flags = 0;
249 	hints.ai_family = AF_UNSPEC;
250 	hints.ai_socktype = SOCK_STREAM;
251 	error = getaddrinfo(host, port, &hints, &res);
252 	if (error) {
253 		warnx("%s: %s", host, gai_strerror(error));
254 		if (exit_on_error)
255 			exit(EX_NOHOST);
256 		return (NULL);
257 	}
258 	return (res);
259 }
260 
261 /*
262  * Wrapper for asprintf(3) that exits on error.
263  */
264 static void
265 s_asprintf(char **ret, const char *format, ...)
266 {
267 	va_list ap;
268 
269 	va_start(ap, format);
270 	if (vasprintf(ret, format, ap) == -1) {
271 		va_end(ap);
272 		err(EX_OSERR, "vasprintf()");
273 	}
274 	va_end(ap);
275 }
276 
277 static void
278 whois(const char *query, const char *hostname, int flags)
279 {
280 	FILE *fp;
281 	struct addrinfo *hostres, *res;
282 	char *buf, *host, *nhost, *p;
283 	int i, s;
284 	size_t c, len;
285 
286 	s = -1;
287 	hostres = gethostinfo(hostname, 1);
288 	for (res = hostres; res; res = res->ai_next) {
289 		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
290 		if (s < 0)
291 			continue;
292 		if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
293 			break;
294 		close(s);
295 	}
296 	freeaddrinfo(hostres);
297 	if (res == NULL)
298 		err(EX_OSERR, "connect()");
299 
300 	fp = fdopen(s, "r+");
301 	if (fp == NULL)
302 		err(EX_OSERR, "fdopen()");
303 	if (strcmp(hostname, GERMNICHOST) == 0) {
304 		fprintf(fp, "-T dn,ace -C US-ASCII %s\r\n", query);
305 	} else if (strcmp(hostname, "dk" QNICHOST_TAIL) == 0) {
306 		fprintf(fp, "--show-handles %s\r\n", query);
307 	} else {
308 		fprintf(fp, "%s\r\n", query);
309 	}
310 	fflush(fp);
311 	nhost = NULL;
312 	while ((buf = fgetln(fp, &len)) != NULL) {
313 		while (len > 0 && isspace((unsigned char)buf[len - 1]))
314 			buf[--len] = '\0';
315 		printf("%.*s\n", (int)len, buf);
316 
317 		if ((flags & WHOIS_RECURSE) && nhost == NULL) {
318 			host = strnstr(buf, WHOIS_SERVER_ID, len);
319 			if (host != NULL) {
320 				host += sizeof(WHOIS_SERVER_ID) - 1;
321 				for (p = host; p < buf + len; p++) {
322 					if (!ishost(*p)) {
323 						*p = '\0';
324 						break;
325 					}
326 				}
327 				s_asprintf(&nhost, "%.*s",
328 				     (int)(buf + len - host), host);
329 			} else if ((host =
330 			    strnstr(buf, WHOIS_ORG_SERVER_ID, len)) != NULL) {
331 				host += sizeof(WHOIS_ORG_SERVER_ID) - 1;
332 				for (p = host; p < buf + len; p++) {
333 					if (!ishost(*p)) {
334 						*p = '\0';
335 						break;
336 					}
337 				}
338 				s_asprintf(&nhost, "%.*s",
339 				    (int)(buf + len - host), host);
340 			} else if (strcmp(hostname, ANICHOST) == 0) {
341 				for (c = 0; c <= len; c++)
342 					buf[c] = tolower((unsigned char)buf[c]);
343 				for (i = 0; ip_whois[i] != NULL; i++) {
344 					if (strnstr(buf, ip_whois[i], len) !=
345 					    NULL) {
346 						s_asprintf(&nhost, "%s",
347 						    ip_whois[i]);
348 						break;
349 					}
350 				}
351 			}
352 		}
353 	}
354 	fclose(fp);
355 	if (nhost != NULL) {
356 		whois(query, nhost, 0);
357 		free(nhost);
358 	}
359 }
360 
361 static void
362 usage(void)
363 {
364 	fprintf(stderr,
365 	    "usage: whois [-aAbfgiIklmQrR6] [-c country-code | -h hostname] "
366 	    "[-p port] name ...\n");
367 	exit(EX_USAGE);
368 }
369