1 /*	$OpenBSD: rtquery.c,v 1.17 2005/04/12 15:26:47 cloder Exp $	*/
2 
3 /*-
4  * Copyright (c) 1982, 1986, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 char copyright[] =
33 "@(#) Copyright (c) 1982, 1986, 1993\n\
34 	The Regents of the University of California.  All rights reserved.\n";
35 
36 #if !defined(lint)
37 static char sccsid[] = "@(#)query.c	8.1 (Berkeley) 6/5/93";
38 #endif
39 
40 #include <sys/cdefs.h>
41 #include <sys/param.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/time.h>
45 #include <netinet/in.h>
46 #define RIPVERSION RIPv2
47 #include <protocols/routed.h>
48 #include <arpa/inet.h>
49 #include <netdb.h>
50 #include <errno.h>
51 #include <unistd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #ifdef sgi
56 #include <strings.h>
57 #include <bstring.h>
58 #endif
59 
60 #ifndef sgi
61 #define _HAVE_SIN_LEN
62 #endif
63 
64 #define	WTIME	15		/* Time to wait for all responses */
65 #define	STIME	(250*1000)	/* usec to wait for another response */
66 
67 int	s;
68 
69 char	*pgmname;
70 
71 union {
72 	struct rip rip;
73 	char	packet[MAXPACKETSIZE+MAXPATHLEN];
74 } omsg_buf;
75 #define OMSG omsg_buf.rip
76 int omsg_len = sizeof(struct rip);
77 
78 union {
79 	struct	rip rip;
80 	char	packet[MAXPACKETSIZE+1024];
81 	} imsg_buf;
82 #define IMSG imsg_buf.rip
83 
84 int	nflag;				/* numbers, no names */
85 int	pflag;				/* play the `gated` game */
86 int	ripv2 = 1;			/* use RIP version 2 */
87 int	wtime = WTIME;
88 int	rflag;				/* 1=ask about a particular route */
89 int	trace;
90 int	not_trace;
91 
92 struct timeval sent;			/* when query sent */
93 
94 static void rip_input(struct sockaddr_in*, int);
95 static int out(char *);
96 static void trace_loop(char *argv[]);
97 static void query_loop(char *argv[], int);
98 static int getnet(char *, struct netinfo *);
99 static u_int std_mask(u_int);
100 
101 
102 int
main(int argc,char * argv[])103 main(int argc, char *argv[])
104 {
105 	int ch, bsize;
106 	char *p, *options, *value;
107 
108 	OMSG.rip_nets[0].n_dst = RIP_DEFAULT;
109 	OMSG.rip_nets[0].n_family = RIP_AF_UNSPEC;
110 	OMSG.rip_nets[0].n_metric = htonl(HOPCNT_INFINITY);
111 
112 	pgmname = argv[0];
113 	while ((ch = getopt(argc, argv, "np1w:r:t:")) != -1)
114 		switch (ch) {
115 		case 'n':
116 			not_trace = 1;
117 			nflag = 1;
118 			break;
119 
120 		case 'p':
121 			not_trace = 1;
122 			pflag = 1;
123 			break;
124 
125 		case '1':
126 			ripv2 = 0;
127 			break;
128 
129 		case 'w':
130 			not_trace = 1;
131 			wtime = (int)strtoul(optarg, &p, 0);
132 			if (*p != '\0'
133 			    || wtime <= 0)
134 				goto usage;
135 			break;
136 
137 		case 'r':
138 			not_trace = 1;
139 			if (rflag)
140 				goto usage;
141 			rflag = getnet(optarg, &OMSG.rip_nets[0]);
142 			if (!rflag) {
143 				struct hostent *hp = gethostbyname(optarg);
144 				if (hp == 0) {
145 					fprintf(stderr, "%s: %s:",
146 						pgmname, optarg);
147 					herror(0);
148 					exit(1);
149 				}
150 				memmove(&OMSG.rip_nets[0].n_dst, hp->h_addr,
151 				      sizeof(OMSG.rip_nets[0].n_dst));
152 				OMSG.rip_nets[0].n_family = RIP_AF_INET;
153 				OMSG.rip_nets[0].n_mask = -1;
154 				rflag = 1;
155 			}
156 			break;
157 
158 		case 't':
159 			trace = 1;
160 			options = optarg;
161 			while (*options != '\0') {
162 				char *traceopts[] = {
163 #				    define TRACE_ON	0
164 					"on",
165 #				    define TRACE_MORE	1
166 					"more",
167 #				    define TRACE_OFF	2
168 					"off",
169 #				    define TRACE_DUMP	3
170 					"dump",
171 					0
172 				};
173 				switch (getsubopt(&options,traceopts,&value)) {
174 				case TRACE_ON:
175 					OMSG.rip_cmd = RIPCMD_TRACEON;
176 					if (!value
177 					    || strlen(value) > MAXPATHLEN)
178 						goto usage;
179 					break;
180 				case TRACE_MORE:
181 					if (value)
182 						goto usage;
183 					OMSG.rip_cmd = RIPCMD_TRACEON;
184 					value = "";
185 					break;
186 				case TRACE_OFF:
187 					if (value)
188 						goto usage;
189 					OMSG.rip_cmd = RIPCMD_TRACEOFF;
190 					value = "";
191 					break;
192 				case TRACE_DUMP:
193 					if (value)
194 						goto usage;
195 					OMSG.rip_cmd = RIPCMD_TRACEON;
196 					value = "dump/../table";
197 					break;
198 				default:
199 					goto usage;
200 				}
201 				strlcpy((char*)OMSG.rip_tracefile, value,
202 				    (char*)&omsg_buf + sizeof omsg_buf -
203 				    (char*)OMSG.rip_tracefile);
204 				omsg_len += strlen(value) - sizeof(OMSG.ripun);
205 			}
206 			break;
207 
208 		default:
209 			goto usage;
210 	}
211 	argv += optind;
212 	argc -= optind;
213 	if ((not_trace && trace) || argc == 0) {
214 usage:		fprintf(stderr, "%s: [-1np] [-r addr] [-t op] [-w timeout]"
215 		    " host ...\n",
216 		    pgmname);
217 		exit(1);
218 	}
219 
220 	s = socket(AF_INET, SOCK_DGRAM, 0);
221 	if (s < 0) {
222 		perror("socket");
223 		exit(2);
224 	}
225 
226 	/* be prepared to receive a lot of routes */
227 	for (bsize = 127*1024; ; bsize -= 1024) {
228 		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
229 		    &bsize, sizeof(bsize)) == 0)
230 			break;
231 		if (bsize <= 4*1024) {
232 			perror("setsockopt SO_RCVBUF");
233 			break;
234 		}
235 	}
236 
237 	if (trace)
238 		trace_loop(argv);
239 	else
240 		query_loop(argv, argc);
241 	/* NOTREACHED */
242 }
243 
244 
245 /* tell the target hosts about tracing
246  */
247 static void
trace_loop(char * argv[])248 trace_loop(char *argv[])
249 {
250 	struct sockaddr_in myaddr;
251 	int res;
252 
253 	if (geteuid() != 0) {
254 		(void)fprintf(stderr, "-t requires UID 0\n");
255 		exit(1);
256 	}
257 
258 	if (ripv2) {
259 		OMSG.rip_vers = RIPv2;
260 	} else {
261 		OMSG.rip_vers = RIPv1;
262 	}
263 
264 	bzero(&myaddr, sizeof(myaddr));
265 	myaddr.sin_family = AF_INET;
266 #ifdef _HAVE_SIN_LEN
267 	myaddr.sin_len = sizeof(myaddr);
268 #endif
269 	myaddr.sin_port = htons(IPPORT_RESERVED-1);
270 	while (bind(s, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
271 		if (errno != EADDRINUSE || myaddr.sin_port == 0) {
272 			perror("bind");
273 			exit(2);
274 		}
275 		myaddr.sin_port = htons(ntohs(myaddr.sin_port)-1);
276 	}
277 
278 	res = 1;
279 	while (*argv != 0) {
280 		if (out(*argv++) <= 0)
281 			res = 0;
282 	}
283 	exit(res);
284 }
285 
286 
287 /* query all of the listed hosts
288  */
289 static void
query_loop(char * argv[],int argc)290 query_loop(char *argv[], int argc)
291 {
292 	struct seen {
293 		struct seen *next;
294 		struct in_addr addr;
295 	} *seen, *sp;
296 	int answered = 0;
297 	int cc;
298 	fd_set bits;
299 	struct timeval now, delay;
300 	struct sockaddr_in from;
301 	socklen_t fromlen;
302 
303 	OMSG.rip_cmd = (pflag) ? RIPCMD_POLL : RIPCMD_REQUEST;
304 	if (ripv2) {
305 		OMSG.rip_vers = RIPv2;
306 	} else {
307 		OMSG.rip_vers = RIPv1;
308 		OMSG.rip_nets[0].n_mask = 0;
309 	}
310 
311 	/* ask the first (valid) host */
312 	seen = 0;
313 	while (0 > out(*argv++)) {
314 		if (*argv == 0)
315 			exit(1);
316 		answered++;
317 	}
318 
319 	FD_ZERO(&bits);
320 	for (;;) {
321 		FD_SET(s, &bits);
322 		delay.tv_sec = 0;
323 		delay.tv_usec = STIME;
324 		cc = select(s+1, &bits, 0,0, &delay);
325 		if (cc > 0) {
326 			fromlen = sizeof(from);
327 			cc = recvfrom(s, imsg_buf.packet,
328 			    sizeof(imsg_buf.packet), 0,
329 			    (struct sockaddr *)&from, &fromlen);
330 			if (cc < 0) {
331 				perror("recvfrom");
332 				exit(1);
333 			}
334 
335 			/*
336 			 * count the distinct responding hosts.
337 			 * You cannot match responding hosts with
338 			 * addresses to which queries were transmitted,
339 			 * because a router might respond with a
340 			 * different source address.
341 			 */
342 			for (sp = seen; sp != 0; sp = sp->next) {
343 				if (sp->addr.s_addr == from.sin_addr.s_addr)
344 					break;
345 			}
346 			if (sp == 0) {
347 				sp = malloc(sizeof(*sp));
348 				sp->addr = from.sin_addr;
349 				sp->next = seen;
350 				seen = sp;
351 				answered++;
352 			}
353 
354 			rip_input(&from, cc);
355 			continue;
356 		}
357 
358 		if (cc < 0) {
359 			if ( errno == EINTR)
360 				continue;
361 			perror("select");
362 			exit(1);
363 		}
364 
365 		/* After a pause in responses, probe another host.
366 		 * This reduces the intermingling of answers.
367 		 */
368 		while (*argv != 0 && 0 > out(*argv++))
369 			answered++;
370 
371 		/* continue until no more packets arrive
372 		 * or we have heard from all hosts
373 		 */
374 		if (answered >= argc)
375 			break;
376 
377 		/* or until we have waited a long time
378 		 */
379 		if (gettimeofday(&now, 0) < 0) {
380 			perror("gettimeofday(now)");
381 			exit(1);
382 		}
383 		if (sent.tv_sec + wtime <= now.tv_sec)
384 			break;
385 	}
386 
387 	/* fail if there was no answer */
388 	exit (answered >= argc ? 0 : 1);
389 }
390 
391 
392 /* sent do one host
393  */
394 static int
out(char * host)395 out(char *host)
396 {
397 	struct sockaddr_in router;
398 	struct hostent *hp;
399 
400 	if (gettimeofday(&sent, 0) < 0) {
401 		perror("gettimeofday(sent)");
402 		return -1;
403 	}
404 
405 	bzero(&router, sizeof(router));
406 	router.sin_family = AF_INET;
407 #ifdef _HAVE_SIN_LEN
408 	router.sin_len = sizeof(router);
409 #endif
410 	if (!inet_aton(host, &router.sin_addr)) {
411 		hp = gethostbyname(host);
412 		if (hp == 0) {
413 			herror(host);
414 			return -1;
415 		}
416 		memmove(&router.sin_addr, hp->h_addr, sizeof(router.sin_addr));
417 	}
418 	router.sin_port = htons(RIP_PORT);
419 
420 	if (sendto(s, &omsg_buf, omsg_len, 0,
421 	    (struct sockaddr *)&router, sizeof(router)) < 0) {
422 		perror(host);
423 		return -1;
424 	}
425 
426 	return 0;
427 }
428 
429 
430 /*
431  * Handle an incoming RIP packet.
432  */
433 static void
rip_input(struct sockaddr_in * from,int size)434 rip_input(struct sockaddr_in *from,
435 	  int size)
436 {
437 	struct netinfo *n, *lim;
438 	struct in_addr in;
439 	char *name;
440 	char net_buf[80];
441 	u_int mask, dmask;
442 	char *sp;
443 	int i;
444 	struct hostent *hp;
445 	struct netent *np;
446 	struct netauth *a;
447 
448 	if (nflag) {
449 		printf("%s:", inet_ntoa(from->sin_addr));
450 	} else {
451 		hp = gethostbyaddr((char*)&from->sin_addr,
452 		    sizeof(struct in_addr), AF_INET);
453 		if (hp == 0) {
454 			printf("%s:", inet_ntoa(from->sin_addr));
455 		} else {
456 			printf("%s (%s):", hp->h_name,
457 			    inet_ntoa(from->sin_addr));
458 		}
459 	}
460 	if (IMSG.rip_cmd != RIPCMD_RESPONSE) {
461 		printf("\n    unexpected response type %d\n", IMSG.rip_cmd);
462 		return;
463 	}
464 	printf(" RIPv%d%s %d bytes\n", IMSG.rip_vers,
465 	    (IMSG.rip_vers != RIPv1 && IMSG.rip_vers != RIPv2) ? " ?" : "",
466 	    size);
467 	if (size > MAXPACKETSIZE) {
468 		if (size > sizeof(imsg_buf) - sizeof(*n)) {
469 			printf("       at least %d bytes too long\n",
470 			    size-MAXPACKETSIZE);
471 			size = sizeof(imsg_buf) - sizeof(*n);
472 		} else {
473 			printf("       %d bytes too long\n",
474 			    size-MAXPACKETSIZE);
475 		}
476 	} else if (size%sizeof(*n) != sizeof(struct rip)%sizeof(*n)) {
477 		printf("    response of bad length=%d\n", size);
478 	}
479 
480 	n = IMSG.rip_nets;
481 	lim = (struct netinfo *)((char*)n + size) - 1;
482 	for (; n <= lim; n++) {
483 		name = "";
484 		if (n->n_family == RIP_AF_INET) {
485 			in.s_addr = n->n_dst;
486 			(void)strlcpy(net_buf, inet_ntoa(in), sizeof(net_buf));
487 
488 			mask = ntohl(n->n_mask);
489 			dmask = mask & -mask;
490 			if (mask != 0) {
491 				sp = &net_buf[strlen(net_buf)];
492 				if (IMSG.rip_vers == RIPv1) {
493 					snprintf(sp,
494 					    net_buf + sizeof net_buf - sp,
495 					    " mask=%#x ? ",mask);
496 					mask = 0;
497 				} else if (mask + dmask == 0) {
498 					for (i = 0;
499 					    (i != 32 && ((1<<i)&mask) == 0);
500 					    i++)
501 						continue;
502 					snprintf(sp,
503 					    net_buf + sizeof net_buf - sp,
504 					    "/%d",32-i);
505 				} else
506 					snprintf(sp,
507 					    net_buf + sizeof net_buf - sp,
508 					    " (mask %#x)", mask);
509 			}
510 
511 			if (!nflag) {
512 				if (mask == 0) {
513 					mask = std_mask(in.s_addr);
514 					if ((ntohl(in.s_addr) & ~mask) != 0)
515 						mask = 0;
516 				}
517 				/* Without a netmask, do not worry about
518 				 * whether the destination is a host or a
519 				 * network. Try both and use the first name
520 				 * we get.
521 				 *
522 				 * If we have a netmask we can make a
523 				 * good guess.
524 				 */
525 				if ((in.s_addr & ~mask) == 0) {
526 					np = getnetbyaddr(in.s_addr,
527 							  AF_INET);
528 					if (np != 0)
529 						name = np->n_name;
530 					else if (in.s_addr == 0)
531 						name = "default";
532 				}
533 				if (name[0] == '\0' &&
534 				    ((in.s_addr & ~mask) != 0 ||
535 				    mask == 0xffffffff)) {
536 					hp = gethostbyaddr((char*)&in,
537 					    sizeof(in), AF_INET);
538 					if (hp != 0)
539 						name = hp->h_name;
540 				}
541 			}
542 
543 		} else if (n->n_family == RIP_AF_AUTH) {
544 			a = (struct netauth*)n;
545 			(void)printf("    authentication type %d: ",
546 			    a->a_type);
547 			for (i = 0; i < sizeof(a->au.au_pw); i++)
548 				(void)printf("%02x ", a->au.au_pw[i]);
549 			putc('\n', stdout);
550 			continue;
551 
552 		} else {
553 			snprintf(net_buf, sizeof net_buf,
554 			    "(af %#x) %d.%d.%d.%d",
555 			    ntohs(n->n_family),
556 			    (char)(n->n_dst >> 24),
557 			    (char)(n->n_dst >> 16),
558 			    (char)(n->n_dst >> 8),
559 			    (char)n->n_dst);
560 		}
561 
562 		(void)printf("  %-18s metric %2d %-10s",
563 		    net_buf, ntohl(n->n_metric), name);
564 
565 		if (n->n_nhop != 0) {
566 			in.s_addr = n->n_nhop;
567 			if (nflag)
568 				hp = 0;
569 			else
570 				hp = gethostbyaddr((char*)&in, sizeof(in),
571 				    AF_INET);
572 			(void)printf(" nhop=%-15s%s",
573 			    (hp != 0) ? hp->h_name : inet_ntoa(in),
574 			    (IMSG.rip_vers == RIPv1) ? " ?" : "");
575 		}
576 		if (n->n_tag != 0)
577 			(void)printf(" tag=%#x%s", n->n_tag,
578 			    (IMSG.rip_vers == RIPv1) ? " ?" : "");
579 		putc('\n', stdout);
580 	}
581 }
582 
583 
584 /* Return the classical netmask for an IP address.
585  */
586 static u_int
std_mask(u_int addr)587 std_mask(u_int addr)			/* in network order */
588 {
589 	NTOHL(addr);			/* was a host, not a network */
590 
591 	if (addr == 0)			/* default route has mask 0 */
592 		return 0;
593 	if (IN_CLASSA(addr))
594 		return IN_CLASSA_NET;
595 	if (IN_CLASSB(addr))
596 		return IN_CLASSB_NET;
597 	return IN_CLASSC_NET;
598 }
599 
600 
601 /* get a network number as a name or a number, with an optional "/xx"
602  * netmask.
603  */
604 static int				/* 0=bad */
getnet(char * name,struct netinfo * rt)605 getnet(char *name,
606        struct netinfo *rt)
607 {
608 	int i;
609 	struct netent *nentp;
610 	u_int mask;
611 	struct in_addr in;
612 	char hname[MAXHOSTNAMELEN+1];
613 	char *mname, *p;
614 
615 	/* Detect and separate "1.2.3.4/24" */
616 	if (0 != (mname = strrchr(name,'/'))) {
617 		i = (int)(mname - name);
618 		if (i > sizeof(hname)-1)	/* name too long */
619 			return 0;
620 		memmove(hname, name, i);
621 		hname[i] = '\0';
622 		mname++;
623 		name = hname;
624 	}
625 
626 	nentp = getnetbyname(name);
627 	if (nentp != 0) {
628 		in.s_addr = nentp->n_net;
629 	} else if (inet_aton(name, &in) == 1) {
630 		NTOHL(in.s_addr);
631 	} else {
632 		return 0;
633 	}
634 
635 	if (mname == 0) {
636 		mask = std_mask(in.s_addr);
637 		if ((~mask & in.s_addr) != 0)
638 			mask = 0xffffffff;
639 	} else {
640 		mask = (u_int)strtoul(mname, &p, 0);
641 		if (*p != '\0' || mask > 32)
642 			return 0;
643 		mask = 0xffffffff << (32-mask);
644 	}
645 
646 	rt->n_dst = htonl(in.s_addr);
647 	rt->n_family = RIP_AF_INET;
648 	rt->n_mask = htonl(mask);
649 	return 1;
650 }
651