]> git.proxmox.com Git - mirror_iproute2.git/blob - lib/utils.c
util: spelling fix
[mirror_iproute2.git] / lib / utils.c
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 <fcntl.h>
18 #include <limits.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <string.h>
22 #include <ctype.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 <linux/snmp.h>
31 #include <time.h>
32 #include <sys/time.h>
33 #include <errno.h>
34 #ifdef HAVE_LIBCAP
35 #include <sys/capability.h>
36 #endif
37
38 #include "rt_names.h"
39 #include "utils.h"
40 #include "ll_map.h"
41 #include "namespace.h"
42
43 int resolve_hosts;
44 int timestamp_short;
45 int pretty;
46 const char *_SL_ = "\n";
47
48 int read_prop(const char *dev, char *prop, long *value)
49 {
50 char fname[128], buf[80], *endp, *nl;
51 FILE *fp;
52 long result;
53 int ret;
54
55 ret = snprintf(fname, sizeof(fname), "/sys/class/net/%s/%s",
56 dev, prop);
57
58 if (ret <= 0 || ret >= sizeof(fname)) {
59 fprintf(stderr, "could not build pathname for property\n");
60 return -1;
61 }
62
63 fp = fopen(fname, "r");
64 if (fp == NULL) {
65 fprintf(stderr, "fopen %s: %s\n", fname, strerror(errno));
66 return -1;
67 }
68
69 if (!fgets(buf, sizeof(buf), fp)) {
70 fprintf(stderr, "property \"%s\" in file %s is currently unknown\n", prop, fname);
71 fclose(fp);
72 goto out;
73 }
74
75 nl = strchr(buf, '\n');
76 if (nl)
77 *nl = '\0';
78
79 fclose(fp);
80 result = strtol(buf, &endp, 0);
81
82 if (*endp || buf == endp) {
83 fprintf(stderr, "value \"%s\" in file %s is not a number\n",
84 buf, fname);
85 goto out;
86 }
87
88 if ((result == LONG_MAX || result == LONG_MIN) && errno == ERANGE) {
89 fprintf(stderr, "strtol %s: %s", fname, strerror(errno));
90 goto out;
91 }
92
93 *value = result;
94 return 0;
95 out:
96 fprintf(stderr, "Failed to parse %s\n", fname);
97 return -1;
98 }
99
100 /* Parse a percent e.g: '30%'
101 * return: 0 = ok, -1 = error, 1 = out of range
102 */
103 int parse_percent(double *val, const char *str)
104 {
105 char *p;
106
107 *val = strtod(str, &p) / 100.;
108 if (*val == HUGE_VALF || *val == HUGE_VALL)
109 return 1;
110 if (*p && strcmp(p, "%"))
111 return -1;
112
113 return 0;
114 }
115
116 int get_hex(char c)
117 {
118 if (c >= 'A' && c <= 'F')
119 return c - 'A' + 10;
120 if (c >= 'a' && c <= 'f')
121 return c - 'a' + 10;
122 if (c >= '0' && c <= '9')
123 return c - '0';
124
125 return -1;
126 }
127
128 int get_integer(int *val, const char *arg, int base)
129 {
130 long res;
131 char *ptr;
132
133 if (!arg || !*arg)
134 return -1;
135
136 res = strtol(arg, &ptr, base);
137
138 /* If there were no digits at all, strtol() stores
139 * the original value of nptr in *endptr (and returns 0).
140 * In particular, if *nptr is not '\0' but **endptr is '\0' on return,
141 * the entire string is valid.
142 */
143 if (!ptr || ptr == arg || *ptr)
144 return -1;
145
146 /* If an underflow occurs, strtol() returns LONG_MIN.
147 * If an overflow occurs, strtol() returns LONG_MAX.
148 * In both cases, errno is set to ERANGE.
149 */
150 if ((res == LONG_MAX || res == LONG_MIN) && errno == ERANGE)
151 return -1;
152
153 /* Outside range of int */
154 if (res < INT_MIN || res > INT_MAX)
155 return -1;
156
157 *val = res;
158 return 0;
159 }
160
161 int mask2bits(__u32 netmask)
162 {
163 unsigned int bits = 0;
164 __u32 mask = ntohl(netmask);
165 __u32 host = ~mask;
166
167 /* a valid netmask must be 2^n - 1 */
168 if ((host & (host + 1)) != 0)
169 return -1;
170
171 for (; mask; mask <<= 1)
172 ++bits;
173 return bits;
174 }
175
176 static int get_netmask(unsigned int *val, const char *arg, int base)
177 {
178 inet_prefix addr;
179
180 if (!get_unsigned(val, arg, base))
181 return 0;
182
183 /* try coverting dotted quad to CIDR */
184 if (!get_addr_1(&addr, arg, AF_INET) && addr.family == AF_INET) {
185 int b = mask2bits(addr.data[0]);
186
187 if (b >= 0) {
188 *val = b;
189 return 0;
190 }
191 }
192
193 return -1;
194 }
195
196 int get_unsigned(unsigned int *val, const char *arg, int base)
197 {
198 unsigned long res;
199 char *ptr;
200
201 if (!arg || !*arg)
202 return -1;
203
204 res = strtoul(arg, &ptr, base);
205
206 /* empty string or trailing non-digits */
207 if (!ptr || ptr == arg || *ptr)
208 return -1;
209
210 /* overflow */
211 if (res == ULONG_MAX && errno == ERANGE)
212 return -1;
213
214 /* out side range of unsigned */
215 if (res > UINT_MAX)
216 return -1;
217
218 *val = res;
219 return 0;
220 }
221
222 /*
223 * get_time_rtt is "translated" from a similar routine "get_time" in
224 * tc_util.c. We don't use the exact same routine because tc passes
225 * microseconds to the kernel and the callers of get_time_rtt want to
226 * pass milliseconds (standard unit for rtt values since 2.6.27), and
227 * have a different assumption for the units of a "raw" number.
228 */
229 int get_time_rtt(unsigned int *val, const char *arg, int *raw)
230 {
231 double t;
232 unsigned long res;
233 char *p;
234
235 if (strchr(arg, '.') != NULL) {
236 t = strtod(arg, &p);
237 if (t < 0.0)
238 return -1;
239
240 /* no digits? */
241 if (!p || p == arg)
242 return -1;
243
244 /* over/underflow */
245 if ((t == HUGE_VALF || t == HUGE_VALL) && errno == ERANGE)
246 return -1;
247 } else {
248 res = strtoul(arg, &p, 0);
249
250 /* empty string? */
251 if (!p || p == arg)
252 return -1;
253
254 /* overflow */
255 if (res == ULONG_MAX && errno == ERANGE)
256 return -1;
257
258 t = (double)res;
259 }
260
261 if (p == arg)
262 return -1;
263 *raw = 1;
264
265 if (*p) {
266 *raw = 0;
267 if (strcasecmp(p, "s") == 0 ||
268 strcasecmp(p, "sec") == 0 ||
269 strcasecmp(p, "secs") == 0)
270 t *= 1000;
271 else if (strcasecmp(p, "ms") == 0 ||
272 strcasecmp(p, "msec") == 0 ||
273 strcasecmp(p, "msecs") == 0)
274 t *= 1.0; /* allow suffix, do nothing */
275 else
276 return -1;
277 }
278
279 /* emulate ceil() without having to bring-in -lm and always be >= 1 */
280 *val = t;
281 if (*val < t)
282 *val += 1;
283
284 return 0;
285
286 }
287
288 int get_u64(__u64 *val, const char *arg, int base)
289 {
290 unsigned long long res;
291 char *ptr;
292
293 if (!arg || !*arg)
294 return -1;
295
296 res = strtoull(arg, &ptr, base);
297
298 /* empty string or trailing non-digits */
299 if (!ptr || ptr == arg || *ptr)
300 return -1;
301
302 /* overflow */
303 if (res == ULLONG_MAX && errno == ERANGE)
304 return -1;
305
306 /* in case ULL is 128 bits */
307 if (res > 0xFFFFFFFFFFFFFFFFULL)
308 return -1;
309
310 *val = res;
311 return 0;
312 }
313
314 int get_u32(__u32 *val, const char *arg, int base)
315 {
316 unsigned long res;
317 char *ptr;
318
319 if (!arg || !*arg)
320 return -1;
321 res = strtoul(arg, &ptr, base);
322
323 /* empty string or trailing non-digits */
324 if (!ptr || ptr == arg || *ptr)
325 return -1;
326
327 /* overflow */
328 if (res == ULONG_MAX && errno == ERANGE)
329 return -1;
330
331 /* in case UL > 32 bits */
332 if (res > 0xFFFFFFFFUL)
333 return -1;
334
335 *val = res;
336 return 0;
337 }
338
339 int get_u16(__u16 *val, const char *arg, int base)
340 {
341 unsigned long res;
342 char *ptr;
343
344 if (!arg || !*arg)
345 return -1;
346 res = strtoul(arg, &ptr, base);
347
348 /* empty string or trailing non-digits */
349 if (!ptr || ptr == arg || *ptr)
350 return -1;
351
352 /* overflow */
353 if (res == ULONG_MAX && errno == ERANGE)
354 return -1;
355
356 if (res > 0xFFFFUL)
357 return -1;
358
359 *val = res;
360 return 0;
361 }
362
363 int get_u8(__u8 *val, const char *arg, int base)
364 {
365 unsigned long res;
366 char *ptr;
367
368 if (!arg || !*arg)
369 return -1;
370
371 res = strtoul(arg, &ptr, base);
372 /* empty string or trailing non-digits */
373 if (!ptr || ptr == arg || *ptr)
374 return -1;
375
376 /* overflow */
377 if (res == ULONG_MAX && errno == ERANGE)
378 return -1;
379
380 if (res > 0xFFUL)
381 return -1;
382
383 *val = res;
384 return 0;
385 }
386
387 int get_s32(__s32 *val, const char *arg, int base)
388 {
389 long res;
390 char *ptr;
391
392 errno = 0;
393
394 if (!arg || !*arg)
395 return -1;
396 res = strtol(arg, &ptr, base);
397 if (!ptr || ptr == arg || *ptr)
398 return -1;
399 if ((res == LONG_MIN || res == LONG_MAX) && errno == ERANGE)
400 return -1;
401 if (res > INT32_MAX || res < INT32_MIN)
402 return -1;
403
404 *val = res;
405 return 0;
406 }
407
408 int get_s16(__s16 *val, const char *arg, int base)
409 {
410 long res;
411 char *ptr;
412
413 if (!arg || !*arg)
414 return -1;
415 res = strtol(arg, &ptr, base);
416 if (!ptr || ptr == arg || *ptr)
417 return -1;
418 if ((res == LONG_MIN || res == LONG_MAX) && errno == ERANGE)
419 return -1;
420 if (res > 0x7FFF || res < -0x8000)
421 return -1;
422
423 *val = res;
424 return 0;
425 }
426
427 int get_s8(__s8 *val, const char *arg, int base)
428 {
429 long res;
430 char *ptr;
431
432 if (!arg || !*arg)
433 return -1;
434 res = strtol(arg, &ptr, base);
435 if (!ptr || ptr == arg || *ptr)
436 return -1;
437 if ((res == LONG_MIN || res == LONG_MAX) && errno == ERANGE)
438 return -1;
439 if (res > 0x7F || res < -0x80)
440 return -1;
441 *val = res;
442 return 0;
443 }
444
445 int get_be64(__be64 *val, const char *arg, int base)
446 {
447 __u64 v;
448 int ret = get_u64(&v, arg, base);
449
450 if (!ret)
451 *val = htonll(v);
452
453 return ret;
454 }
455
456 int get_be32(__be32 *val, const char *arg, int base)
457 {
458 __u32 v;
459 int ret = get_u32(&v, arg, base);
460
461 if (!ret)
462 *val = htonl(v);
463
464 return ret;
465 }
466
467 int get_be16(__be16 *val, const char *arg, int base)
468 {
469 __u16 v;
470 int ret = get_u16(&v, arg, base);
471
472 if (!ret)
473 *val = htons(v);
474
475 return ret;
476 }
477
478 /* This uses a non-standard parsing (ie not inet_aton, or inet_pton)
479 * because of legacy choice to parse 10.8 as 10.8.0.0 not 10.0.0.8
480 */
481 static int get_addr_ipv4(__u8 *ap, const char *cp)
482 {
483 int i;
484
485 for (i = 0; i < 4; i++) {
486 unsigned long n;
487 char *endp;
488
489 n = strtoul(cp, &endp, 0);
490 if (n > 255)
491 return -1; /* bogus network value */
492
493 if (endp == cp) /* no digits */
494 return -1;
495
496 ap[i] = n;
497
498 if (*endp == '\0')
499 break;
500
501 if (i == 3 || *endp != '.')
502 return -1; /* extra characters */
503 cp = endp + 1;
504 }
505
506 return 1;
507 }
508
509 int get_addr64(__u64 *ap, const char *cp)
510 {
511 int i;
512
513 union {
514 __u16 v16[4];
515 __u64 v64;
516 } val;
517
518 for (i = 0; i < 4; i++) {
519 unsigned long n;
520 char *endp;
521
522 n = strtoul(cp, &endp, 16);
523 if (n > 0xffff)
524 return -1; /* bogus network value */
525
526 if (endp == cp) /* no digits */
527 return -1;
528
529 val.v16[i] = htons(n);
530
531 if (*endp == '\0')
532 break;
533
534 if (i == 3 || *endp != ':')
535 return -1; /* extra characters */
536 cp = endp + 1;
537 }
538
539 *ap = val.v64;
540
541 return 1;
542 }
543
544 static void set_address_type(inet_prefix *addr)
545 {
546 switch (addr->family) {
547 case AF_INET:
548 if (!addr->data[0])
549 addr->flags |= ADDRTYPE_INET_UNSPEC;
550 else if (IN_MULTICAST(ntohl(addr->data[0])))
551 addr->flags |= ADDRTYPE_INET_MULTI;
552 else
553 addr->flags |= ADDRTYPE_INET;
554 break;
555 case AF_INET6:
556 if (IN6_IS_ADDR_UNSPECIFIED(addr->data))
557 addr->flags |= ADDRTYPE_INET_UNSPEC;
558 else if (IN6_IS_ADDR_MULTICAST(addr->data))
559 addr->flags |= ADDRTYPE_INET_MULTI;
560 else
561 addr->flags |= ADDRTYPE_INET;
562 break;
563 }
564 }
565
566 static int __get_addr_1(inet_prefix *addr, const char *name, int family)
567 {
568 memset(addr, 0, sizeof(*addr));
569
570 if (strcmp(name, "default") == 0) {
571 if ((family == AF_DECnet) || (family == AF_MPLS))
572 return -1;
573 addr->family = family;
574 addr->bytelen = af_byte_len(addr->family);
575 addr->bitlen = -2;
576 addr->flags |= PREFIXLEN_SPECIFIED;
577 return 0;
578 }
579
580 if (strcmp(name, "all") == 0 ||
581 strcmp(name, "any") == 0) {
582 if ((family == AF_DECnet) || (family == AF_MPLS))
583 return -1;
584 addr->family = family;
585 addr->bytelen = 0;
586 addr->bitlen = -2;
587 return 0;
588 }
589
590 if (family == AF_PACKET) {
591 int len;
592
593 len = ll_addr_a2n((char *) &addr->data, sizeof(addr->data),
594 name);
595 if (len < 0)
596 return -1;
597
598 addr->family = AF_PACKET;
599 addr->bytelen = len;
600 addr->bitlen = len * 8;
601 return 0;
602 }
603
604 if (strchr(name, ':')) {
605 addr->family = AF_INET6;
606 if (family != AF_UNSPEC && family != AF_INET6)
607 return -1;
608 if (inet_pton(AF_INET6, name, addr->data) <= 0)
609 return -1;
610 addr->bytelen = 16;
611 addr->bitlen = -1;
612 return 0;
613 }
614
615 if (family == AF_DECnet) {
616 struct dn_naddr dna;
617
618 addr->family = AF_DECnet;
619 if (dnet_pton(AF_DECnet, name, &dna) <= 0)
620 return -1;
621 memcpy(addr->data, dna.a_addr, 2);
622 addr->bytelen = 2;
623 addr->bitlen = -1;
624 return 0;
625 }
626
627 if (family == AF_MPLS) {
628 unsigned int maxlabels;
629 int i;
630
631 addr->family = AF_MPLS;
632 if (mpls_pton(AF_MPLS, name, addr->data,
633 sizeof(addr->data)) <= 0)
634 return -1;
635 addr->bytelen = 4;
636 addr->bitlen = 20;
637 /* How many bytes do I need? */
638 maxlabels = sizeof(addr->data) / sizeof(struct mpls_label);
639 for (i = 0; i < maxlabels; i++) {
640 if (ntohl(addr->data[i]) & MPLS_LS_S_MASK) {
641 addr->bytelen = (i + 1)*4;
642 break;
643 }
644 }
645 return 0;
646 }
647
648 addr->family = AF_INET;
649 if (family != AF_UNSPEC && family != AF_INET)
650 return -1;
651
652 if (get_addr_ipv4((__u8 *)addr->data, name) <= 0)
653 return -1;
654
655 addr->bytelen = 4;
656 addr->bitlen = -1;
657 return 0;
658 }
659
660 int get_addr_1(inet_prefix *addr, const char *name, int family)
661 {
662 int ret;
663
664 ret = __get_addr_1(addr, name, family);
665 if (ret)
666 return ret;
667
668 set_address_type(addr);
669 return 0;
670 }
671
672 int af_bit_len(int af)
673 {
674 switch (af) {
675 case AF_INET6:
676 return 128;
677 case AF_INET:
678 return 32;
679 case AF_DECnet:
680 return 16;
681 case AF_IPX:
682 return 80;
683 case AF_MPLS:
684 return 20;
685 }
686
687 return 0;
688 }
689
690 int af_byte_len(int af)
691 {
692 return af_bit_len(af) / 8;
693 }
694
695 int get_prefix_1(inet_prefix *dst, char *arg, int family)
696 {
697 char *slash;
698 int err, bitlen, flags;
699
700 slash = strchr(arg, '/');
701 if (slash)
702 *slash = 0;
703
704 err = get_addr_1(dst, arg, family);
705
706 if (slash)
707 *slash = '/';
708
709 if (err)
710 return err;
711
712 bitlen = af_bit_len(dst->family);
713
714 flags = 0;
715 if (slash) {
716 unsigned int plen;
717
718 if (dst->bitlen == -2)
719 return -1;
720 if (get_netmask(&plen, slash + 1, 0))
721 return -1;
722 if (plen > bitlen)
723 return -1;
724
725 flags |= PREFIXLEN_SPECIFIED;
726 bitlen = plen;
727 } else {
728 if (dst->bitlen == -2)
729 bitlen = 0;
730 }
731
732 dst->flags |= flags;
733 dst->bitlen = bitlen;
734
735 return 0;
736 }
737
738 static const char *family_name_verbose(int family)
739 {
740 if (family == AF_UNSPEC)
741 return "any valid";
742 return family_name(family);
743 }
744
745 int get_addr(inet_prefix *dst, const char *arg, int family)
746 {
747 if (get_addr_1(dst, arg, family)) {
748 fprintf(stderr,
749 "Error: %s address is expected rather than \"%s\".\n",
750 family_name_verbose(family), arg);
751 exit(1);
752 }
753 return 0;
754 }
755
756 int get_addr_rta(inet_prefix *dst, const struct rtattr *rta, int family)
757 {
758 const int len = RTA_PAYLOAD(rta);
759 const void *data = RTA_DATA(rta);
760
761 switch (len) {
762 case 4:
763 dst->family = AF_INET;
764 dst->bytelen = 4;
765 memcpy(dst->data, data, 4);
766 break;
767 case 16:
768 dst->family = AF_INET6;
769 dst->bytelen = 16;
770 memcpy(dst->data, data, 16);
771 break;
772 case 2:
773 dst->family = AF_DECnet;
774 dst->bytelen = 2;
775 memcpy(dst->data, data, 2);
776 break;
777 case 10:
778 dst->family = AF_IPX;
779 dst->bytelen = 10;
780 memcpy(dst->data, data, 10);
781 break;
782 default:
783 return -1;
784 }
785
786 if (family != AF_UNSPEC && family != dst->family)
787 return -2;
788
789 dst->bitlen = -1;
790 dst->flags = 0;
791
792 set_address_type(dst);
793 return 0;
794 }
795
796 int get_prefix(inet_prefix *dst, char *arg, int family)
797 {
798 if (family == AF_PACKET) {
799 fprintf(stderr,
800 "Error: \"%s\" may be inet prefix, but it is not allowed in this context.\n",
801 arg);
802 exit(1);
803 }
804
805 if (get_prefix_1(dst, arg, family)) {
806 fprintf(stderr,
807 "Error: %s prefix is expected rather than \"%s\".\n",
808 family_name_verbose(family), arg);
809 exit(1);
810 }
811 return 0;
812 }
813
814 __u32 get_addr32(const char *name)
815 {
816 inet_prefix addr;
817
818 if (get_addr_1(&addr, name, AF_INET)) {
819 fprintf(stderr,
820 "Error: an IP address is expected rather than \"%s\"\n",
821 name);
822 exit(1);
823 }
824 return addr.data[0];
825 }
826
827 void incomplete_command(void)
828 {
829 fprintf(stderr, "Command line is not complete. Try option \"help\"\n");
830 exit(-1);
831 }
832
833 void missarg(const char *key)
834 {
835 fprintf(stderr, "Error: argument \"%s\" is required\n", key);
836 exit(-1);
837 }
838
839 void invarg(const char *msg, const char *arg)
840 {
841 fprintf(stderr, "Error: argument \"%s\" is wrong: %s\n", arg, msg);
842 exit(-1);
843 }
844
845 void duparg(const char *key, const char *arg)
846 {
847 fprintf(stderr,
848 "Error: duplicate \"%s\": \"%s\" is the second value.\n",
849 key, arg);
850 exit(-1);
851 }
852
853 void duparg2(const char *key, const char *arg)
854 {
855 fprintf(stderr,
856 "Error: either \"%s\" is duplicate, or \"%s\" is a garbage.\n",
857 key, arg);
858 exit(-1);
859 }
860
861 int nodev(const char *dev)
862 {
863 fprintf(stderr, "Cannot find device \"%s\"\n", dev);
864 return -1;
865 }
866
867 int check_ifname(const char *name)
868 {
869 /* These checks mimic kernel checks in dev_valid_name */
870 if (*name == '\0')
871 return -1;
872 if (strlen(name) >= IFNAMSIZ)
873 return -1;
874
875 while (*name) {
876 if (*name == '/' || isspace(*name))
877 return -1;
878 ++name;
879 }
880 return 0;
881 }
882
883 /* buf is assumed to be IFNAMSIZ */
884 int get_ifname(char *buf, const char *name)
885 {
886 int ret;
887
888 ret = check_ifname(name);
889 if (ret == 0)
890 strncpy(buf, name, IFNAMSIZ);
891
892 return ret;
893 }
894
895 const char *get_ifname_rta(int ifindex, const struct rtattr *rta)
896 {
897 const char *name;
898
899 if (rta) {
900 name = rta_getattr_str(rta);
901 } else {
902 fprintf(stderr,
903 "BUG: device with ifindex %d has nil ifname\n",
904 ifindex);
905 name = ll_idx_n2a(ifindex);
906 }
907
908 if (check_ifname(name))
909 return NULL;
910
911 return name;
912 }
913
914 int matches(const char *cmd, const char *pattern)
915 {
916 int len = strlen(cmd);
917
918 if (len > strlen(pattern))
919 return -1;
920 return memcmp(pattern, cmd, len);
921 }
922
923 int inet_addr_match(const inet_prefix *a, const inet_prefix *b, int bits)
924 {
925 const __u32 *a1 = a->data;
926 const __u32 *a2 = b->data;
927 int words = bits >> 0x05;
928
929 bits &= 0x1f;
930
931 if (words)
932 if (memcmp(a1, a2, words << 2))
933 return -1;
934
935 if (bits) {
936 __u32 w1, w2;
937 __u32 mask;
938
939 w1 = a1[words];
940 w2 = a2[words];
941
942 mask = htonl((0xffffffff) << (0x20 - bits));
943
944 if ((w1 ^ w2) & mask)
945 return 1;
946 }
947
948 return 0;
949 }
950
951 int inet_addr_match_rta(const inet_prefix *m, const struct rtattr *rta)
952 {
953 inet_prefix dst;
954
955 if (!rta || m->family == AF_UNSPEC || m->bitlen <= 0)
956 return 0;
957
958 if (get_addr_rta(&dst, rta, m->family))
959 return -1;
960
961 return inet_addr_match(&dst, m, m->bitlen);
962 }
963
964 int __iproute2_hz_internal;
965
966 int __get_hz(void)
967 {
968 char name[1024];
969 int hz = 0;
970 FILE *fp;
971
972 if (getenv("HZ"))
973 return atoi(getenv("HZ")) ? : HZ;
974
975 if (getenv("PROC_NET_PSCHED"))
976 snprintf(name, sizeof(name)-1,
977 "%s", getenv("PROC_NET_PSCHED"));
978 else if (getenv("PROC_ROOT"))
979 snprintf(name, sizeof(name)-1,
980 "%s/net/psched", getenv("PROC_ROOT"));
981 else
982 strcpy(name, "/proc/net/psched");
983
984 fp = fopen(name, "r");
985
986 if (fp) {
987 unsigned int nom, denom;
988
989 if (fscanf(fp, "%*08x%*08x%08x%08x", &nom, &denom) == 2)
990 if (nom == 1000000)
991 hz = denom;
992 fclose(fp);
993 }
994 if (hz)
995 return hz;
996 return HZ;
997 }
998
999 int __iproute2_user_hz_internal;
1000
1001 int __get_user_hz(void)
1002 {
1003 return sysconf(_SC_CLK_TCK);
1004 }
1005
1006 const char *rt_addr_n2a_r(int af, int len,
1007 const void *addr, char *buf, int buflen)
1008 {
1009 switch (af) {
1010 case AF_INET:
1011 case AF_INET6:
1012 return inet_ntop(af, addr, buf, buflen);
1013 case AF_MPLS:
1014 return mpls_ntop(af, addr, buf, buflen);
1015 case AF_IPX:
1016 return ipx_ntop(af, addr, buf, buflen);
1017 case AF_DECnet:
1018 {
1019 struct dn_naddr dna = { 2, { 0, 0, } };
1020
1021 memcpy(dna.a_addr, addr, 2);
1022 return dnet_ntop(af, &dna, buf, buflen);
1023 }
1024 case AF_PACKET:
1025 return ll_addr_n2a(addr, len, ARPHRD_VOID, buf, buflen);
1026 case AF_BRIDGE:
1027 {
1028 const union {
1029 struct sockaddr sa;
1030 struct sockaddr_in sin;
1031 struct sockaddr_in6 sin6;
1032 } *sa = addr;
1033
1034 switch (sa->sa.sa_family) {
1035 case AF_INET:
1036 return inet_ntop(AF_INET, &sa->sin.sin_addr,
1037 buf, buflen);
1038 case AF_INET6:
1039 return inet_ntop(AF_INET6, &sa->sin6.sin6_addr,
1040 buf, buflen);
1041 }
1042
1043 /* fallthrough */
1044 }
1045 default:
1046 return "???";
1047 }
1048 }
1049
1050 const char *rt_addr_n2a(int af, int len, const void *addr)
1051 {
1052 static char buf[256];
1053
1054 return rt_addr_n2a_r(af, len, addr, buf, 256);
1055 }
1056
1057 int read_family(const char *name)
1058 {
1059 int family = AF_UNSPEC;
1060
1061 if (strcmp(name, "inet") == 0)
1062 family = AF_INET;
1063 else if (strcmp(name, "inet6") == 0)
1064 family = AF_INET6;
1065 else if (strcmp(name, "dnet") == 0)
1066 family = AF_DECnet;
1067 else if (strcmp(name, "link") == 0)
1068 family = AF_PACKET;
1069 else if (strcmp(name, "ipx") == 0)
1070 family = AF_IPX;
1071 else if (strcmp(name, "mpls") == 0)
1072 family = AF_MPLS;
1073 else if (strcmp(name, "bridge") == 0)
1074 family = AF_BRIDGE;
1075 return family;
1076 }
1077
1078 const char *family_name(int family)
1079 {
1080 if (family == AF_INET)
1081 return "inet";
1082 if (family == AF_INET6)
1083 return "inet6";
1084 if (family == AF_DECnet)
1085 return "dnet";
1086 if (family == AF_PACKET)
1087 return "link";
1088 if (family == AF_IPX)
1089 return "ipx";
1090 if (family == AF_MPLS)
1091 return "mpls";
1092 if (family == AF_BRIDGE)
1093 return "bridge";
1094 return "???";
1095 }
1096
1097 #ifdef RESOLVE_HOSTNAMES
1098 struct namerec {
1099 struct namerec *next;
1100 const char *name;
1101 inet_prefix addr;
1102 };
1103
1104 #define NHASH 257
1105 static struct namerec *nht[NHASH];
1106
1107 static const char *resolve_address(const void *addr, int len, int af)
1108 {
1109 struct namerec *n;
1110 struct hostent *h_ent;
1111 unsigned int hash;
1112 static int notfirst;
1113
1114
1115 if (af == AF_INET6 && ((__u32 *)addr)[0] == 0 &&
1116 ((__u32 *)addr)[1] == 0 && ((__u32 *)addr)[2] == htonl(0xffff)) {
1117 af = AF_INET;
1118 addr += 12;
1119 len = 4;
1120 }
1121
1122 hash = *(__u32 *)(addr + len - 4) % NHASH;
1123
1124 for (n = nht[hash]; n; n = n->next) {
1125 if (n->addr.family == af &&
1126 n->addr.bytelen == len &&
1127 memcmp(n->addr.data, addr, len) == 0)
1128 return n->name;
1129 }
1130 n = malloc(sizeof(*n));
1131 if (n == NULL)
1132 return NULL;
1133 n->addr.family = af;
1134 n->addr.bytelen = len;
1135 n->name = NULL;
1136 memcpy(n->addr.data, addr, len);
1137 n->next = nht[hash];
1138 nht[hash] = n;
1139 if (++notfirst == 1)
1140 sethostent(1);
1141 fflush(stdout);
1142
1143 h_ent = gethostbyaddr(addr, len, af);
1144 if (h_ent != NULL)
1145 n->name = strdup(h_ent->h_name);
1146
1147 /* Even if we fail, "negative" entry is remembered. */
1148 return n->name;
1149 }
1150 #endif
1151
1152 const char *format_host_r(int af, int len, const void *addr,
1153 char *buf, int buflen)
1154 {
1155 #ifdef RESOLVE_HOSTNAMES
1156 if (resolve_hosts) {
1157 const char *n;
1158
1159 len = len <= 0 ? af_byte_len(af) : len;
1160
1161 if (len > 0 &&
1162 (n = resolve_address(addr, len, af)) != NULL)
1163 return n;
1164 }
1165 #endif
1166 return rt_addr_n2a_r(af, len, addr, buf, buflen);
1167 }
1168
1169 const char *format_host(int af, int len, const void *addr)
1170 {
1171 static char buf[256];
1172
1173 return format_host_r(af, len, addr, buf, 256);
1174 }
1175
1176
1177 char *hexstring_n2a(const __u8 *str, int len, char *buf, int blen)
1178 {
1179 char *ptr = buf;
1180 int i;
1181
1182 for (i = 0; i < len; i++) {
1183 if (blen < 3)
1184 break;
1185 sprintf(ptr, "%02x", str[i]);
1186 ptr += 2;
1187 blen -= 2;
1188 }
1189 return buf;
1190 }
1191
1192 __u8 *hexstring_a2n(const char *str, __u8 *buf, int blen, unsigned int *len)
1193 {
1194 unsigned int cnt = 0;
1195 char *endptr;
1196
1197 if (strlen(str) % 2)
1198 return NULL;
1199 while (cnt < blen && strlen(str) > 1) {
1200 unsigned int tmp;
1201 char tmpstr[3];
1202
1203 strncpy(tmpstr, str, 2);
1204 tmpstr[2] = '\0';
1205 errno = 0;
1206 tmp = strtoul(tmpstr, &endptr, 16);
1207 if (errno != 0 || tmp > 0xFF || *endptr != '\0')
1208 return NULL;
1209 buf[cnt++] = tmp;
1210 str += 2;
1211 }
1212
1213 if (len)
1214 *len = cnt;
1215
1216 return buf;
1217 }
1218
1219 int hex2mem(const char *buf, uint8_t *mem, int count)
1220 {
1221 int i, j;
1222 int c;
1223
1224 for (i = 0, j = 0; i < count; i++, j += 2) {
1225 c = get_hex(buf[j]);
1226 if (c < 0)
1227 return -1;
1228
1229 mem[i] = c << 4;
1230
1231 c = get_hex(buf[j + 1]);
1232 if (c < 0)
1233 return -1;
1234
1235 mem[i] |= c;
1236 }
1237
1238 return 0;
1239 }
1240
1241 int addr64_n2a(__u64 addr, char *buff, size_t len)
1242 {
1243 __u16 *words = (__u16 *)&addr;
1244 __u16 v;
1245 int i, ret;
1246 size_t written = 0;
1247 char *sep = ":";
1248
1249 for (i = 0; i < 4; i++) {
1250 v = ntohs(words[i]);
1251
1252 if (i == 3)
1253 sep = "";
1254
1255 ret = snprintf(&buff[written], len - written, "%x%s", v, sep);
1256 if (ret < 0)
1257 return ret;
1258
1259 written += ret;
1260 }
1261
1262 return written;
1263 }
1264
1265 /* Print buffer and escape bytes that are !isprint or among 'escape' */
1266 void print_escape_buf(const __u8 *buf, size_t len, const char *escape)
1267 {
1268 size_t i;
1269
1270 for (i = 0; i < len; ++i) {
1271 if (isprint(buf[i]) && buf[i] != '\\' &&
1272 !strchr(escape, buf[i]))
1273 printf("%c", buf[i]);
1274 else
1275 printf("\\%03o", buf[i]);
1276 }
1277 }
1278
1279 int print_timestamp(FILE *fp)
1280 {
1281 struct timeval tv;
1282 struct tm *tm;
1283
1284 gettimeofday(&tv, NULL);
1285 tm = localtime(&tv.tv_sec);
1286
1287 if (timestamp_short) {
1288 char tshort[40];
1289
1290 strftime(tshort, sizeof(tshort), "%Y-%m-%dT%H:%M:%S", tm);
1291 fprintf(fp, "[%s.%06ld] ", tshort, tv.tv_usec);
1292 } else {
1293 char *tstr = asctime(tm);
1294
1295 tstr[strlen(tstr)-1] = 0;
1296 fprintf(fp, "Timestamp: %s %ld usec\n",
1297 tstr, tv.tv_usec);
1298 }
1299
1300 return 0;
1301 }
1302
1303 unsigned int print_name_and_link(const char *fmt,
1304 const char *name, struct rtattr *tb[])
1305 {
1306 const char *link = NULL;
1307 unsigned int m_flag = 0;
1308 SPRINT_BUF(b1);
1309
1310 if (tb[IFLA_LINK]) {
1311 int iflink = rta_getattr_u32(tb[IFLA_LINK]);
1312
1313 if (iflink) {
1314 if (tb[IFLA_LINK_NETNSID]) {
1315 if (is_json_context()) {
1316 print_int(PRINT_JSON,
1317 "link_index", NULL, iflink);
1318 } else {
1319 link = ll_idx_n2a(iflink);
1320 }
1321 } else {
1322 link = ll_index_to_name(iflink);
1323
1324 if (is_json_context()) {
1325 print_string(PRINT_JSON,
1326 "link", NULL, link);
1327 link = NULL;
1328 }
1329
1330 m_flag = ll_index_to_flags(iflink);
1331 m_flag = !(m_flag & IFF_UP);
1332 }
1333 } else {
1334 if (is_json_context())
1335 print_null(PRINT_JSON, "link", NULL, NULL);
1336 else
1337 link = "NONE";
1338 }
1339
1340 if (link) {
1341 snprintf(b1, sizeof(b1), "%s@%s", name, link);
1342 name = b1;
1343 }
1344 }
1345
1346 print_color_string(PRINT_ANY, COLOR_IFNAME, "ifname", fmt, name);
1347
1348 return m_flag;
1349 }
1350
1351 int cmdlineno;
1352
1353 /* Like glibc getline but handle continuation lines and comments */
1354 ssize_t getcmdline(char **linep, size_t *lenp, FILE *in)
1355 {
1356 ssize_t cc;
1357 char *cp;
1358
1359 cc = getline(linep, lenp, in);
1360 if (cc < 0)
1361 return cc; /* eof or error */
1362 ++cmdlineno;
1363
1364 cp = strchr(*linep, '#');
1365 if (cp)
1366 *cp = '\0';
1367
1368 while ((cp = strstr(*linep, "\\\n")) != NULL) {
1369 char *line1 = NULL;
1370 size_t len1 = 0;
1371 ssize_t cc1;
1372
1373 cc1 = getline(&line1, &len1, in);
1374 if (cc1 < 0) {
1375 fprintf(stderr, "Missing continuation line\n");
1376 return cc1;
1377 }
1378
1379 ++cmdlineno;
1380 *cp = 0;
1381
1382 cp = strchr(line1, '#');
1383 if (cp)
1384 *cp = '\0';
1385
1386 *lenp = strlen(*linep) + strlen(line1) + 1;
1387 *linep = realloc(*linep, *lenp);
1388 if (!*linep) {
1389 fprintf(stderr, "Out of memory\n");
1390 *lenp = 0;
1391 return -1;
1392 }
1393 cc += cc1 - 2;
1394 strcat(*linep, line1);
1395 free(line1);
1396 }
1397 return cc;
1398 }
1399
1400 /* split command line into argument vector */
1401 int makeargs(char *line, char *argv[], int maxargs)
1402 {
1403 static const char ws[] = " \t\r\n";
1404 char *cp = line;
1405 int argc = 0;
1406
1407 while (*cp) {
1408 /* skip leading whitespace */
1409 cp += strspn(cp, ws);
1410
1411 if (*cp == '\0')
1412 break;
1413
1414 if (argc >= (maxargs - 1)) {
1415 fprintf(stderr, "Too many arguments to command\n");
1416 exit(1);
1417 }
1418
1419 /* word begins with quote */
1420 if (*cp == '\'' || *cp == '"') {
1421 char quote = *cp++;
1422
1423 argv[argc++] = cp;
1424 /* find ending quote */
1425 cp = strchr(cp, quote);
1426 if (cp == NULL) {
1427 fprintf(stderr, "Unterminated quoted string\n");
1428 exit(1);
1429 }
1430 } else {
1431 argv[argc++] = cp;
1432
1433 /* find end of word */
1434 cp += strcspn(cp, ws);
1435 if (*cp == '\0')
1436 break;
1437 }
1438
1439 /* separate words */
1440 *cp++ = 0;
1441 }
1442 argv[argc] = NULL;
1443
1444 return argc;
1445 }
1446
1447 void print_nlmsg_timestamp(FILE *fp, const struct nlmsghdr *n)
1448 {
1449 char *tstr;
1450 time_t secs = ((__u32 *)NLMSG_DATA(n))[0];
1451 long usecs = ((__u32 *)NLMSG_DATA(n))[1];
1452
1453 tstr = asctime(localtime(&secs));
1454 tstr[strlen(tstr)-1] = 0;
1455 fprintf(fp, "Timestamp: %s %lu us\n", tstr, usecs);
1456 }
1457
1458 static int on_netns(char *nsname, void *arg)
1459 {
1460 struct netns_func *f = arg;
1461
1462 if (netns_switch(nsname))
1463 return -1;
1464
1465 return f->func(nsname, f->arg);
1466 }
1467
1468 static int on_netns_label(char *nsname, void *arg)
1469 {
1470 printf("\nnetns: %s\n", nsname);
1471 return on_netns(nsname, arg);
1472 }
1473
1474 int do_each_netns(int (*func)(char *nsname, void *arg), void *arg,
1475 bool show_label)
1476 {
1477 struct netns_func nsf = { .func = func, .arg = arg };
1478
1479 if (show_label)
1480 return netns_foreach(on_netns_label, &nsf);
1481
1482 return netns_foreach(on_netns, &nsf);
1483 }
1484
1485 char *int_to_str(int val, char *buf)
1486 {
1487 sprintf(buf, "%d", val);
1488 return buf;
1489 }
1490
1491 int get_guid(__u64 *guid, const char *arg)
1492 {
1493 unsigned long int tmp;
1494 char *endptr;
1495 int i;
1496
1497 #define GUID_STR_LEN 23
1498 /* Verify strict format: format string must be
1499 * xx:xx:xx:xx:xx:xx:xx:xx where xx can be an arbitrary
1500 * hex digit
1501 */
1502
1503 if (strlen(arg) != GUID_STR_LEN)
1504 return -1;
1505
1506 /* make sure columns are in place */
1507 for (i = 0; i < 7; i++)
1508 if (arg[2 + i * 3] != ':')
1509 return -1;
1510
1511 *guid = 0;
1512 for (i = 0; i < 8; i++) {
1513 tmp = strtoul(arg + i * 3, &endptr, 16);
1514 if (endptr != arg + i * 3 + 2)
1515 return -1;
1516
1517 if (tmp > 255)
1518 return -1;
1519
1520 *guid |= tmp << (56 - 8 * i);
1521 }
1522
1523 return 0;
1524 }
1525
1526 /* This is a necessary workaround for multicast route dumps */
1527 int get_real_family(int rtm_type, int rtm_family)
1528 {
1529 if (rtm_type != RTN_MULTICAST)
1530 return rtm_family;
1531
1532 if (rtm_family == RTNL_FAMILY_IPMR)
1533 return AF_INET;
1534
1535 if (rtm_family == RTNL_FAMILY_IP6MR)
1536 return AF_INET6;
1537
1538 return rtm_family;
1539 }
1540
1541 /* Based on copy_rtnl_link_stats() from kernel at net/core/rtnetlink.c */
1542 static void copy_rtnl_link_stats64(struct rtnl_link_stats64 *stats64,
1543 const struct rtnl_link_stats *stats)
1544 {
1545 __u64 *a = (__u64 *)stats64;
1546 const __u32 *b = (const __u32 *)stats;
1547 const __u32 *e = b + sizeof(*stats) / sizeof(*b);
1548
1549 while (b < e)
1550 *a++ = *b++;
1551 }
1552
1553 #define IPSTATS_MIB_MAX_LEN (__IPSTATS_MIB_MAX * sizeof(__u64))
1554 static void get_snmp_counters(struct rtnl_link_stats64 *stats64,
1555 struct rtattr *s)
1556 {
1557 __u64 *mib = (__u64 *)RTA_DATA(s);
1558
1559 memset(stats64, 0, sizeof(*stats64));
1560
1561 stats64->rx_packets = mib[IPSTATS_MIB_INPKTS];
1562 stats64->rx_bytes = mib[IPSTATS_MIB_INOCTETS];
1563 stats64->tx_packets = mib[IPSTATS_MIB_OUTPKTS];
1564 stats64->tx_bytes = mib[IPSTATS_MIB_OUTOCTETS];
1565 stats64->rx_errors = mib[IPSTATS_MIB_INDISCARDS];
1566 stats64->tx_errors = mib[IPSTATS_MIB_OUTDISCARDS];
1567 stats64->multicast = mib[IPSTATS_MIB_INMCASTPKTS];
1568 stats64->rx_frame_errors = mib[IPSTATS_MIB_CSUMERRORS];
1569 }
1570
1571 int get_rtnl_link_stats_rta(struct rtnl_link_stats64 *stats64,
1572 struct rtattr *tb[])
1573 {
1574 struct rtnl_link_stats stats;
1575 void *s;
1576 struct rtattr *rta;
1577 int size, len;
1578
1579 if (tb[IFLA_STATS64]) {
1580 rta = tb[IFLA_STATS64];
1581 size = sizeof(struct rtnl_link_stats64);
1582 s = stats64;
1583 } else if (tb[IFLA_STATS]) {
1584 rta = tb[IFLA_STATS];
1585 size = sizeof(struct rtnl_link_stats);
1586 s = &stats;
1587 } else if (tb[IFLA_PROTINFO]) {
1588 struct rtattr *ptb[IPSTATS_MIB_MAX_LEN + 1];
1589
1590 parse_rtattr_nested(ptb, IPSTATS_MIB_MAX_LEN,
1591 tb[IFLA_PROTINFO]);
1592 if (ptb[IFLA_INET6_STATS])
1593 get_snmp_counters(stats64, ptb[IFLA_INET6_STATS]);
1594 return sizeof(*stats64);
1595 } else {
1596 return -1;
1597 }
1598
1599 len = RTA_PAYLOAD(rta);
1600 if (len < size)
1601 memset(s + len, 0, size - len);
1602 else
1603 len = size;
1604
1605 memcpy(s, RTA_DATA(rta), len);
1606
1607 if (s != stats64)
1608 copy_rtnl_link_stats64(stats64, s);
1609 return size;
1610 }
1611
1612 #ifdef NEED_STRLCPY
1613 size_t strlcpy(char *dst, const char *src, size_t size)
1614 {
1615 size_t srclen = strlen(src);
1616
1617 if (size) {
1618 size_t minlen = min(srclen, size - 1);
1619
1620 memcpy(dst, src, minlen);
1621 dst[minlen] = '\0';
1622 }
1623 return srclen;
1624 }
1625
1626 size_t strlcat(char *dst, const char *src, size_t size)
1627 {
1628 size_t dlen = strlen(dst);
1629
1630 if (dlen >= size)
1631 return dlen + strlen(src);
1632
1633 return dlen + strlcpy(dst + dlen, src, size - dlen);
1634 }
1635 #endif
1636
1637 void drop_cap(void)
1638 {
1639 #ifdef HAVE_LIBCAP
1640 /* don't harmstring root/sudo */
1641 if (getuid() != 0 && geteuid() != 0) {
1642 cap_t capabilities;
1643 cap_value_t net_admin = CAP_NET_ADMIN;
1644 cap_flag_t inheritable = CAP_INHERITABLE;
1645 cap_flag_value_t is_set;
1646
1647 capabilities = cap_get_proc();
1648 if (!capabilities)
1649 exit(EXIT_FAILURE);
1650 if (cap_get_flag(capabilities, net_admin, inheritable,
1651 &is_set) != 0)
1652 exit(EXIT_FAILURE);
1653 /* apps with ambient caps can fork and call ip */
1654 if (is_set == CAP_CLEAR) {
1655 if (cap_clear(capabilities) != 0)
1656 exit(EXIT_FAILURE);
1657 if (cap_set_proc(capabilities) != 0)
1658 exit(EXIT_FAILURE);
1659 }
1660 cap_free(capabilities);
1661 }
1662 #endif
1663 }