1 /*
2  * utils.c
3  *
4  *		This program is free software; you can redistribute it and/or
5  *		modify it under the terms of the GNU General Public License
6  *		as published by the Free Software Foundation; either version
7  *		2 of the License, or (at your option) any later version.
8  *
9  * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10  *
11  */
12 
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <math.h>
16 #include <unistd.h>
17 #include <syslog.h>
18 #include <fcntl.h>
19 #include <limits.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <string.h>
23 #include <netdb.h>
24 #include <arpa/inet.h>
25 #include <asm/types.h>
26 #include <linux/pkt_sched.h>
27 #include <linux/param.h>
28 #include <linux/if_arp.h>
29 #include <linux/mpls.h>
30 #include <time.h>
31 #include <sys/time.h>
32 #include <errno.h>
33 
34 #include "rt_names.h"
35 #include "utils.h"
36 #include "namespace.h"
37 
38 int timestamp_short = 0;
39 
get_integer(int * val,const char * arg,int base)40 int get_integer(int *val, const char *arg, int base)
41 {
42 	long res;
43 	char *ptr;
44 
45 	if (!arg || !*arg)
46 		return -1;
47 
48 	res = strtol(arg, &ptr, base);
49 
50 	/* If there were no digits at all, strtol()  stores
51          * the original value of nptr in *endptr (and returns 0).
52 	 * In particular, if *nptr is not '\0' but **endptr is '\0' on return,
53 	 * the entire string is valid.
54 	 */
55 	if (!ptr || ptr == arg || *ptr)
56 		return -1;
57 
58 	/* If an underflow occurs, strtol() returns LONG_MIN.
59 	 * If an overflow occurs,  strtol() returns LONG_MAX.
60 	 * In both cases, errno is set to ERANGE.
61 	 */
62 	if ((res == LONG_MAX || res == LONG_MIN) && errno == ERANGE)
63 		return -1;
64 
65 	/* Outside range of int */
66 	if (res < INT_MIN || res > INT_MAX)
67 		return -1;
68 
69 	*val = res;
70 	return 0;
71 }
72 
mask2bits(__u32 netmask)73 int mask2bits(__u32 netmask)
74 {
75 	unsigned bits = 0;
76 	__u32 mask = ntohl(netmask);
77 	__u32 host = ~mask;
78 
79 	/* a valid netmask must be 2^n - 1 */
80 	if ((host & (host + 1)) != 0)
81 		return -1;
82 
83 	for (; mask; mask <<= 1)
84 		++bits;
85 	return bits;
86 }
87 
get_netmask(unsigned * val,const char * arg,int base)88 static int get_netmask(unsigned *val, const char *arg, int base)
89 {
90 	inet_prefix addr;
91 
92 	if (!get_unsigned(val, arg, base))
93 		return 0;
94 
95 	/* try coverting dotted quad to CIDR */
96 	if (!get_addr_1(&addr, arg, AF_INET) && addr.family == AF_INET) {
97 		int b = mask2bits(addr.data[0]);
98 
99 		if (b >= 0) {
100 			*val = b;
101 			return 0;
102 		}
103 	}
104 
105 	return -1;
106 }
107 
get_unsigned(unsigned * val,const char * arg,int base)108 int get_unsigned(unsigned *val, const char *arg, int base)
109 {
110 	unsigned long res;
111 	char *ptr;
112 
113 	if (!arg || !*arg)
114 		return -1;
115 
116 	res = strtoul(arg, &ptr, base);
117 
118 	/* empty string or trailing non-digits */
119 	if (!ptr || ptr == arg || *ptr)
120 		return -1;
121 
122 	/* overflow */
123 	if (res == ULONG_MAX && errno == ERANGE)
124 		return -1;
125 
126 	/* out side range of unsigned */
127 	if (res > UINT_MAX)
128 		return -1;
129 
130 	*val = res;
131 	return 0;
132 }
133 
134 /*
135  * get_time_rtt is "translated" from a similar routine "get_time" in
136  * tc_util.c.  We don't use the exact same routine because tc passes
137  * microseconds to the kernel and the callers of get_time_rtt want to
138  * pass milliseconds (standard unit for rtt values since 2.6.27), and
139  * have a different assumption for the units of a "raw" number.
140  */
get_time_rtt(unsigned * val,const char * arg,int * raw)141 int get_time_rtt(unsigned *val, const char *arg, int *raw)
142 {
143 	double t;
144 	unsigned long res;
145 	char *p;
146 
147 	if (strchr(arg, '.') != NULL) {
148 		t = strtod(arg, &p);
149 		if (t < 0.0)
150 			return -1;
151 
152 		/* no digits? */
153 		if (!p || p == arg)
154 			return -1;
155 
156 		/* over/underflow */
157 		if ((t == HUGE_VALF || t == HUGE_VALL) && errno == ERANGE)
158 			return -1;
159 	} else {
160 		res = strtoul(arg, &p, 0);
161 
162 		/* empty string? */
163 		if (!p || p == arg)
164 			return -1;
165 
166 		/* overflow */
167 		if (res == ULONG_MAX && errno == ERANGE)
168 			return -1;
169 
170 		t = (double)res;
171 	}
172 
173 	if (p == arg)
174 		return -1;
175 	*raw = 1;
176 
177 	if (*p) {
178 		*raw = 0;
179                 if (strcasecmp(p, "s") == 0 || strcasecmp(p, "sec")==0 ||
180                     strcasecmp(p, "secs")==0)
181                         t *= 1000;
182                 else if (strcasecmp(p, "ms") == 0 || strcasecmp(p, "msec")==0 ||
183                          strcasecmp(p, "msecs") == 0)
184 			t *= 1.0; /* allow suffix, do nothing */
185                 else
186                         return -1;
187         }
188 
189 	/* emulate ceil() without having to bring-in -lm and always be >= 1 */
190 
191 	*val = t;
192 	if (*val < t)
193 		*val += 1;
194 
195         return 0;
196 
197 }
198 
get_u64(__u64 * val,const char * arg,int base)199 int get_u64(__u64 *val, const char *arg, int base)
200 {
201 	unsigned long long res;
202 	char *ptr;
203 
204 	if (!arg || !*arg)
205 		return -1;
206 
207 	res = strtoull(arg, &ptr, base);
208 
209 	/* empty string or trailing non-digits */
210 	if (!ptr || ptr == arg || *ptr)
211 		return -1;
212 
213 	/* overflow */
214 	if (res == ULLONG_MAX && errno == ERANGE)
215 		return -1;
216 
217 	/* in case ULL is 128 bits */
218 	if (res > 0xFFFFFFFFFFFFFFFFULL)
219 		return -1;
220 
221  	*val = res;
222  	return 0;
223 }
224 
get_u32(__u32 * val,const char * arg,int base)225 int get_u32(__u32 *val, const char *arg, int base)
226 {
227 	unsigned long res;
228 	char *ptr;
229 
230 	if (!arg || !*arg)
231 		return -1;
232 	res = strtoul(arg, &ptr, base);
233 
234 	/* empty string or trailing non-digits */
235 	if (!ptr || ptr == arg || *ptr)
236 		return -1;
237 
238 	/* overflow */
239 	if (res == ULONG_MAX && errno == ERANGE)
240 		return -1;
241 
242 	/* in case UL > 32 bits */
243 	if (res > 0xFFFFFFFFUL)
244 		return -1;
245 
246 	*val = res;
247 	return 0;
248 }
249 
get_u16(__u16 * val,const char * arg,int base)250 int get_u16(__u16 *val, const char *arg, int base)
251 {
252 	unsigned long res;
253 	char *ptr;
254 
255 	if (!arg || !*arg)
256 		return -1;
257 	res = strtoul(arg, &ptr, base);
258 
259 	/* empty string or trailing non-digits */
260 	if (!ptr || ptr == arg || *ptr)
261 		return -1;
262 
263 	/* overflow */
264 	if (res == ULONG_MAX && errno == ERANGE)
265 		return -1;
266 
267 	if (res > 0xFFFFUL)
268 		return -1;
269 
270 	*val = res;
271 	return 0;
272 }
273 
get_u8(__u8 * val,const char * arg,int base)274 int get_u8(__u8 *val, const char *arg, int base)
275 {
276 	unsigned long res;
277 	char *ptr;
278 
279 	if (!arg || !*arg)
280 		return -1;
281 
282 	res = strtoul(arg, &ptr, base);
283 	/* empty string or trailing non-digits */
284 	if (!ptr || ptr == arg || *ptr)
285 		return -1;
286 
287 	/* overflow */
288 	if (res == ULONG_MAX && errno == ERANGE)
289 		return -1;
290 
291 	if (res > 0xFFUL)
292 		return -1;
293 
294 	*val = res;
295 	return 0;
296 }
297 
get_s32(__s32 * val,const char * arg,int base)298 int get_s32(__s32 *val, const char *arg, int base)
299 {
300 	long res;
301 	char *ptr;
302 
303 	errno = 0;
304 
305 	if (!arg || !*arg)
306 		return -1;
307 	res = strtol(arg, &ptr, base);
308 	if (!ptr || ptr == arg || *ptr)
309 		return -1;
310 	if ((res == LONG_MIN || res == LONG_MAX) && errno == ERANGE)
311 		return -1;
312 	if (res > INT32_MAX || res < INT32_MIN)
313 		return -1;
314 
315 	*val = res;
316 	return 0;
317 }
318 
get_s16(__s16 * val,const char * arg,int base)319 int get_s16(__s16 *val, const char *arg, int base)
320 {
321 	long res;
322 	char *ptr;
323 
324 	if (!arg || !*arg)
325 		return -1;
326 	res = strtol(arg, &ptr, base);
327 	if (!ptr || ptr == arg || *ptr)
328 		return -1;
329 	if ((res == LONG_MIN || res == LONG_MAX) && errno == ERANGE)
330 		return -1;
331 	if (res > 0x7FFF || res < -0x8000)
332 		return -1;
333 
334 	*val = res;
335 	return 0;
336 }
337 
get_s8(__s8 * val,const char * arg,int base)338 int get_s8(__s8 *val, const char *arg, int base)
339 {
340 	long res;
341 	char *ptr;
342 
343 	if (!arg || !*arg)
344 		return -1;
345 	res = strtol(arg, &ptr, base);
346 	if (!ptr || ptr == arg || *ptr)
347 		return -1;
348 	if ((res == LONG_MIN || res == LONG_MAX) && errno == ERANGE)
349 		return -1;
350 	if (res > 0x7F || res < -0x80)
351 		return -1;
352 	*val = res;
353 	return 0;
354 }
355 
356 /* This uses a non-standard parsing (ie not inet_aton, or inet_pton)
357  * because of legacy choice to parse 10.8 as 10.8.0.0 not 10.0.0.8
358  */
get_addr_ipv4(__u8 * ap,const char * cp)359 static int get_addr_ipv4(__u8 *ap, const char *cp)
360 {
361 	int i;
362 
363 	for (i = 0; i < 4; i++) {
364 		unsigned long n;
365 		char *endp;
366 
367 		n = strtoul(cp, &endp, 0);
368 		if (n > 255)
369 			return -1;	/* bogus network value */
370 
371 		if (endp == cp) /* no digits */
372 			return -1;
373 
374 		ap[i] = n;
375 
376 		if (*endp == '\0')
377 			break;
378 
379 		if (i == 3 || *endp != '.')
380 			return -1; 	/* extra characters */
381 		cp = endp + 1;
382 	}
383 
384 	return 1;
385 }
386 
get_addr64(__u64 * ap,const char * cp)387 int get_addr64(__u64 *ap, const char *cp)
388 {
389 	int i;
390 
391 	union {
392 		__u16 v16[4];
393 		__u64 v64;
394 	} val;
395 
396 	for (i = 0; i < 4; i++) {
397 		unsigned long n;
398 		char *endp;
399 
400 		n = strtoul(cp, &endp, 16);
401 		if (n > 0xffff)
402 			return -1;	/* bogus network value */
403 
404 		if (endp == cp) /* no digits */
405 			return -1;
406 
407 		val.v16[i] = htons(n);
408 
409 		if (*endp == '\0')
410 			break;
411 
412 		if (i == 3 || *endp != ':')
413 			return -1;	/* extra characters */
414 		cp = endp + 1;
415 	}
416 
417 	*ap = val.v64;
418 
419 	return 1;
420 }
421 
get_addr_1(inet_prefix * addr,const char * name,int family)422 int get_addr_1(inet_prefix *addr, const char *name, int family)
423 {
424 	memset(addr, 0, sizeof(*addr));
425 
426 	if (strcmp(name, "default") == 0 ||
427 	    strcmp(name, "all") == 0 ||
428 	    strcmp(name, "any") == 0) {
429 		if ((family == AF_DECnet) || (family == AF_MPLS))
430 			return -1;
431 		addr->family = family;
432 		addr->bytelen = (family == AF_INET6 ? 16 : 4);
433 		addr->bitlen = -1;
434 		return 0;
435 	}
436 
437 	if (family == AF_PACKET) {
438 		int len;
439 		len = ll_addr_a2n((char *)&addr->data, sizeof(addr->data), name);
440 		if (len < 0)
441 			return -1;
442 
443 		addr->family = AF_PACKET;
444 		addr->bytelen = len;
445 		addr->bitlen = len * 8;
446 		return 0;
447 	}
448 
449 	if (strchr(name, ':')) {
450 		addr->family = AF_INET6;
451 		if (family != AF_UNSPEC && family != AF_INET6)
452 			return -1;
453 		if (inet_pton(AF_INET6, name, addr->data) <= 0)
454 			return -1;
455 		addr->bytelen = 16;
456 		addr->bitlen = -1;
457 		return 0;
458 	}
459 
460 #ifndef ANDROID
461 	if (family == AF_DECnet) {
462 		struct dn_naddr dna;
463 		addr->family = AF_DECnet;
464 		if (dnet_pton(AF_DECnet, name, &dna) <= 0)
465 			return -1;
466 		memcpy(addr->data, dna.a_addr, 2);
467 		addr->bytelen = 2;
468 		addr->bitlen = -1;
469 		return 0;
470 	}
471 #endif
472 
473 	if (family == AF_MPLS) {
474 		int i;
475 		addr->family = AF_MPLS;
476 		if (mpls_pton(AF_MPLS, name, addr->data) <= 0)
477 			return -1;
478 		addr->bytelen = 4;
479 		addr->bitlen = 20;
480 		/* How many bytes do I need? */
481 		for (i = 0; i < 8; i++) {
482 			if (ntohl(addr->data[i]) & MPLS_LS_S_MASK) {
483 				addr->bytelen = (i + 1)*4;
484 				break;
485 			}
486 		}
487 		return 0;
488 	}
489 
490 	addr->family = AF_INET;
491 	if (family != AF_UNSPEC && family != AF_INET)
492 		return -1;
493 
494 	if (get_addr_ipv4((__u8 *)addr->data, name) <= 0)
495 		return -1;
496 
497 	addr->bytelen = 4;
498 	addr->bitlen = -1;
499 	return 0;
500 }
501 
af_bit_len(int af)502 int af_bit_len(int af)
503 {
504 	switch (af) {
505 	case AF_INET6:
506 		return 128;
507 	case AF_INET:
508 		return 32;
509 	case AF_DECnet:
510 		return 16;
511 	case AF_IPX:
512 		return 80;
513 	case AF_MPLS:
514 		return 20;
515 	}
516 
517 	return 0;
518 }
519 
af_byte_len(int af)520 int af_byte_len(int af)
521 {
522 	return af_bit_len(af) / 8;
523 }
524 
get_prefix_1(inet_prefix * dst,char * arg,int family)525 int get_prefix_1(inet_prefix *dst, char *arg, int family)
526 {
527 	int err;
528 	unsigned plen;
529 	char *slash;
530 
531 	memset(dst, 0, sizeof(*dst));
532 
533 	if (strcmp(arg, "default") == 0 ||
534 	    strcmp(arg, "any") == 0 ||
535 	    strcmp(arg, "all") == 0) {
536 		if ((family == AF_DECnet) || (family == AF_MPLS))
537 			return -1;
538 		dst->family = family;
539 		dst->bytelen = 0;
540 		dst->bitlen = 0;
541 		return 0;
542 	}
543 
544 	slash = strchr(arg, '/');
545 	if (slash)
546 		*slash = 0;
547 
548 	err = get_addr_1(dst, arg, family);
549 	if (err == 0) {
550 		dst->bitlen = af_bit_len(dst->family);
551 
552 		if (slash) {
553 			if (get_netmask(&plen, slash+1, 0)
554 			    || plen > dst->bitlen) {
555 				err = -1;
556 				goto done;
557 			}
558 			dst->flags |= PREFIXLEN_SPECIFIED;
559 			dst->bitlen = plen;
560 		}
561 	}
562 done:
563 	if (slash)
564 		*slash = '/';
565 	return err;
566 }
567 
get_addr(inet_prefix * dst,const char * arg,int family)568 int get_addr(inet_prefix *dst, const char *arg, int family)
569 {
570 	if (get_addr_1(dst, arg, family)) {
571 		fprintf(stderr, "Error: %s address is expected rather than \"%s\".\n",
572 				family_name(family) ,arg);
573 		exit(1);
574 	}
575 	return 0;
576 }
577 
get_prefix(inet_prefix * dst,char * arg,int family)578 int get_prefix(inet_prefix *dst, char *arg, int family)
579 {
580 	if (family == AF_PACKET) {
581 		fprintf(stderr, "Error: \"%s\" may be inet prefix, but it is not allowed in this context.\n", arg);
582 		exit(1);
583 	}
584 	if (get_prefix_1(dst, arg, family)) {
585 		fprintf(stderr, "Error: %s prefix is expected rather than \"%s\".\n",
586 				family_name(family) ,arg);
587 		exit(1);
588 	}
589 	return 0;
590 }
591 
get_addr32(const char * name)592 __u32 get_addr32(const char *name)
593 {
594 	inet_prefix addr;
595 	if (get_addr_1(&addr, name, AF_INET)) {
596 		fprintf(stderr, "Error: an IP address is expected rather than \"%s\"\n", name);
597 		exit(1);
598 	}
599 	return addr.data[0];
600 }
601 
incomplete_command(void)602 void incomplete_command(void)
603 {
604 	fprintf(stderr, "Command line is not complete. Try option \"help\"\n");
605 	exit(-1);
606 }
607 
missarg(const char * key)608 void missarg(const char *key)
609 {
610 	fprintf(stderr, "Error: argument \"%s\" is required\n", key);
611 	exit(-1);
612 }
613 
invarg(const char * msg,const char * arg)614 void invarg(const char *msg, const char *arg)
615 {
616 	fprintf(stderr, "Error: argument \"%s\" is wrong: %s\n", arg, msg);
617 	exit(-1);
618 }
619 
duparg(const char * key,const char * arg)620 void duparg(const char *key, const char *arg)
621 {
622 	fprintf(stderr, "Error: duplicate \"%s\": \"%s\" is the second value.\n", key, arg);
623 	exit(-1);
624 }
625 
duparg2(const char * key,const char * arg)626 void duparg2(const char *key, const char *arg)
627 {
628 	fprintf(stderr, "Error: either \"%s\" is duplicate, or \"%s\" is a garbage.\n", key, arg);
629 	exit(-1);
630 }
631 
matches(const char * cmd,const char * pattern)632 int matches(const char *cmd, const char *pattern)
633 {
634 	int len = strlen(cmd);
635 	if (len > strlen(pattern))
636 		return -1;
637 	return memcmp(pattern, cmd, len);
638 }
639 
inet_addr_match(const inet_prefix * a,const inet_prefix * b,int bits)640 int inet_addr_match(const inet_prefix *a, const inet_prefix *b, int bits)
641 {
642 	const __u32 *a1 = a->data;
643 	const __u32 *a2 = b->data;
644 	int words = bits >> 0x05;
645 
646 	bits &= 0x1f;
647 
648 	if (words)
649 		if (memcmp(a1, a2, words << 2))
650 			return -1;
651 
652 	if (bits) {
653 		__u32 w1, w2;
654 		__u32 mask;
655 
656 		w1 = a1[words];
657 		w2 = a2[words];
658 
659 		mask = htonl((0xffffffff) << (0x20 - bits));
660 
661 		if ((w1 ^ w2) & mask)
662 			return 1;
663 	}
664 
665 	return 0;
666 }
667 
668 int __iproute2_hz_internal;
669 
__get_hz(void)670 int __get_hz(void)
671 {
672 	char name[1024];
673 	int hz = 0;
674 	FILE *fp;
675 
676 	if (getenv("HZ"))
677 		return atoi(getenv("HZ")) ? : HZ;
678 
679 	if (getenv("PROC_NET_PSCHED")) {
680 		snprintf(name, sizeof(name)-1, "%s", getenv("PROC_NET_PSCHED"));
681 	} else if (getenv("PROC_ROOT")) {
682 		snprintf(name, sizeof(name)-1, "%s/net/psched", getenv("PROC_ROOT"));
683 	} else {
684 		strcpy(name, "/proc/net/psched");
685 	}
686 	fp = fopen(name, "r");
687 
688 	if (fp) {
689 		unsigned nom, denom;
690 		if (fscanf(fp, "%*08x%*08x%08x%08x", &nom, &denom) == 2)
691 			if (nom == 1000000)
692 				hz = denom;
693 		fclose(fp);
694 	}
695 	if (hz)
696 		return hz;
697 	return HZ;
698 }
699 
700 int __iproute2_user_hz_internal;
701 
__get_user_hz(void)702 int __get_user_hz(void)
703 {
704 	return sysconf(_SC_CLK_TCK);
705 }
706 
rt_addr_n2a(int af,int len,const void * addr,char * buf,int buflen)707 const char *rt_addr_n2a(int af, int len, const void *addr, char *buf, int buflen)
708 {
709 	switch (af) {
710 	case AF_INET:
711 	case AF_INET6:
712 		return inet_ntop(af, addr, buf, buflen);
713 #ifndef ANDROID
714 	case AF_MPLS:
715 		return mpls_ntop(af, addr, buf, buflen);
716 	case AF_IPX:
717 		return ipx_ntop(af, addr, buf, buflen);
718 	case AF_DECnet:
719 	{
720 		struct dn_naddr dna = { 2, { 0, 0, }};
721 		memcpy(dna.a_addr, addr, 2);
722 		return dnet_ntop(af, &dna, buf, buflen);
723 	}
724 #endif
725 	case AF_PACKET:
726 		return ll_addr_n2a(addr, len, ARPHRD_VOID, buf, buflen);
727 	default:
728 		return "???";
729 	}
730 }
731 
read_family(const char * name)732 int read_family(const char *name)
733 {
734 	int family = AF_UNSPEC;
735 	if (strcmp(name, "inet") == 0)
736 		family = AF_INET;
737 	else if (strcmp(name, "inet6") == 0)
738 		family = AF_INET6;
739 	else if (strcmp(name, "dnet") == 0)
740 		family = AF_DECnet;
741 	else if (strcmp(name, "link") == 0)
742 		family = AF_PACKET;
743 	else if (strcmp(name, "ipx") == 0)
744 		family = AF_IPX;
745 	else if (strcmp(name, "mpls") == 0)
746 		family = AF_MPLS;
747 	else if (strcmp(name, "bridge") == 0)
748 		family = AF_BRIDGE;
749 	return family;
750 }
751 
family_name(int family)752 const char *family_name(int family)
753 {
754 	if (family == AF_INET)
755 		return "inet";
756 	if (family == AF_INET6)
757 		return "inet6";
758 	if (family == AF_DECnet)
759 		return "dnet";
760 	if (family == AF_PACKET)
761 		return "link";
762 	if (family == AF_IPX)
763 		return "ipx";
764 	if (family == AF_MPLS)
765 		return "mpls";
766 	if (family == AF_BRIDGE)
767 		return "bridge";
768 	return "???";
769 }
770 
771 #ifdef RESOLVE_HOSTNAMES
772 struct namerec
773 {
774 	struct namerec *next;
775 	const char *name;
776 	inet_prefix addr;
777 };
778 
779 #define NHASH 257
780 static struct namerec *nht[NHASH];
781 
resolve_address(const void * addr,int len,int af)782 static const char *resolve_address(const void *addr, int len, int af)
783 {
784 	struct namerec *n;
785 	struct hostent *h_ent;
786 	unsigned hash;
787 	static int notfirst;
788 
789 
790 	if (af == AF_INET6 && ((__u32*)addr)[0] == 0 &&
791 	    ((__u32*)addr)[1] == 0 && ((__u32*)addr)[2] == htonl(0xffff)) {
792 		af = AF_INET;
793 		addr += 12;
794 		len = 4;
795 	}
796 
797 	hash = *(__u32 *)(addr + len - 4) % NHASH;
798 
799 	for (n = nht[hash]; n; n = n->next) {
800 		if (n->addr.family == af &&
801 		    n->addr.bytelen == len &&
802 		    memcmp(n->addr.data, addr, len) == 0)
803 			return n->name;
804 	}
805 	if ((n = malloc(sizeof(*n))) == NULL)
806 		return NULL;
807 	n->addr.family = af;
808 	n->addr.bytelen = len;
809 	n->name = NULL;
810 	memcpy(n->addr.data, addr, len);
811 	n->next = nht[hash];
812 	nht[hash] = n;
813 	if (++notfirst == 1)
814 		sethostent(1);
815 	fflush(stdout);
816 
817 	if ((h_ent = gethostbyaddr(addr, len, af)) != NULL)
818 		n->name = strdup(h_ent->h_name);
819 
820 	/* Even if we fail, "negative" entry is remembered. */
821 	return n->name;
822 }
823 #endif
824 
format_host(int af,int len,const void * addr,char * buf,int buflen)825 const char *format_host(int af, int len, const void *addr,
826 			char *buf, int buflen)
827 {
828 #ifdef RESOLVE_HOSTNAMES
829 	if (resolve_hosts) {
830 		const char *n;
831 
832 		len = len <= 0 ? af_byte_len(af) : len;
833 
834 		if (len > 0 &&
835 		    (n = resolve_address(addr, len, af)) != NULL)
836 			return n;
837 	}
838 #endif
839 	return rt_addr_n2a(af, len, addr, buf, buflen);
840 }
841 
842 
hexstring_n2a(const __u8 * str,int len,char * buf,int blen)843 char *hexstring_n2a(const __u8 *str, int len, char *buf, int blen)
844 {
845 	char *ptr = buf;
846 	int i;
847 
848 	for (i=0; i<len; i++) {
849 		if (blen < 3)
850 			break;
851 		sprintf(ptr, "%02x", str[i]);
852 		ptr += 2;
853 		blen -= 2;
854 	}
855 	return buf;
856 }
857 
hexstring_a2n(const char * str,__u8 * buf,int blen)858 __u8* hexstring_a2n(const char *str, __u8 *buf, int blen)
859 {
860 	int cnt = 0;
861 	char *endptr;
862 
863 	if (strlen(str) % 2)
864 		return NULL;
865 	while (cnt < blen && strlen(str) > 1) {
866 		unsigned int tmp;
867 		char tmpstr[3];
868 
869 		strncpy(tmpstr, str, 2);
870 		tmpstr[2] = '\0';
871 		tmp = strtoul(tmpstr, &endptr, 16);
872 		if (errno != 0 || tmp > 0xFF || *endptr != '\0')
873 			return NULL;
874 		buf[cnt++] = tmp;
875 		str += 2;
876 	}
877 	return buf;
878 }
879 
addr64_n2a(__u64 addr,char * buff,size_t len)880 int addr64_n2a(__u64 addr, char *buff, size_t len)
881 {
882 	__u16 *words = (__u16 *)&addr;
883 	__u16 v;
884 	int i, ret;
885 	size_t written = 0;
886 	char *sep = ":";
887 
888 	for (i = 0; i < 4; i++) {
889 		v = ntohs(words[i]);
890 
891 		if (i == 3)
892 			sep = "";
893 
894 		ret = snprintf(&buff[written], len - written, "%x%s", v, sep);
895 		if (ret < 0)
896 			return ret;
897 
898 		written += ret;
899 	}
900 
901 	return written;
902 }
903 
print_timestamp(FILE * fp)904 int print_timestamp(FILE *fp)
905 {
906 	struct timeval tv;
907 	struct tm *tm;
908 
909 	gettimeofday(&tv, NULL);
910 	tm = localtime(&tv.tv_sec);
911 
912 	if (timestamp_short) {
913 		char tshort[40];
914 
915 		strftime(tshort, sizeof(tshort), "%Y-%m-%dT%H:%M:%S", tm);
916 		fprintf(fp, "[%s.%06ld] ", tshort, tv.tv_usec);
917 	} else {
918 		char *tstr = asctime(tm);
919 
920 		tstr[strlen(tstr)-1] = 0;
921 		fprintf(fp, "Timestamp: %s %ld usec\n",
922 			tstr, tv.tv_usec);
923 	}
924 
925 	return 0;
926 }
927 
928 int cmdlineno;
929 
930 /* Like glibc getline but handle continuation lines and comments */
getcmdline(char ** linep,size_t * lenp,FILE * in)931 ssize_t getcmdline(char **linep, size_t *lenp, FILE *in)
932 {
933 	ssize_t cc;
934 	char *cp;
935 
936 	if ((cc = getline(linep, lenp, in)) < 0)
937 		return cc;	/* eof or error */
938 	++cmdlineno;
939 
940 	cp = strchr(*linep, '#');
941 	if (cp)
942 		*cp = '\0';
943 
944 	while ((cp = strstr(*linep, "\\\n")) != NULL) {
945 		char *line1 = NULL;
946 		size_t len1 = 0;
947 		ssize_t cc1;
948 
949 		if ((cc1 = getline(&line1, &len1, in)) < 0) {
950 			fprintf(stderr, "Missing continuation line\n");
951 			return cc1;
952 		}
953 
954 		++cmdlineno;
955 		*cp = 0;
956 
957 		cp = strchr(line1, '#');
958 		if (cp)
959 			*cp = '\0';
960 
961 		*lenp = strlen(*linep) + strlen(line1) + 1;
962 		*linep = realloc(*linep, *lenp);
963 		if (!*linep) {
964 			fprintf(stderr, "Out of memory\n");
965 			*lenp = 0;
966 			return -1;
967 		}
968 		cc += cc1 - 2;
969 		strcat(*linep, line1);
970 		free(line1);
971 	}
972 	return cc;
973 }
974 
975 /* split command line into argument vector */
makeargs(char * line,char * argv[],int maxargs)976 int makeargs(char *line, char *argv[], int maxargs)
977 {
978 	static const char ws[] = " \t\r\n";
979 	char *cp;
980 	int argc = 0;
981 
982 	for (cp = line + strspn(line, ws); *cp; cp += strspn(cp, ws)) {
983 		if (argc >= (maxargs - 1)) {
984 			fprintf(stderr, "Too many arguments to command\n");
985 			exit(1);
986 		}
987 
988 		/* word begins with quote */
989 		if (*cp == '\'' || *cp == '"') {
990 			char quote = *cp++;
991 
992 			argv[argc++] = cp;
993 			/* find ending quote */
994 			cp = strchr(cp, quote);
995 			if (cp == NULL) {
996 				fprintf(stderr, "Unterminated quoted string\n");
997 				exit(1);
998 			}
999 			*cp++ = 0;
1000 			continue;
1001 		}
1002 
1003 		argv[argc++] = cp;
1004 		/* find end of word */
1005 		cp += strcspn(cp, ws);
1006 		*cp++ = 0;
1007 	}
1008 	argv[argc] = NULL;
1009 
1010 	return argc;
1011 }
1012 
inet_get_addr(const char * src,__u32 * dst,struct in6_addr * dst6)1013 int inet_get_addr(const char *src, __u32 *dst, struct in6_addr *dst6)
1014 {
1015 	if (strchr(src, ':'))
1016 		return inet_pton(AF_INET6, src, dst6);
1017 	else
1018 		return inet_pton(AF_INET, src, dst);
1019 }
1020 
print_nlmsg_timestamp(FILE * fp,const struct nlmsghdr * n)1021 void print_nlmsg_timestamp(FILE *fp, const struct nlmsghdr *n)
1022 {
1023 	char *tstr;
1024 	time_t secs = ((__u32*)NLMSG_DATA(n))[0];
1025 	long usecs = ((__u32*)NLMSG_DATA(n))[1];
1026 	tstr = asctime(localtime(&secs));
1027 	tstr[strlen(tstr)-1] = 0;
1028 	fprintf(fp, "Timestamp: %s %lu us\n", tstr, usecs);
1029 }
1030 
on_netns(char * nsname,void * arg)1031 static int on_netns(char *nsname, void *arg)
1032 {
1033 	struct netns_func *f = arg;
1034 
1035 	if (netns_switch(nsname))
1036 		return -1;
1037 
1038 	return f->func(nsname, f->arg);
1039 }
1040 
on_netns_label(char * nsname,void * arg)1041 static int on_netns_label(char *nsname, void *arg)
1042 {
1043 	printf("\nnetns: %s\n", nsname);
1044 	return on_netns(nsname, arg);
1045 }
1046 
do_each_netns(int (* func)(char * nsname,void * arg),void * arg,bool show_label)1047 int do_each_netns(int (*func)(char *nsname, void *arg), void *arg,
1048 		bool show_label)
1049 {
1050 	struct netns_func nsf = { .func = func, .arg = arg };
1051 
1052 	if (show_label)
1053 		return netns_foreach(on_netns_label, &nsf);
1054 
1055 	return netns_foreach(on_netns, &nsf);
1056 }
1057 
int_to_str(int val,char * buf)1058 char *int_to_str(int val, char *buf)
1059 {
1060 	sprintf(buf, "%d", val);
1061 	return buf;
1062 }
1063