xref: /netbsd-src/sbin/routed/rtquery/rtquery.c (revision 4db4c6282f108255e2041d1e6ea0773fa031a821)
1 /*	$NetBSD: rtquery.c,v 1.25 2014/03/23 05:36:58 dholland 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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgment:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #include <sys/param.h>
38 #include <sys/protosw.h>
39 #include <sys/socket.h>
40 #include <sys/time.h>
41 #include <netinet/in.h>
42 #define RIPVERSION RIPv2
43 #include <protocols/routed.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #ifdef sgi
52 #include <strings.h>
53 #include <bstring.h>
54 #endif
55 
56 #define UNUSED __unused
57 #ifndef __RCSID
58 #define __RCSID(_s) static const char rcsid[] UNUSED = _s
59 #endif
60 #ifndef __COPYRIGHT
61 #define __COPYRIGHT(_s) static const char copyright[] UNUSED = _s
62 #endif
63 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993\
64  The Regents of the University of California.  All rights reserved.");
65 #ifdef __NetBSD__
66 __RCSID("$NetBSD: rtquery.c,v 1.25 2014/03/23 05:36:58 dholland Exp $");
67 #elif defined(__FreeBSD__)
68 __RCSID("$FreeBSD$");
69 #else
70 __RCSID("Revision: 2.26 ");
71 #ident "Revision: 2.26 "
72 #endif
73 
74 #ifndef sgi
75 #define _HAVE_SIN_LEN
76 #endif
77 
78 #ifdef __NetBSD__
79 #include <md5.h>
80 #else
81 #define MD5_DIGEST_LEN 16
82 typedef struct {
83 	u_int32_t state[4];		/* state (ABCD) */
84 	u_int32_t count[2];		/* # of bits, modulo 2^64 (LSB 1st) */
85 	unsigned char buffer[64];	/* input buffer */
86 } MD5_CTX;
87 extern void MD5Init(MD5_CTX*);
88 extern void MD5Update(MD5_CTX*, u_char*, u_int);
89 extern void MD5Final(u_char[MD5_DIGEST_LEN], MD5_CTX*);
90 #endif
91 
92 
93 #define	WTIME	15		/* Time to wait for all responses */
94 #define	STIME	(250*1000)	/* usec to wait for another response */
95 
96 int	soc;
97 
98 const char *pgmname;
99 
100 union {
101 	struct rip rip;
102 	char	packet[MAXPACKETSIZE+MAXPATHLEN];
103 } omsg_buf;
104 #define OMSG omsg_buf.rip
105 int omsg_len = sizeof(struct rip);
106 
107 union {
108 	struct	rip rip;
109 	char	packet[MAXPACKETSIZE+1024];
110 	} imsg_buf;
111 #define IMSG imsg_buf.rip
112 
113 int	nflag;				/* numbers, no names */
114 int	pflag;				/* play the `gated` game */
115 int	ripv2 = 1;			/* use RIP version 2 */
116 int	wtime = WTIME;
117 int	rflag;				/* 1=ask about a particular route */
118 int	trace, not_trace;		/* send trace command or not */
119 int	auth_type = RIP_AUTH_NONE;
120 char	passwd[RIP_AUTH_PW_LEN];
121 u_long	keyid;
122 
123 struct timeval sent;			/* when query sent */
124 
125 static char localhost_str[] = "localhost";
126 static char *default_argv[] = {localhost_str, 0};
127 
128 static void rip_input(struct sockaddr_in*, int);
129 static int out(const char *);
130 static void trace_loop(char *argv[]) __dead;
131 static void query_loop(char *argv[], int) __dead;
132 static int getnet(char *, struct netinfo *);
133 static u_int std_mask(u_int);
134 static int parse_quote(char **, const char *, char *, char *, int);
135 __dead static void usage(void);
136 
137 
138 int
main(int argc,char * argv[])139 main(int argc,
140      char *argv[])
141 {
142 	int ch, bsize;
143 	char *p, *options, *value, delim;
144 	const char *result;
145 
146 	delim = 0;	/* XXX gcc */
147 
148 	OMSG.rip_nets[0].n_dst = RIP_DEFAULT;
149 	OMSG.rip_nets[0].n_family = RIP_AF_UNSPEC;
150 	OMSG.rip_nets[0].n_metric = htonl(HOPCNT_INFINITY);
151 
152 	pgmname = argv[0];
153 	while ((ch = getopt(argc, argv, "np1w:r:t:a:")) != -1)
154 		switch (ch) {
155 		case 'n':
156 			not_trace = 1;
157 			nflag = 1;
158 			break;
159 
160 		case 'p':
161 			not_trace = 1;
162 			pflag = 1;
163 			break;
164 
165 		case '1':
166 			ripv2 = 0;
167 			break;
168 
169 		case 'w':
170 			not_trace = 1;
171 			wtime = (int)strtoul(optarg, &p, 0);
172 			if (*p != '\0'
173 			    || wtime <= 0)
174 				usage();
175 			break;
176 
177 		case 'r':
178 			not_trace = 1;
179 			if (rflag)
180 				usage();
181 			rflag = getnet(optarg, &OMSG.rip_nets[0]);
182 			if (!rflag) {
183 				struct hostent *hp = gethostbyname(optarg);
184 				if (hp == 0) {
185 					fprintf(stderr, "%s: %s:",
186 						pgmname, optarg);
187 					herror(0);
188 					exit(1);
189 				}
190 				memcpy(&OMSG.rip_nets[0].n_dst, hp->h_addr,
191 				       sizeof(OMSG.rip_nets[0].n_dst));
192 				OMSG.rip_nets[0].n_family = RIP_AF_INET;
193 				OMSG.rip_nets[0].n_mask = -1;
194 				rflag = 1;
195 			}
196 			break;
197 
198 		case 't':
199 			trace = 1;
200 			options = optarg;
201 			while (*options != '\0') {
202 				/* messy complications to make -W -Wall happy */
203 				static char on_str[] = "on";
204 				static char more_str[] = "more";
205 				static char off_str[] = "off";
206 				static char dump_str[] = "dump";
207 				static char *traceopts[] = {
208 #				    define TRACE_ON	0
209 					on_str,
210 #				    define TRACE_MORE	1
211 					more_str,
212 #				    define TRACE_OFF	2
213 					off_str,
214 #				    define TRACE_DUMP	3
215 					dump_str,
216 					0
217 				};
218 				result = "";
219 				switch (getsubopt(&options,traceopts,&value)) {
220 				case TRACE_ON:
221 					OMSG.rip_cmd = RIPCMD_TRACEON;
222 					if (!value
223 					    || strlen(value) > MAXPATHLEN)
224 					    usage();
225 					result = value;
226 					break;
227 				case TRACE_MORE:
228 					if (value)
229 					    usage();
230 					OMSG.rip_cmd = RIPCMD_TRACEON;
231 					break;
232 				case TRACE_OFF:
233 					if (value)
234 					    usage();
235 					OMSG.rip_cmd = RIPCMD_TRACEOFF;
236 					break;
237 				case TRACE_DUMP:
238 					if (value)
239 					    usage();
240 					OMSG.rip_cmd = RIPCMD_TRACEON;
241 					result = "dump/../table";
242 					break;
243 				default:
244 					usage();
245 				}
246 				strcpy((char*)OMSG.rip_tracefile, result);
247 				omsg_len += strlen(result) - sizeof(OMSG.ripun);
248 			}
249 			break;
250 
251 		case 'a':
252 			not_trace = 1;
253 			p = strchr(optarg,'=');
254 			if (!p)
255 				usage();
256 			*p++ = '\0';
257 			if (!strcasecmp("passwd",optarg))
258 				auth_type = RIP_AUTH_PW;
259 			else if (!strcasecmp("md5_passwd",optarg))
260 				auth_type = RIP_AUTH_MD5;
261 			else
262 				usage();
263 			if (0 > parse_quote(&p,"|",&delim,
264 					    passwd, sizeof(passwd)))
265 				usage();
266 			if (auth_type == RIP_AUTH_MD5
267 			    && delim == '|') {
268 				keyid = strtoul(p+1,&p,0);
269 				if (keyid > 255 || *p != '\0')
270 					usage();
271 			} else if (delim != '\0') {
272 				usage();
273 			}
274 			break;
275 
276 		default:
277 			usage();
278 	}
279 	argv += optind;
280 	argc -= optind;
281 	if (not_trace && trace)
282 		usage();
283 	if (argc == 0) {
284 		argc = 1;
285 		argv = default_argv;
286 	}
287 
288 	soc = socket(AF_INET, SOCK_DGRAM, 0);
289 	if (soc < 0) {
290 		perror("socket");
291 		exit(2);
292 	}
293 
294 	/* be prepared to receive a lot of routes */
295 	for (bsize = 127*1024; ; bsize -= 1024) {
296 		if (setsockopt(soc, SOL_SOCKET, SO_RCVBUF,
297 			       &bsize, sizeof(bsize)) == 0)
298 			break;
299 		if (bsize <= 4*1024) {
300 			perror("setsockopt SO_RCVBUF");
301 			break;
302 		}
303 	}
304 
305 	if (trace)
306 		trace_loop(argv);
307 	else
308 		query_loop(argv, argc);
309 	/* NOTREACHED */
310 	return 0;
311 }
312 
313 
314 static void
usage(void)315 usage(void)
316 {
317 	fprintf(stderr,
318 		"usage:  rtquery [-np1] [-r tgt_rt] [-w wtime]"
319 		" [-a type=passwd] host1 [host2 ...]\n"
320 		"\trtquery -t {on=filename|more|off|dump}"
321 				" host1 [host2 ...]\n");
322 	exit(1);
323 }
324 
325 
326 /* tell the target hosts about tracing
327  */
328 static void
trace_loop(char * argv[])329 trace_loop(char *argv[])
330 {
331 	struct sockaddr_in myaddr;
332 	int res;
333 
334 	if (geteuid() != 0) {
335 		(void)fprintf(stderr, "-t requires UID 0\n");
336 		exit(1);
337 	}
338 
339 	if (ripv2) {
340 		OMSG.rip_vers = RIPv2;
341 	} else {
342 		OMSG.rip_vers = RIPv1;
343 	}
344 
345 	memset(&myaddr, 0, sizeof(myaddr));
346 	myaddr.sin_family = AF_INET;
347 #ifdef _HAVE_SIN_LEN
348 	myaddr.sin_len = sizeof(myaddr);
349 #endif
350 	myaddr.sin_port = htons(IPPORT_RESERVED-1);
351 	while (bind(soc, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
352 		if (errno != EADDRINUSE
353 		    || myaddr.sin_port == 0) {
354 			perror("bind");
355 			exit(2);
356 		}
357 		myaddr.sin_port = ntohs(myaddr.sin_port)-1;
358 		myaddr.sin_port = htons(myaddr.sin_port);
359 	}
360 
361 	res = 1;
362 	while (*argv != 0) {
363 		if (out(*argv++) <= 0)
364 			res = 0;
365 	}
366 	exit(res);
367 }
368 
369 
370 /* query all of the listed hosts
371  */
372 static void
query_loop(char * argv[],int argc)373 query_loop(char *argv[], int argc)
374 {
375 	struct netauth *na = OMSG.rip_auths;
376 #	define NA0 (na[0])
377 #	define NA2 (na[2])
378 	struct seen {
379 		struct seen *next;
380 		struct in_addr addr;
381 	} *seen, *sp;
382 	int answered = 0;
383 	int cc;
384 	fd_set bits;
385 	struct timeval now, delay;
386 	struct sockaddr_in from;
387 	socklen_t fromlen;
388 	MD5_CTX md5_ctx;
389 
390 
391 	OMSG.rip_cmd = (pflag) ? RIPCMD_POLL : RIPCMD_REQUEST;
392 	if (ripv2) {
393 		OMSG.rip_vers = RIPv2;
394 		if (auth_type == RIP_AUTH_PW) {
395 			na[1] = na[0];
396 			NA0.a_family = RIP_AF_AUTH;
397 			NA0.a_type = RIP_AUTH_PW;
398 			memcpy(NA0.au.au_pw, passwd, RIP_AUTH_PW_LEN);
399 			omsg_len += sizeof(OMSG.rip_nets[0]);
400 
401 		} else if (auth_type == RIP_AUTH_MD5) {
402 			na[1] = na[0];
403 			NA0.a_family = RIP_AF_AUTH;
404 			NA0.a_type = RIP_AUTH_MD5;
405 			NA0.au.a_md5.md5_keyid = (int8_t)keyid;
406 			NA0.au.a_md5.md5_auth_len = RIP_AUTH_MD5_KEY_LEN;
407 			NA0.au.a_md5.md5_seqno = 0;
408 			cc = (char *)&NA2-(char *)&OMSG;
409 			NA0.au.a_md5.md5_pkt_len = htons(cc);
410 			NA2.a_family = RIP_AF_AUTH;
411 			NA2.a_type = htons(1);
412 			MD5Init(&md5_ctx);
413 			MD5Update(&md5_ctx,
414 				  (u_char *)&OMSG, cc);
415 			MD5Update(&md5_ctx,
416 				  (u_char *)passwd, RIP_AUTH_MD5_HASH_LEN);
417 			MD5Final(NA2.au.au_pw, &md5_ctx);
418 			omsg_len += 2*sizeof(OMSG.rip_nets[0]);
419 		}
420 
421 	} else {
422 		OMSG.rip_vers = RIPv1;
423 		OMSG.rip_nets[0].n_mask = 0;
424 	}
425 
426 	/* ask the first (valid) host */
427 	seen = 0;
428 	while (0 > out(*argv++)) {
429 		if (*argv == 0)
430 			exit(1);
431 		answered++;
432 	}
433 
434 	FD_ZERO(&bits);
435 	for (;;) {
436 		FD_SET(soc, &bits);
437 		delay.tv_sec = 0;
438 		delay.tv_usec = STIME;
439 		cc = select(soc+1, &bits, 0,0, &delay);
440 		if (cc > 0) {
441 			fromlen = sizeof(from);
442 			cc = recvfrom(soc, imsg_buf.packet,
443 				      sizeof(imsg_buf.packet), 0,
444 				      (struct sockaddr *)&from, &fromlen);
445 			if (cc < 0) {
446 				perror("recvfrom");
447 				exit(1);
448 			}
449 			/* count the distinct responding hosts.
450 			 * You cannot match responding hosts with
451 			 * addresses to which queries were transmitted,
452 			 * because a router might respond with a
453 			 * different source address.
454 			 */
455 			for (sp = seen; sp != 0; sp = sp->next) {
456 				if (sp->addr.s_addr == from.sin_addr.s_addr)
457 					break;
458 			}
459 			if (sp == 0) {
460 				sp = malloc(sizeof(*sp));
461 				if (sp == 0) {
462 					fprintf(stderr,
463 						"rtquery: malloc failed\n");
464 					exit(1);
465 				}
466 				sp->addr = from.sin_addr;
467 				sp->next = seen;
468 				seen = sp;
469 				answered++;
470 			}
471 
472 			rip_input(&from, cc);
473 			continue;
474 		}
475 
476 		if (cc < 0) {
477 			if (errno == EINTR)
478 				continue;
479 			perror("select");
480 			exit(1);
481 		}
482 
483 		/* After a pause in responses, probe another host.
484 		 * This reduces the intermingling of answers.
485 		 */
486 		while (*argv != 0 && 0 > out(*argv++))
487 			answered++;
488 
489 		/* continue until no more packets arrive
490 		 * or we have heard from all hosts
491 		 */
492 		if (answered >= argc)
493 			break;
494 
495 		/* or until we have waited a long time
496 		 */
497 		if (gettimeofday(&now, 0) < 0) {
498 			perror("gettimeofday(now)");
499 			exit(1);
500 		}
501 		if (sent.tv_sec + wtime <= now.tv_sec)
502 			break;
503 	}
504 
505 	/* fail if there was no answer */
506 	exit (answered >= argc ? 0 : 1);
507 }
508 
509 
510 /* send to one host
511  */
512 static int
out(const char * host)513 out(const char *host)
514 {
515 	struct sockaddr_in router;
516 	struct hostent *hp;
517 
518 	if (gettimeofday(&sent, 0) < 0) {
519 		perror("gettimeofday(sent)");
520 		return -1;
521 	}
522 
523 	memset(&router, 0, sizeof(router));
524 	router.sin_family = AF_INET;
525 #ifdef _HAVE_SIN_LEN
526 	router.sin_len = sizeof(router);
527 #endif
528 	if (!inet_aton(host, &router.sin_addr)) {
529 		hp = gethostbyname(host);
530 		if (hp == 0) {
531 			herror(host);
532 			return -1;
533 		}
534 		memcpy(&router.sin_addr, hp->h_addr, sizeof(router.sin_addr));
535 	}
536 	router.sin_port = htons(RIP_PORT);
537 
538 	if (sendto(soc, &omsg_buf, omsg_len, 0,
539 		   (struct sockaddr *)&router, sizeof(router)) < 0) {
540 		perror(host);
541 		return -1;
542 	}
543 
544 	return 0;
545 }
546 
547 
548 /*
549  * Convert string to printable characters
550  */
551 static char *
qstring(u_char * s,int len)552 qstring(u_char *s, int len)
553 {
554 	static char buf[8*20+1];
555 	size_t bufpos;
556 	u_char *s2, c;
557 
558 
559 	for (bufpos = 0; len != 0 && bufpos < sizeof(buf) - 1; len--) {
560 		c = *s++;
561 		if (c == '\0') {
562 			for (s2 = s+1; s2 < &s[len]; s2++) {
563 				if (*s2 != '\0')
564 					break;
565 			}
566 			if (s2 >= &s[len])
567 			    goto exit;
568 		}
569 
570 		if (c >= ' ' && c < 0x7f && c != '\\') {
571 			buf[bufpos++] = c;
572 			continue;
573 		}
574 		if (bufpos >= sizeof(buf) - 2) {
575 			/* too long */
576 			break;
577 		}
578 		buf[bufpos++] = '\\';
579 		switch (c) {
580 		case '\\':
581 			buf[bufpos++] = '\\';
582 			break;
583 		case '\n':
584 			buf[bufpos++] = 'n';
585 			break;
586 		case '\r':
587 			buf[bufpos++] = 'r';
588 			break;
589 		case '\t':
590 			buf[bufpos++] = 't';
591 			break;
592 		case '\b':
593 			buf[bufpos++] = 'b';
594 			break;
595 		default:
596 			bufpos += snprintf(buf + bufpos, sizeof(buf) - bufpos,
597 					   "%o", c);
598 			break;
599 		}
600 	}
601 exit:
602 	buf[bufpos] = '\0';
603 	return buf;
604 }
605 
606 
607 /*
608  * Handle an incoming RIP packet.
609  */
610 static void
rip_input(struct sockaddr_in * from,int size)611 rip_input(struct sockaddr_in *from,
612 	  int size)
613 {
614 	struct netinfo *n, *lim;
615 	struct in_addr in;
616 	const char *name;
617 	char net_buf[80];
618 	u_char hash[RIP_AUTH_MD5_KEY_LEN];
619 	MD5_CTX md5_ctx;
620 	u_char md5_authed = 0;
621 	u_int mask, dmask;
622 	size_t spos;
623 	int i;
624 	struct hostent *hp;
625 	struct netent *np;
626 	struct netauth *na;
627 
628 
629 	if (nflag) {
630 		printf("%s:", inet_ntoa(from->sin_addr));
631 	} else {
632 		hp = gethostbyaddr((char*)&from->sin_addr,
633 				   sizeof(struct in_addr), AF_INET);
634 		if (hp == 0) {
635 			printf("%s:",
636 			       inet_ntoa(from->sin_addr));
637 		} else {
638 			printf("%s (%s):", hp->h_name,
639 			       inet_ntoa(from->sin_addr));
640 		}
641 	}
642 	if (IMSG.rip_cmd != RIPCMD_RESPONSE) {
643 		printf("\n    unexpected response type %d\n", IMSG.rip_cmd);
644 		return;
645 	}
646 	printf(" RIPv%d%s %d bytes\n", IMSG.rip_vers,
647 	       (IMSG.rip_vers != RIPv1 && IMSG.rip_vers != RIPv2) ? " ?" : "",
648 	       size);
649 	if (size > MAXPACKETSIZE) {
650 		if (size > (int)sizeof(imsg_buf) - (int)sizeof(*n)) {
651 			printf("       at least %d bytes too long\n",
652 			       size-MAXPACKETSIZE);
653 			size = (int)sizeof(imsg_buf) - (int)sizeof(*n);
654 		} else {
655 			printf("       %d bytes too long\n",
656 			       size-MAXPACKETSIZE);
657 		}
658 	} else if (size%sizeof(*n) != sizeof(struct rip)%sizeof(*n)) {
659 		printf("    response of bad length=%d\n", size);
660 	}
661 
662 	n = IMSG.rip_nets;
663 	lim = (struct netinfo *)((char*)n + size) - 1;
664 	for (; n <= lim; n++) {
665 		name = "";
666 		if (n->n_family == RIP_AF_INET) {
667 			in.s_addr = n->n_dst;
668 			(void)strcpy(net_buf, inet_ntoa(in));
669 
670 			mask = ntohl(n->n_mask);
671 			dmask = mask & -mask;
672 			if (mask != 0) {
673 				spos = strlen(net_buf);
674 				if (IMSG.rip_vers == RIPv1) {
675 					(void)snprintf(net_buf + spos,
676 						       sizeof(net_buf) - spos,
677 						       " mask=%#x ? ", mask);
678 					mask = 0;
679 				} else if (mask + dmask == 0) {
680 					for (i = 0;
681 					     (i != 32
682 					      && ((1<<i)&mask) == 0);
683 					     i++)
684 						continue;
685 					(void)snprintf(net_buf + spos,
686 						      sizeof(net_buf) - spos,
687 						      "/%d", 32-i);
688 				} else {
689 					(void)snprintf(net_buf + spos,
690 						       sizeof(net_buf) - spos,
691 						       " (mask %#x)", mask);
692 				}
693 			}
694 
695 			if (!nflag) {
696 				if (mask == 0) {
697 					mask = std_mask(in.s_addr);
698 					if ((ntohl(in.s_addr) & ~mask) != 0)
699 						mask = 0;
700 				}
701 				/* Without a netmask, do not worry about
702 				 * whether the destination is a host or a
703 				 * network. Try both and use the first name
704 				 * we get.
705 				 *
706 				 * If we have a netmask we can make a
707 				 * good guess.
708 				 */
709 				if ((in.s_addr & ~mask) == 0) {
710 					np = getnetbyaddr((long)in.s_addr,
711 							  AF_INET);
712 					if (np != 0)
713 						name = np->n_name;
714 					else if (in.s_addr == 0)
715 						name = "default";
716 				}
717 				if (name[0] == '\0'
718 				    && ((in.s_addr & ~mask) != 0
719 					|| mask == 0xffffffff)) {
720 					hp = gethostbyaddr((char*)&in,
721 							   sizeof(in),
722 							   AF_INET);
723 					if (hp != 0)
724 						name = hp->h_name;
725 				}
726 			}
727 
728 		} else if (n->n_family == RIP_AF_AUTH) {
729 			na = (struct netauth*)n;
730 			if (na->a_type == RIP_AUTH_PW
731 			    && n == IMSG.rip_nets) {
732 				(void)printf("  Password Authentication:"
733 					     " \"%s\"\n",
734 					     qstring(na->au.au_pw,
735 						     RIP_AUTH_PW_LEN));
736 				continue;
737 			}
738 
739 			if (na->a_type == RIP_AUTH_MD5
740 			    && n == IMSG.rip_nets) {
741 				(void)printf("  MD5 Auth"
742 					     " len=%d KeyID=%d"
743 					     " auth_len=%d"
744 					     " seqno=%#x"
745 					     " rsvd=%#x,%#x\n",
746 					     ntohs(na->au.a_md5.md5_pkt_len),
747 					     na->au.a_md5.md5_keyid,
748 					     na->au.a_md5.md5_auth_len,
749 					     (int)ntohl(na->au.a_md5.md5_seqno),
750 					     na->au.a_md5.rsvd[0],
751 					     na->au.a_md5.rsvd[1]);
752 				md5_authed = 1;
753 				continue;
754 			}
755 			(void)printf("  Authentication type %d: ",
756 				     ntohs(na->a_type));
757 			for (i = 0; i < (int)sizeof(na->au.au_pw); i++)
758 				(void)printf("%02x ", na->au.au_pw[i]);
759 			putc('\n', stdout);
760 			if (md5_authed && n+1 > lim
761 			    && na->a_type == ntohs(1)) {
762 				MD5Init(&md5_ctx);
763 				MD5Update(&md5_ctx, (u_char *)&IMSG,
764 					  (char *)na-(char *)&IMSG
765 					  +RIP_AUTH_MD5_HASH_XTRA);
766 				MD5Update(&md5_ctx, (u_char *)passwd,
767 					  RIP_AUTH_MD5_KEY_LEN);
768 				MD5Final(hash, &md5_ctx);
769 				(void)printf("    %s hash\n",
770 					     memcmp(hash, na->au.au_pw,
771 						    sizeof(hash))
772 					     ? "WRONG" : "correct");
773 			}
774 			continue;
775 
776 		} else {
777 			(void)snprintf(net_buf, sizeof(net_buf),
778 				      "(af %#x) %d.%d.%d.%d",
779 				      ntohs(n->n_family),
780 				      (u_char)(n->n_dst >> 24),
781 				      (u_char)(n->n_dst >> 16),
782 				      (u_char)(n->n_dst >> 8),
783 				      (u_char)n->n_dst);
784 		}
785 
786 		(void)printf("  %-18s metric %2d %-10s",
787 			     net_buf, (int)ntohl(n->n_metric), name);
788 
789 		if (n->n_nhop != 0) {
790 			in.s_addr = n->n_nhop;
791 			if (nflag)
792 				hp = 0;
793 			else
794 				hp = gethostbyaddr((char*)&in, sizeof(in),
795 						   AF_INET);
796 			(void)printf(" nhop=%-15s%s",
797 				     (hp != 0) ? hp->h_name : inet_ntoa(in),
798 				     (IMSG.rip_vers == RIPv1) ? " ?" : "");
799 		}
800 		if (n->n_tag != 0)
801 			(void)printf(" tag=%#x%s", n->n_tag,
802 				     (IMSG.rip_vers == RIPv1) ? " ?" : "");
803 		putc('\n', stdout);
804 	}
805 }
806 
807 
808 /* Return the classical netmask for an IP address.
809  */
810 static u_int
std_mask(u_int addr)811 std_mask(u_int addr)			/* in network order */
812 {
813 	addr = ntohl(addr);			/* was a host, not a network */
814 
815 	if (addr == 0)			/* default route has mask 0 */
816 		return 0;
817 	if (IN_CLASSA(addr))
818 		return IN_CLASSA_NET;
819 	if (IN_CLASSB(addr))
820 		return IN_CLASSB_NET;
821 	return IN_CLASSC_NET;
822 }
823 
824 
825 /* get a network number as a name or a number, with an optional "/xx"
826  * netmask.
827  */
828 static int				/* 0=bad */
getnet(char * name,struct netinfo * rt)829 getnet(char *name,
830        struct netinfo *rt)
831 {
832 	int i;
833 	struct netent *nentp;
834 	u_int mask;
835 	struct in_addr in;
836 	char hname[MAXHOSTNAMELEN+1];
837 	char *mname, *p;
838 
839 
840 	/* Detect and separate "1.2.3.4/24"
841 	 */
842 	if (0 != (mname = strrchr(name,'/'))) {
843 		i = (int)(mname - name);
844 		if (i > (int)sizeof(hname)-1)	/* name too long */
845 			return 0;
846 		memmove(hname, name, i);
847 		hname[i] = '\0';
848 		mname++;
849 		name = hname;
850 	}
851 
852 	nentp = getnetbyname(name);
853 	if (nentp != 0) {
854 		in.s_addr = nentp->n_net;
855 	} else if (inet_aton(name, &in) == 1) {
856 		in.s_addr = ntohl(in.s_addr);
857 	} else {
858 		return 0;
859 	}
860 
861 	if (mname == 0) {
862 		mask = std_mask(in.s_addr);
863 		if ((~mask & in.s_addr) != 0)
864 			mask = 0xffffffff;
865 	} else {
866 		mask = (u_int)strtoul(mname, &p, 0);
867 		if (*p != '\0' || mask > 32)
868 			return 0;
869 		mask = 0xffffffff << (32-mask);
870 	}
871 
872 	rt->n_dst = htonl(in.s_addr);
873 	rt->n_family = RIP_AF_INET;
874 	rt->n_mask = htonl(mask);
875 	return 1;
876 }
877 
878 
879 /* strtok(), but honoring backslash
880  */
881 static int				/* -1=bad */
parse_quote(char ** linep,const char * delims,char * delimp,char * buf,int lim)882 parse_quote(char **linep,
883 	    const char *delims,
884 	    char *delimp,
885 	    char *buf,
886 	    int	lim)
887 {
888 	char c, *pc;
889 	const char *p;
890 
891 
892 	pc = *linep;
893 	if (*pc == '\0')
894 		return -1;
895 
896 	for (;;) {
897 		if (lim == 0)
898 			return -1;
899 		c = *pc++;
900 		if (c == '\0')
901 			break;
902 
903 		if (c == '\\' && *pc != '\0') {
904 			if ((c = *pc++) == 'n') {
905 				c = '\n';
906 			} else if (c == 'r') {
907 				c = '\r';
908 			} else if (c == 't') {
909 				c = '\t';
910 			} else if (c == 'b') {
911 				c = '\b';
912 			} else if (c >= '0' && c <= '7') {
913 				c -= '0';
914 				if (*pc >= '0' && *pc <= '7') {
915 					c = (c<<3)+(*pc++ - '0');
916 					if (*pc >= '0' && *pc <= '7')
917 					    c = (c<<3)+(*pc++ - '0');
918 				}
919 			}
920 
921 		} else {
922 			for (p = delims; *p != '\0'; ++p) {
923 				if (*p == c)
924 					goto exit;
925 			}
926 		}
927 
928 		*buf++ = c;
929 		--lim;
930 	}
931 exit:
932 	if (delimp != 0)
933 		*delimp = c;
934 	*linep = pc-1;
935 	if (lim != 0)
936 		*buf = '\0';
937 	return 0;
938 }
939