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