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