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