iproute2/ip/ipaddress.c
<<
>>
Prefs
   1/*
   2 * ipaddress.c          "ip address".
   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 <stdarg.h>
  14#include <stdio.h>
  15#include <stdlib.h>
  16#include <unistd.h>
  17#include <inttypes.h>
  18#include <fcntl.h>
  19#include <sys/ioctl.h>
  20#include <sys/socket.h>
  21#include <sys/param.h>
  22#include <errno.h>
  23#include <netinet/in.h>
  24#include <arpa/inet.h>
  25#include <string.h>
  26#include <fnmatch.h>
  27
  28#include <linux/netdevice.h>
  29#include <linux/if_arp.h>
  30#include <linux/if_infiniband.h>
  31#include <linux/sockios.h>
  32#include <linux/net_namespace.h>
  33
  34#include "rt_names.h"
  35#include "utils.h"
  36#include "ll_map.h"
  37#include "ip_common.h"
  38#include "color.h"
  39
  40enum {
  41        IPADD_LIST,
  42        IPADD_FLUSH,
  43        IPADD_SAVE,
  44};
  45
  46static struct link_filter filter;
  47static int do_link;
  48
  49static void usage(void) __attribute__((noreturn));
  50
  51static void usage(void)
  52{
  53        if (do_link)
  54                iplink_usage();
  55
  56        fprintf(stderr,
  57                "Usage: ip address {add|change|replace} IFADDR dev IFNAME [ LIFETIME ]\n"
  58                "                                                      [ CONFFLAG-LIST ]\n"
  59                "       ip address del IFADDR dev IFNAME [mngtmpaddr]\n"
  60                "       ip address {save|flush} [ dev IFNAME ] [ scope SCOPE-ID ]\n"
  61                "                            [ to PREFIX ] [ FLAG-LIST ] [ label LABEL ] [up]\n"
  62                "       ip address [ show [ dev IFNAME ] [ scope SCOPE-ID ] [ master DEVICE ]\n"
  63                "                         [ type TYPE ] [ to PREFIX ] [ FLAG-LIST ]\n"
  64                "                         [ label LABEL ] [up] [ vrf NAME ] ]\n"
  65                "       ip address {showdump|restore}\n"
  66                "IFADDR := PREFIX | ADDR peer PREFIX\n"
  67                "          [ broadcast ADDR ] [ anycast ADDR ]\n"
  68                "          [ label IFNAME ] [ scope SCOPE-ID ] [ metric METRIC ]\n"
  69                "SCOPE-ID := [ host | link | global | NUMBER ]\n"
  70                "FLAG-LIST := [ FLAG-LIST ] FLAG\n"
  71                "FLAG  := [ permanent | dynamic | secondary | primary |\n"
  72                "           [-]tentative | [-]deprecated | [-]dadfailed | temporary |\n"
  73                "           CONFFLAG-LIST ]\n"
  74                "CONFFLAG-LIST := [ CONFFLAG-LIST ] CONFFLAG\n"
  75                "CONFFLAG  := [ home | nodad | mngtmpaddr | noprefixroute | autojoin ]\n"
  76                "LIFETIME := [ valid_lft LFT ] [ preferred_lft LFT ]\n"
  77                "LFT := forever | SECONDS\n");
  78        iplink_types_usage();
  79
  80        exit(-1);
  81}
  82
  83static void print_link_flags(FILE *fp, unsigned int flags, unsigned int mdown)
  84{
  85        open_json_array(PRINT_ANY, is_json_context() ? "flags" : "<");
  86        if (flags & IFF_UP && !(flags & IFF_RUNNING))
  87                print_string(PRINT_ANY, NULL,
  88                             flags ? "%s," : "%s", "NO-CARRIER");
  89        flags &= ~IFF_RUNNING;
  90#define _PF(f) if (flags&IFF_##f) {                                     \
  91                flags &= ~IFF_##f ;                                     \
  92                print_string(PRINT_ANY, NULL, flags ? "%s," : "%s", #f); }
  93        _PF(LOOPBACK);
  94        _PF(BROADCAST);
  95        _PF(POINTOPOINT);
  96        _PF(MULTICAST);
  97        _PF(NOARP);
  98        _PF(ALLMULTI);
  99        _PF(PROMISC);
 100        _PF(MASTER);
 101        _PF(SLAVE);
 102        _PF(DEBUG);
 103        _PF(DYNAMIC);
 104        _PF(AUTOMEDIA);
 105        _PF(PORTSEL);
 106        _PF(NOTRAILERS);
 107        _PF(UP);
 108        _PF(LOWER_UP);
 109        _PF(DORMANT);
 110        _PF(ECHO);
 111#undef _PF
 112        if (flags)
 113                print_hex(PRINT_ANY, NULL, "%x", flags);
 114        if (mdown)
 115                print_string(PRINT_ANY, NULL, ",%s", "M-DOWN");
 116        close_json_array(PRINT_ANY, "> ");
 117}
 118
 119static const char *oper_states[] = {
 120        "UNKNOWN", "NOTPRESENT", "DOWN", "LOWERLAYERDOWN",
 121        "TESTING", "DORMANT",    "UP"
 122};
 123
 124static void print_operstate(FILE *f, __u8 state)
 125{
 126        if (state >= ARRAY_SIZE(oper_states)) {
 127                if (is_json_context())
 128                        print_uint(PRINT_JSON, "operstate_index", NULL, state);
 129                else
 130                        print_0xhex(PRINT_FP, NULL, "state %#llx", state);
 131        } else if (brief) {
 132                print_color_string(PRINT_ANY,
 133                                   oper_state_color(state),
 134                                   "operstate",
 135                                   "%-14s ",
 136                                   oper_states[state]);
 137        } else {
 138                if (is_json_context())
 139                        print_string(PRINT_JSON,
 140                                     "operstate",
 141                                     NULL, oper_states[state]);
 142                else {
 143                        fprintf(f, "state ");
 144                        color_fprintf(f, oper_state_color(state),
 145                                      "%s ", oper_states[state]);
 146                }
 147        }
 148}
 149
 150int get_operstate(const char *name)
 151{
 152        int i;
 153
 154        for (i = 0; i < ARRAY_SIZE(oper_states); i++)
 155                if (strcasecmp(name, oper_states[i]) == 0)
 156                        return i;
 157        return -1;
 158}
 159
 160static void print_queuelen(FILE *f, struct rtattr *tb[IFLA_MAX + 1])
 161{
 162        int qlen;
 163
 164        if (tb[IFLA_TXQLEN])
 165                qlen = rta_getattr_u32(tb[IFLA_TXQLEN]);
 166        else {
 167                struct ifreq ifr = {};
 168                int s = socket(AF_INET, SOCK_STREAM, 0);
 169
 170                if (s < 0)
 171                        return;
 172
 173                strcpy(ifr.ifr_name, rta_getattr_str(tb[IFLA_IFNAME]));
 174                if (ioctl(s, SIOCGIFTXQLEN, &ifr) < 0) {
 175                        fprintf(stderr,
 176                                "ioctl(SIOCGIFTXQLEN) failed: %s\n",
 177                                strerror(errno));
 178                        close(s);
 179                        return;
 180                }
 181                close(s);
 182                qlen = ifr.ifr_qlen;
 183        }
 184        if (qlen)
 185                print_int(PRINT_ANY, "txqlen", "qlen %d", qlen);
 186}
 187
 188static const char *link_modes[] = {
 189        "DEFAULT", "DORMANT"
 190};
 191
 192static void print_linkmode(FILE *f, struct rtattr *tb)
 193{
 194        unsigned int mode = rta_getattr_u8(tb);
 195
 196        if (mode >= ARRAY_SIZE(link_modes))
 197                print_int(PRINT_ANY,
 198                          "linkmode_index",
 199                          "mode %d ",
 200                          mode);
 201        else
 202                print_string(PRINT_ANY,
 203                             "linkmode",
 204                             "mode %s "
 205                             , link_modes[mode]);
 206}
 207
 208static char *parse_link_kind(struct rtattr *tb, bool slave)
 209{
 210        struct rtattr *linkinfo[IFLA_INFO_MAX+1];
 211        int attr = slave ? IFLA_INFO_SLAVE_KIND : IFLA_INFO_KIND;
 212
 213        parse_rtattr_nested(linkinfo, IFLA_INFO_MAX, tb);
 214
 215        if (linkinfo[attr])
 216                return RTA_DATA(linkinfo[attr]);
 217
 218        return "";
 219}
 220
 221static int match_link_kind(struct rtattr **tb, const char *kind, bool slave)
 222{
 223        if (!tb[IFLA_LINKINFO])
 224                return -1;
 225
 226        return strcmp(parse_link_kind(tb[IFLA_LINKINFO], slave), kind);
 227}
 228
 229static void print_linktype(FILE *fp, struct rtattr *tb)
 230{
 231        struct rtattr *linkinfo[IFLA_INFO_MAX+1];
 232        struct link_util *lu;
 233        struct link_util *slave_lu;
 234        char slave[32];
 235
 236        parse_rtattr_nested(linkinfo, IFLA_INFO_MAX, tb);
 237        open_json_object("linkinfo");
 238
 239        if (linkinfo[IFLA_INFO_KIND]) {
 240                const char *kind
 241                        = rta_getattr_str(linkinfo[IFLA_INFO_KIND]);
 242
 243                print_nl();
 244                print_string(PRINT_ANY, "info_kind", "    %s ", kind);
 245
 246                lu = get_link_kind(kind);
 247                if (lu && lu->print_opt) {
 248                        struct rtattr *attr[lu->maxattr+1], **data = NULL;
 249
 250                        if (linkinfo[IFLA_INFO_DATA]) {
 251                                parse_rtattr_nested(attr, lu->maxattr,
 252                                                    linkinfo[IFLA_INFO_DATA]);
 253                                data = attr;
 254                        }
 255                        open_json_object("info_data");
 256                        lu->print_opt(lu, fp, data);
 257                        close_json_object();
 258
 259                        if (linkinfo[IFLA_INFO_XSTATS] && show_stats &&
 260                            lu->print_xstats) {
 261                                open_json_object("info_xstats");
 262                                lu->print_xstats(lu, fp, linkinfo[IFLA_INFO_XSTATS]);
 263                                close_json_object();
 264                        }
 265                }
 266        }
 267
 268        if (linkinfo[IFLA_INFO_SLAVE_KIND]) {
 269                const char *slave_kind
 270                        = rta_getattr_str(linkinfo[IFLA_INFO_SLAVE_KIND]);
 271
 272                print_nl();
 273                print_string(PRINT_ANY,
 274                             "info_slave_kind",
 275                             "    %s_slave ",
 276                             slave_kind);
 277
 278                snprintf(slave, sizeof(slave), "%s_slave", slave_kind);
 279
 280                slave_lu = get_link_kind(slave);
 281                if (slave_lu && slave_lu->print_opt) {
 282                        struct rtattr *attr[slave_lu->maxattr+1], **data = NULL;
 283
 284                        if (linkinfo[IFLA_INFO_SLAVE_DATA]) {
 285                                parse_rtattr_nested(attr, slave_lu->maxattr,
 286                                                    linkinfo[IFLA_INFO_SLAVE_DATA]);
 287                                data = attr;
 288                        }
 289                        open_json_object("info_slave_data");
 290                        slave_lu->print_opt(slave_lu, fp, data);
 291                        close_json_object();
 292                }
 293        }
 294        close_json_object();
 295}
 296
 297static void print_af_spec(FILE *fp, struct rtattr *af_spec_attr)
 298{
 299        struct rtattr *inet6_attr;
 300        struct rtattr *tb[IFLA_INET6_MAX + 1];
 301
 302        inet6_attr = parse_rtattr_one_nested(AF_INET6, af_spec_attr);
 303        if (!inet6_attr)
 304                return;
 305
 306        parse_rtattr_nested(tb, IFLA_INET6_MAX, inet6_attr);
 307
 308        if (tb[IFLA_INET6_ADDR_GEN_MODE]) {
 309                __u8 mode = rta_getattr_u8(tb[IFLA_INET6_ADDR_GEN_MODE]);
 310                SPRINT_BUF(b1);
 311
 312                switch (mode) {
 313                case IN6_ADDR_GEN_MODE_EUI64:
 314                        print_string(PRINT_ANY,
 315                                     "inet6_addr_gen_mode",
 316                                     "addrgenmode %s ",
 317                                     "eui64");
 318                        break;
 319                case IN6_ADDR_GEN_MODE_NONE:
 320                        print_string(PRINT_ANY,
 321                                     "inet6_addr_gen_mode",
 322                                     "addrgenmode %s ",
 323                                     "none");
 324                        break;
 325                case IN6_ADDR_GEN_MODE_STABLE_PRIVACY:
 326                        print_string(PRINT_ANY,
 327                                     "inet6_addr_gen_mode",
 328                                     "addrgenmode %s ",
 329                                     "stable_secret");
 330                        break;
 331                case IN6_ADDR_GEN_MODE_RANDOM:
 332                        print_string(PRINT_ANY,
 333                                     "inet6_addr_gen_mode",
 334                                     "addrgenmode %s ",
 335                                     "random");
 336                        break;
 337                default:
 338                        snprintf(b1, sizeof(b1), "%#.2hhx", mode);
 339                        print_string(PRINT_ANY,
 340                                     "inet6_addr_gen_mode",
 341                                     "addrgenmode %s ",
 342                                     b1);
 343                        break;
 344                }
 345        }
 346}
 347
 348static void print_vf_stats64(FILE *fp, struct rtattr *vfstats);
 349
 350static void print_vfinfo(FILE *fp, struct ifinfomsg *ifi, struct rtattr *vfinfo)
 351{
 352        struct ifla_vf_mac *vf_mac;
 353        struct ifla_vf_broadcast *vf_broadcast;
 354        struct ifla_vf_tx_rate *vf_tx_rate;
 355        struct rtattr *vf[IFLA_VF_MAX + 1] = {};
 356
 357        SPRINT_BUF(b1);
 358
 359        if (vfinfo->rta_type != IFLA_VF_INFO) {
 360                fprintf(stderr, "BUG: rta type is %d\n", vfinfo->rta_type);
 361                return;
 362        }
 363
 364        parse_rtattr_nested(vf, IFLA_VF_MAX, vfinfo);
 365
 366        vf_mac = RTA_DATA(vf[IFLA_VF_MAC]);
 367        vf_broadcast = RTA_DATA(vf[IFLA_VF_BROADCAST]);
 368        vf_tx_rate = RTA_DATA(vf[IFLA_VF_TX_RATE]);
 369
 370        print_string(PRINT_FP, NULL, "%s    ", _SL_);
 371        print_int(PRINT_ANY, "vf", "vf %d ", vf_mac->vf);
 372
 373        print_string(PRINT_ANY,
 374                     "link_type",
 375                     "    link/%s ",
 376                     ll_type_n2a(ifi->ifi_type, b1, sizeof(b1)));
 377
 378        print_color_string(PRINT_ANY, COLOR_MAC,
 379                           "address", "%s",
 380                           ll_addr_n2a((unsigned char *) &vf_mac->mac,
 381                                       ifi->ifi_type == ARPHRD_ETHER ?
 382                                       ETH_ALEN : INFINIBAND_ALEN,
 383                                       ifi->ifi_type,
 384                                       b1, sizeof(b1)));
 385
 386        if (vf[IFLA_VF_BROADCAST]) {
 387                if (ifi->ifi_flags&IFF_POINTOPOINT) {
 388                        print_string(PRINT_FP, NULL, " peer ", NULL);
 389                        print_bool(PRINT_JSON,
 390                                   "link_pointtopoint", NULL, true);
 391                } else
 392                        print_string(PRINT_FP, NULL, " brd ", NULL);
 393
 394                print_color_string(PRINT_ANY, COLOR_MAC,
 395                                   "broadcast", "%s",
 396                                   ll_addr_n2a((unsigned char *) &vf_broadcast->broadcast,
 397                                               ifi->ifi_type == ARPHRD_ETHER ?
 398                                               ETH_ALEN : INFINIBAND_ALEN,
 399                                               ifi->ifi_type,
 400                                               b1, sizeof(b1)));
 401        }
 402
 403        if (vf[IFLA_VF_VLAN_LIST]) {
 404                struct rtattr *i, *vfvlanlist = vf[IFLA_VF_VLAN_LIST];
 405                int rem = RTA_PAYLOAD(vfvlanlist);
 406
 407                open_json_array(PRINT_JSON, "vlan_list");
 408                for (i = RTA_DATA(vfvlanlist);
 409                     RTA_OK(i, rem); i = RTA_NEXT(i, rem)) {
 410                        struct ifla_vf_vlan_info *vf_vlan_info = RTA_DATA(i);
 411                        SPRINT_BUF(b2);
 412
 413                        open_json_object(NULL);
 414                        if (vf_vlan_info->vlan)
 415                                print_int(PRINT_ANY,
 416                                          "vlan",
 417                                          ", vlan %d",
 418                                          vf_vlan_info->vlan);
 419                        if (vf_vlan_info->qos)
 420                                print_int(PRINT_ANY,
 421                                          "qos",
 422                                          ", qos %d",
 423                                          vf_vlan_info->qos);
 424                        if (vf_vlan_info->vlan_proto &&
 425                            vf_vlan_info->vlan_proto != htons(ETH_P_8021Q))
 426                                print_string(PRINT_ANY,
 427                                             "protocol",
 428                                             ", vlan protocol %s",
 429                                             ll_proto_n2a(
 430                                                     vf_vlan_info->vlan_proto,
 431                                                     b2, sizeof(b2)));
 432                        close_json_object();
 433                }
 434                close_json_array(PRINT_JSON, NULL);
 435        } else {
 436                struct ifla_vf_vlan *vf_vlan = RTA_DATA(vf[IFLA_VF_VLAN]);
 437
 438                if (vf_vlan->vlan)
 439                        print_int(PRINT_ANY,
 440                                  "vlan",
 441                                  ", vlan %d",
 442                                  vf_vlan->vlan);
 443                if (vf_vlan->qos)
 444                        print_int(PRINT_ANY, "qos", ", qos %d", vf_vlan->qos);
 445        }
 446
 447        if (vf_tx_rate->rate)
 448                print_uint(PRINT_ANY,
 449                           "tx_rate",
 450                           ", tx rate %u (Mbps)",
 451                           vf_tx_rate->rate);
 452
 453        if (vf[IFLA_VF_RATE]) {
 454                struct ifla_vf_rate *vf_rate = RTA_DATA(vf[IFLA_VF_RATE]);
 455                int max_tx = vf_rate->max_tx_rate;
 456                int min_tx = vf_rate->min_tx_rate;
 457
 458                if (is_json_context()) {
 459                        open_json_object("rate");
 460                        print_uint(PRINT_JSON, "max_tx", NULL, max_tx);
 461                        print_uint(PRINT_ANY, "min_tx", NULL, min_tx);
 462                        close_json_object();
 463                } else {
 464                        if (max_tx)
 465                                fprintf(fp, ", max_tx_rate %uMbps", max_tx);
 466                        if (min_tx)
 467                                fprintf(fp, ", min_tx_rate %uMbps", min_tx);
 468                }
 469        }
 470
 471        if (vf[IFLA_VF_SPOOFCHK]) {
 472                struct ifla_vf_spoofchk *vf_spoofchk =
 473                        RTA_DATA(vf[IFLA_VF_SPOOFCHK]);
 474
 475                if (vf_spoofchk->setting != -1)
 476                        print_bool(PRINT_ANY,
 477                                   "spoofchk",
 478                                   vf_spoofchk->setting ?
 479                                   ", spoof checking on" : ", spoof checking off",
 480                                   vf_spoofchk->setting);
 481        }
 482
 483        if (vf[IFLA_VF_IB_NODE_GUID]) {
 484                struct ifla_vf_guid *guid = RTA_DATA(vf[IFLA_VF_IB_NODE_GUID]);
 485                uint64_t node_guid = ntohll(guid->guid);
 486
 487                print_string(PRINT_ANY, "node guid", ", NODE_GUID %s",
 488                             ll_addr_n2a((const unsigned char *)&node_guid,
 489                                         sizeof(node_guid), ARPHRD_INFINIBAND,
 490                                         b1, sizeof(b1)));
 491        }
 492        if (vf[IFLA_VF_IB_PORT_GUID]) {
 493                struct ifla_vf_guid *guid = RTA_DATA(vf[IFLA_VF_IB_PORT_GUID]);
 494                uint64_t port_guid = ntohll(guid->guid);
 495
 496                print_string(PRINT_ANY, "port guid", ", PORT_GUID %s",
 497                             ll_addr_n2a((const unsigned char *)&port_guid,
 498                                         sizeof(port_guid), ARPHRD_INFINIBAND,
 499                                         b1, sizeof(b1)));
 500        }
 501        if (vf[IFLA_VF_LINK_STATE]) {
 502                struct ifla_vf_link_state *vf_linkstate =
 503                        RTA_DATA(vf[IFLA_VF_LINK_STATE]);
 504
 505                if (vf_linkstate->link_state == IFLA_VF_LINK_STATE_AUTO)
 506                        print_string(PRINT_ANY,
 507                                     "link_state",
 508                                     ", link-state %s",
 509                                     "auto");
 510                else if (vf_linkstate->link_state == IFLA_VF_LINK_STATE_ENABLE)
 511                        print_string(PRINT_ANY,
 512                                     "link_state",
 513                                     ", link-state %s",
 514                                     "enable");
 515                else
 516                        print_string(PRINT_ANY,
 517                                     "link_state",
 518                                     ", link-state %s",
 519                                     "disable");
 520        }
 521
 522        if (vf[IFLA_VF_TRUST]) {
 523                struct ifla_vf_trust *vf_trust = RTA_DATA(vf[IFLA_VF_TRUST]);
 524
 525                if (vf_trust->setting != -1)
 526                        print_bool(PRINT_ANY,
 527                                   "trust",
 528                                   vf_trust->setting ? ", trust on" : ", trust off",
 529                                   vf_trust->setting);
 530        }
 531
 532        if (vf[IFLA_VF_RSS_QUERY_EN]) {
 533                struct ifla_vf_rss_query_en *rss_query =
 534                        RTA_DATA(vf[IFLA_VF_RSS_QUERY_EN]);
 535
 536                if (rss_query->setting != -1)
 537                        print_bool(PRINT_ANY,
 538                                   "query_rss_en",
 539                                   rss_query->setting ? ", query_rss on"
 540                                   : ", query_rss off",
 541                                   rss_query->setting);
 542        }
 543
 544        if (vf[IFLA_VF_STATS] && show_stats)
 545                print_vf_stats64(fp, vf[IFLA_VF_STATS]);
 546}
 547
 548static void size_columns(unsigned int cols[], unsigned int n, ...)
 549{
 550        unsigned int i, len;
 551        uint64_t val, powi;
 552        va_list args;
 553
 554        va_start(args, n);
 555
 556        for (i = 0; i < n; i++) {
 557                val = va_arg(args, unsigned long long);
 558
 559                if (human_readable)
 560                        continue;
 561
 562                for (len = 1, powi = 10; powi < val; len++, powi *= 10)
 563                        /* nothing */;
 564                if (len > cols[i])
 565                        cols[i] = len;
 566        }
 567
 568        va_end(args);
 569}
 570
 571void print_num(FILE *fp, unsigned int width, uint64_t count)
 572{
 573        const char *prefix = "kMGTPE";
 574        const unsigned int base = use_iec ? 1024 : 1000;
 575        uint64_t powi = 1;
 576        uint16_t powj = 1;
 577        uint8_t precision = 2;
 578        char buf[64];
 579
 580        if (!human_readable || count < base) {
 581                fprintf(fp, "%*"PRIu64" ", width, count);
 582                return;
 583        }
 584
 585        /* increase value by a factor of 1000/1024 and print
 586         * if result is something a human can read
 587         */
 588        for (;;) {
 589                powi *= base;
 590                if (count / base < powi)
 591                        break;
 592
 593                if (!prefix[1])
 594                        break;
 595                ++prefix;
 596        }
 597
 598        /* try to guess a good number of digits for precision */
 599        for (; precision > 0; precision--) {
 600                powj *= 10;
 601                if (count / powi < powj)
 602                        break;
 603        }
 604
 605        snprintf(buf, sizeof(buf), "%.*f%c%s", precision,
 606                 (double) count / powi, *prefix, use_iec ? "i" : "");
 607
 608        fprintf(fp, "%*s ", width, buf);
 609}
 610
 611static void print_vf_stats64(FILE *fp, struct rtattr *vfstats)
 612{
 613        struct rtattr *vf[IFLA_VF_STATS_MAX + 1];
 614
 615        if (vfstats->rta_type != IFLA_VF_STATS) {
 616                fprintf(stderr, "BUG: rta type is %d\n", vfstats->rta_type);
 617                return;
 618        }
 619
 620        parse_rtattr_nested(vf, IFLA_VF_STATS_MAX, vfstats);
 621
 622        if (is_json_context()) {
 623                open_json_object("stats");
 624
 625                /* RX stats */
 626                open_json_object("rx");
 627                print_u64(PRINT_JSON, "bytes", NULL,
 628                           rta_getattr_u64(vf[IFLA_VF_STATS_RX_BYTES]));
 629                print_u64(PRINT_JSON, "packets", NULL,
 630                           rta_getattr_u64(vf[IFLA_VF_STATS_RX_PACKETS]));
 631                print_u64(PRINT_JSON, "multicast", NULL,
 632                           rta_getattr_u64(vf[IFLA_VF_STATS_MULTICAST]));
 633                print_u64(PRINT_JSON, "broadcast", NULL,
 634                           rta_getattr_u64(vf[IFLA_VF_STATS_BROADCAST]));
 635                if (vf[IFLA_VF_STATS_RX_DROPPED])
 636                        print_u64(PRINT_JSON, "dropped", NULL,
 637                                  rta_getattr_u64(vf[IFLA_VF_STATS_RX_DROPPED]));
 638                close_json_object();
 639
 640                /* TX stats */
 641                open_json_object("tx");
 642                print_u64(PRINT_JSON, "tx_bytes", NULL,
 643                           rta_getattr_u64(vf[IFLA_VF_STATS_TX_BYTES]));
 644                print_u64(PRINT_JSON, "tx_packets", NULL,
 645                           rta_getattr_u64(vf[IFLA_VF_STATS_TX_PACKETS]));
 646                if (vf[IFLA_VF_STATS_TX_DROPPED])
 647                        print_u64(PRINT_JSON, "dropped", NULL,
 648                                  rta_getattr_u64(vf[IFLA_VF_STATS_TX_DROPPED]));
 649                close_json_object();
 650                close_json_object();
 651        } else {
 652                /* RX stats */
 653                fprintf(fp, "%s", _SL_);
 654                fprintf(fp, "    RX: bytes  packets  mcast   bcast ");
 655                if (vf[IFLA_VF_STATS_RX_DROPPED])
 656                        fprintf(fp, "  dropped ");
 657                fprintf(fp, "%s", _SL_);
 658                fprintf(fp, "    ");
 659
 660                print_num(fp, 10, rta_getattr_u64(vf[IFLA_VF_STATS_RX_BYTES]));
 661                print_num(fp, 8, rta_getattr_u64(vf[IFLA_VF_STATS_RX_PACKETS]));
 662                print_num(fp, 7, rta_getattr_u64(vf[IFLA_VF_STATS_MULTICAST]));
 663                print_num(fp, 7, rta_getattr_u64(vf[IFLA_VF_STATS_BROADCAST]));
 664                if (vf[IFLA_VF_STATS_RX_DROPPED])
 665                        print_num(fp, 8, rta_getattr_u64(vf[IFLA_VF_STATS_RX_DROPPED]));
 666
 667                /* TX stats */
 668                fprintf(fp, "%s", _SL_);
 669                fprintf(fp, "    TX: bytes  packets ");
 670                if (vf[IFLA_VF_STATS_TX_DROPPED])
 671                        fprintf(fp, "  dropped ");
 672                fprintf(fp, "%s", _SL_);
 673                fprintf(fp, "    ");
 674
 675                print_num(fp, 10, rta_getattr_u64(vf[IFLA_VF_STATS_TX_BYTES]));
 676                print_num(fp, 8, rta_getattr_u64(vf[IFLA_VF_STATS_TX_PACKETS]));
 677                if (vf[IFLA_VF_STATS_TX_DROPPED])
 678                        print_num(fp, 8, rta_getattr_u64(vf[IFLA_VF_STATS_TX_DROPPED]));
 679        }
 680}
 681
 682static void __print_link_stats(FILE *fp, struct rtattr *tb[])
 683{
 684        const struct rtattr *carrier_changes = tb[IFLA_CARRIER_CHANGES];
 685        struct rtnl_link_stats64 _s, *s = &_s;
 686        unsigned int cols[] = {
 687                strlen("*X errors:"),
 688                strlen("packets"),
 689                strlen("errors"),
 690                strlen("dropped"),
 691                strlen("heartbt"),
 692                strlen("overrun"),
 693                strlen("compressed"),
 694        };
 695        int ret;
 696
 697        ret = get_rtnl_link_stats_rta(s, tb);
 698        if (ret < 0)
 699                return;
 700
 701        if (is_json_context()) {
 702                open_json_object((ret == sizeof(*s)) ? "stats64" : "stats");
 703
 704                /* RX stats */
 705                open_json_object("rx");
 706                print_u64(PRINT_JSON, "bytes", NULL, s->rx_bytes);
 707                print_u64(PRINT_JSON, "packets", NULL, s->rx_packets);
 708                print_u64(PRINT_JSON, "errors", NULL, s->rx_errors);
 709                print_u64(PRINT_JSON, "dropped", NULL, s->rx_dropped);
 710                print_u64(PRINT_JSON, "over_errors", NULL, s->rx_over_errors);
 711                print_u64(PRINT_JSON, "multicast", NULL, s->multicast);
 712                if (s->rx_compressed)
 713                        print_u64(PRINT_JSON,
 714                                   "compressed", NULL, s->rx_compressed);
 715
 716                /* RX error stats */
 717                if (show_stats > 1) {
 718                        print_u64(PRINT_JSON,
 719                                   "length_errors",
 720                                   NULL, s->rx_length_errors);
 721                        print_u64(PRINT_JSON,
 722                                   "crc_errors",
 723                                   NULL, s->rx_crc_errors);
 724                        print_u64(PRINT_JSON,
 725                                   "frame_errors",
 726                                   NULL, s->rx_frame_errors);
 727                        print_u64(PRINT_JSON,
 728                                   "fifo_errors",
 729                                   NULL, s->rx_fifo_errors);
 730                        print_u64(PRINT_JSON,
 731                                   "missed_errors",
 732                                   NULL, s->rx_missed_errors);
 733                        if (s->rx_nohandler)
 734                                print_u64(PRINT_JSON,
 735                                           "nohandler", NULL, s->rx_nohandler);
 736                }
 737                close_json_object();
 738
 739                /* TX stats */
 740                open_json_object("tx");
 741                print_u64(PRINT_JSON, "bytes", NULL, s->tx_bytes);
 742                print_u64(PRINT_JSON, "packets", NULL, s->tx_packets);
 743                print_u64(PRINT_JSON, "errors", NULL, s->tx_errors);
 744                print_u64(PRINT_JSON, "dropped", NULL, s->tx_dropped);
 745                print_u64(PRINT_JSON,
 746                           "carrier_errors",
 747                           NULL, s->tx_carrier_errors);
 748                print_u64(PRINT_JSON, "collisions", NULL, s->collisions);
 749                if (s->tx_compressed)
 750                        print_u64(PRINT_JSON,
 751                                   "compressed", NULL, s->tx_compressed);
 752
 753                /* TX error stats */
 754                if (show_stats > 1) {
 755                        print_u64(PRINT_JSON,
 756                                   "aborted_errors",
 757                                   NULL, s->tx_aborted_errors);
 758                        print_u64(PRINT_JSON,
 759                                   "fifo_errors",
 760                                   NULL, s->tx_fifo_errors);
 761                        print_u64(PRINT_JSON,
 762                                   "window_errors",
 763                                   NULL, s->tx_window_errors);
 764                        print_u64(PRINT_JSON,
 765                                   "heartbeat_errors",
 766                                   NULL, s->tx_heartbeat_errors);
 767                        if (carrier_changes)
 768                                print_u64(PRINT_JSON, "carrier_changes", NULL,
 769                                           rta_getattr_u32(carrier_changes));
 770                }
 771
 772                close_json_object();
 773                close_json_object();
 774        } else {
 775                size_columns(cols, ARRAY_SIZE(cols),
 776                             s->rx_bytes, s->rx_packets, s->rx_errors,
 777                             s->rx_dropped, s->rx_missed_errors,
 778                             s->multicast, s->rx_compressed);
 779                if (show_stats > 1)
 780                        size_columns(cols, ARRAY_SIZE(cols), 0,
 781                                     s->rx_length_errors, s->rx_crc_errors,
 782                                     s->rx_frame_errors, s->rx_fifo_errors,
 783                                     s->rx_over_errors, s->rx_nohandler);
 784                size_columns(cols, ARRAY_SIZE(cols),
 785                             s->tx_bytes, s->tx_packets, s->tx_errors,
 786                             s->tx_dropped, s->tx_carrier_errors,
 787                             s->collisions, s->tx_compressed);
 788                if (show_stats > 1)
 789                        size_columns(cols, ARRAY_SIZE(cols), 0, 0,
 790                                     s->tx_aborted_errors, s->tx_fifo_errors,
 791                                     s->tx_window_errors,
 792                                     s->tx_heartbeat_errors,
 793                                     carrier_changes ?
 794                                     rta_getattr_u32(carrier_changes) : 0);
 795
 796                /* RX stats */
 797                fprintf(fp, "    RX: %*s %*s %*s %*s %*s %*s %*s%s",
 798                        cols[0] - 4, "bytes", cols[1], "packets",
 799                        cols[2], "errors", cols[3], "dropped",
 800                        cols[4], "missed", cols[5], "mcast",
 801                        cols[6], s->rx_compressed ? "compressed" : "", _SL_);
 802
 803                fprintf(fp, "    ");
 804                print_num(fp, cols[0], s->rx_bytes);
 805                print_num(fp, cols[1], s->rx_packets);
 806                print_num(fp, cols[2], s->rx_errors);
 807                print_num(fp, cols[3], s->rx_dropped);
 808                print_num(fp, cols[4], s->rx_missed_errors);
 809                print_num(fp, cols[5], s->multicast);
 810                if (s->rx_compressed)
 811                        print_num(fp, cols[6], s->rx_compressed);
 812
 813                /* RX error stats */
 814                if (show_stats > 1) {
 815                        fprintf(fp, "%s", _SL_);
 816                        fprintf(fp, "    RX errors:%*s %*s %*s %*s %*s %*s %*s%s",
 817                                cols[0] - 10, "", cols[1], "length",
 818                                cols[2], "crc", cols[3], "frame",
 819                                cols[4], "fifo", cols[5], "overrun",
 820                                cols[6], s->rx_nohandler ? "nohandler" : "",
 821                                _SL_);
 822                        fprintf(fp, "%*s", cols[0] + 5, "");
 823                        print_num(fp, cols[1], s->rx_length_errors);
 824                        print_num(fp, cols[2], s->rx_crc_errors);
 825                        print_num(fp, cols[3], s->rx_frame_errors);
 826                        print_num(fp, cols[4], s->rx_fifo_errors);
 827                        print_num(fp, cols[5], s->rx_over_errors);
 828                        if (s->rx_nohandler)
 829                                print_num(fp, cols[6], s->rx_nohandler);
 830                }
 831                fprintf(fp, "%s", _SL_);
 832
 833                /* TX stats */
 834                fprintf(fp, "    TX: %*s %*s %*s %*s %*s %*s %*s%s",
 835                        cols[0] - 4, "bytes", cols[1], "packets",
 836                        cols[2], "errors", cols[3], "dropped",
 837                        cols[4], "carrier", cols[5], "collsns",
 838                        cols[6], s->tx_compressed ? "compressed" : "", _SL_);
 839
 840                fprintf(fp, "    ");
 841                print_num(fp, cols[0], s->tx_bytes);
 842                print_num(fp, cols[1], s->tx_packets);
 843                print_num(fp, cols[2], s->tx_errors);
 844                print_num(fp, cols[3], s->tx_dropped);
 845                print_num(fp, cols[4], s->tx_carrier_errors);
 846                print_num(fp, cols[5], s->collisions);
 847                if (s->tx_compressed)
 848                        print_num(fp, cols[6], s->tx_compressed);
 849
 850                /* TX error stats */
 851                if (show_stats > 1) {
 852                        fprintf(fp, "%s", _SL_);
 853                        fprintf(fp, "    TX errors:%*s %*s %*s %*s %*s %*s%s",
 854                                cols[0] - 10, "", cols[1], "aborted",
 855                                cols[2], "fifo", cols[3], "window",
 856                                cols[4], "heartbt",
 857                                cols[5], carrier_changes ? "transns" : "",
 858                                _SL_);
 859
 860                        fprintf(fp, "%*s", cols[0] + 5, "");
 861                        print_num(fp, cols[1], s->tx_aborted_errors);
 862                        print_num(fp, cols[2], s->tx_fifo_errors);
 863                        print_num(fp, cols[3], s->tx_window_errors);
 864                        print_num(fp, cols[4], s->tx_heartbeat_errors);
 865                        if (carrier_changes)
 866                                print_num(fp, cols[5],
 867                                          rta_getattr_u32(carrier_changes));
 868                }
 869        }
 870}
 871
 872static void print_link_stats(FILE *fp, struct nlmsghdr *n)
 873{
 874        struct ifinfomsg *ifi = NLMSG_DATA(n);
 875        struct rtattr *tb[IFLA_MAX+1];
 876
 877        parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi),
 878                     n->nlmsg_len - NLMSG_LENGTH(sizeof(*ifi)));
 879        __print_link_stats(fp, tb);
 880        print_nl();
 881}
 882
 883static int print_linkinfo_brief(FILE *fp, const char *name,
 884                                const struct ifinfomsg *ifi,
 885                                struct rtattr *tb[])
 886{
 887        unsigned int m_flag = 0;
 888
 889        m_flag = print_name_and_link("%-16s ", name, tb);
 890
 891        if (tb[IFLA_OPERSTATE])
 892                print_operstate(fp, rta_getattr_u8(tb[IFLA_OPERSTATE]));
 893
 894        if (filter.family == AF_PACKET) {
 895                SPRINT_BUF(b1);
 896
 897                if (tb[IFLA_ADDRESS]) {
 898                        print_color_string(PRINT_ANY, COLOR_MAC,
 899                                           "address", "%s ",
 900                                           ll_addr_n2a(
 901                                                   RTA_DATA(tb[IFLA_ADDRESS]),
 902                                                   RTA_PAYLOAD(tb[IFLA_ADDRESS]),
 903                                                   ifi->ifi_type,
 904                                                   b1, sizeof(b1)));
 905                }
 906        }
 907
 908        if (filter.family == AF_PACKET) {
 909                print_link_flags(fp, ifi->ifi_flags, m_flag);
 910                print_string(PRINT_FP, NULL, "%s", "\n");
 911        }
 912
 913        fflush(fp);
 914        return 0;
 915}
 916
 917static const char *link_events[] = {
 918        [IFLA_EVENT_NONE] = "NONE",
 919        [IFLA_EVENT_REBOOT] = "REBOOT",
 920        [IFLA_EVENT_FEATURES] = "FEATURE CHANGE",
 921        [IFLA_EVENT_BONDING_FAILOVER] = "BONDING FAILOVER",
 922        [IFLA_EVENT_NOTIFY_PEERS] = "NOTIFY PEERS",
 923        [IFLA_EVENT_IGMP_RESEND] = "RESEND IGMP",
 924        [IFLA_EVENT_BONDING_OPTIONS] = "BONDING OPTION"
 925};
 926
 927static void print_link_event(FILE *f, __u32 event)
 928{
 929        if (event >= ARRAY_SIZE(link_events))
 930                print_int(PRINT_ANY, "event", "event %d ", event);
 931        else {
 932                if (event)
 933                        print_string(PRINT_ANY,
 934                                     "event", "event %s ",
 935                                     link_events[event]);
 936        }
 937}
 938
 939static void print_proto_down(FILE *f, struct rtattr *tb[])
 940{
 941        struct rtattr *preason[IFLA_PROTO_DOWN_REASON_MAX+1];
 942
 943        if (tb[IFLA_PROTO_DOWN]) {
 944                if (rta_getattr_u8(tb[IFLA_PROTO_DOWN]))
 945                        print_bool(PRINT_ANY,
 946                                   "proto_down", " protodown on ", true);
 947        }
 948
 949        if (tb[IFLA_PROTO_DOWN_REASON]) {
 950                char buf[255];
 951                __u32 reason;
 952                int i, start = 1;
 953
 954                parse_rtattr_nested(preason, IFLA_PROTO_DOWN_REASON_MAX,
 955                                   tb[IFLA_PROTO_DOWN_REASON]);
 956                if (!tb[IFLA_PROTO_DOWN_REASON_VALUE])
 957                        return;
 958
 959                reason = rta_getattr_u8(preason[IFLA_PROTO_DOWN_REASON_VALUE]);
 960                if (!reason)
 961                        return;
 962
 963                open_json_array(PRINT_ANY,
 964                                is_json_context() ? "proto_down_reason" : "protodown_reason <");
 965                for (i = 0; reason; i++, reason >>= 1) {
 966                        if (reason & 0x1) {
 967                                if (protodown_reason_n2a(i, buf, sizeof(buf)))
 968                                        break;
 969                                print_string(PRINT_ANY, NULL,
 970                                             start ? "%s" : ",%s", buf);
 971                                start = 0;
 972                        }
 973                }
 974                close_json_array(PRINT_ANY, ">");
 975        }
 976}
 977
 978int print_linkinfo(struct nlmsghdr *n, void *arg)
 979{
 980        FILE *fp = (FILE *)arg;
 981        struct ifinfomsg *ifi = NLMSG_DATA(n);
 982        struct rtattr *tb[IFLA_MAX+1];
 983        int len = n->nlmsg_len;
 984        const char *name;
 985        unsigned int m_flag = 0;
 986        SPRINT_BUF(b1);
 987        bool truncated_vfs = false;
 988
 989        if (n->nlmsg_type != RTM_NEWLINK && n->nlmsg_type != RTM_DELLINK)
 990                return 0;
 991
 992        len -= NLMSG_LENGTH(sizeof(*ifi));
 993        if (len < 0)
 994                return -1;
 995
 996        if (filter.ifindex && ifi->ifi_index != filter.ifindex)
 997                return -1;
 998        if (filter.up && !(ifi->ifi_flags&IFF_UP))
 999                return -1;
1000
1001        parse_rtattr_flags(tb, IFLA_MAX, IFLA_RTA(ifi), len, NLA_F_NESTED);
1002
1003        name = get_ifname_rta(ifi->ifi_index, tb[IFLA_IFNAME]);
1004        if (!name)
1005                return -1;
1006
1007        if (filter.label)
1008                return 0;
1009
1010        if (tb[IFLA_GROUP]) {
1011                int group = rta_getattr_u32(tb[IFLA_GROUP]);
1012
1013                if (filter.group != -1 && group != filter.group)
1014                        return -1;
1015        }
1016
1017        if (tb[IFLA_MASTER]) {
1018                int master = rta_getattr_u32(tb[IFLA_MASTER]);
1019
1020                if (filter.master > 0 && master != filter.master)
1021                        return -1;
1022        } else if (filter.master > 0)
1023                return -1;
1024
1025        if (filter.kind && match_link_kind(tb, filter.kind, 0))
1026                return -1;
1027
1028        if (filter.slave_kind && match_link_kind(tb, filter.slave_kind, 1))
1029                return -1;
1030
1031        if (n->nlmsg_type == RTM_DELLINK)
1032                print_bool(PRINT_ANY, "deleted", "Deleted ", true);
1033
1034        if (brief)
1035                return print_linkinfo_brief(fp, name, ifi, tb);
1036
1037        print_int(PRINT_ANY, "ifindex", "%d: ", ifi->ifi_index);
1038
1039        m_flag = print_name_and_link("%s: ", name, tb);
1040        print_link_flags(fp, ifi->ifi_flags, m_flag);
1041
1042        if (tb[IFLA_MTU])
1043                print_int(PRINT_ANY,
1044                          "mtu", "mtu %u ",
1045                          rta_getattr_u32(tb[IFLA_MTU]));
1046        if (tb[IFLA_XDP])
1047                xdp_dump(fp, tb[IFLA_XDP], do_link, false);
1048        if (tb[IFLA_QDISC])
1049                print_string(PRINT_ANY,
1050                             "qdisc",
1051                             "qdisc %s ",
1052                             rta_getattr_str(tb[IFLA_QDISC]));
1053        if (tb[IFLA_MASTER]) {
1054                int master = rta_getattr_u32(tb[IFLA_MASTER]);
1055
1056                print_string(PRINT_ANY,
1057                             "master", "master %s ",
1058                             ll_index_to_name(master));
1059        }
1060
1061        if (tb[IFLA_OPERSTATE])
1062                print_operstate(fp, rta_getattr_u8(tb[IFLA_OPERSTATE]));
1063
1064        if (do_link && tb[IFLA_LINKMODE])
1065                print_linkmode(fp, tb[IFLA_LINKMODE]);
1066
1067        if (tb[IFLA_GROUP]) {
1068                int group = rta_getattr_u32(tb[IFLA_GROUP]);
1069
1070                print_string(PRINT_ANY,
1071                             "group",
1072                             "group %s ",
1073                             rtnl_group_n2a(group, b1, sizeof(b1)));
1074        }
1075
1076        if (filter.showqueue)
1077                print_queuelen(fp, tb);
1078
1079        if (tb[IFLA_EVENT])
1080                print_link_event(fp, rta_getattr_u32(tb[IFLA_EVENT]));
1081
1082        if (!filter.family || filter.family == AF_PACKET || show_details) {
1083                print_nl();
1084                print_string(PRINT_ANY,
1085                             "link_type",
1086                             "    link/%s ",
1087                             ll_type_n2a(ifi->ifi_type, b1, sizeof(b1)));
1088                if (tb[IFLA_ADDRESS]) {
1089                        print_color_string(PRINT_ANY,
1090                                           COLOR_MAC,
1091                                           "address",
1092                                           "%s",
1093                                           ll_addr_n2a(RTA_DATA(tb[IFLA_ADDRESS]),
1094                                                       RTA_PAYLOAD(tb[IFLA_ADDRESS]),
1095                                                       ifi->ifi_type,
1096                                                       b1, sizeof(b1)));
1097                }
1098                if (tb[IFLA_BROADCAST]) {
1099                        if (ifi->ifi_flags&IFF_POINTOPOINT) {
1100                                print_string(PRINT_FP, NULL, " peer ", NULL);
1101                                print_bool(PRINT_JSON,
1102                                           "link_pointtopoint", NULL, true);
1103                        } else {
1104                                print_string(PRINT_FP, NULL, " brd ", NULL);
1105                        }
1106                        print_color_string(PRINT_ANY,
1107                                           COLOR_MAC,
1108                                           "broadcast",
1109                                           "%s",
1110                                           ll_addr_n2a(RTA_DATA(tb[IFLA_BROADCAST]),
1111                                                       RTA_PAYLOAD(tb[IFLA_BROADCAST]),
1112                                                       ifi->ifi_type,
1113                                                       b1, sizeof(b1)));
1114                }
1115                if (tb[IFLA_PERM_ADDRESS]) {
1116                        unsigned int len = RTA_PAYLOAD(tb[IFLA_PERM_ADDRESS]);
1117
1118                        if (!tb[IFLA_ADDRESS] ||
1119                            RTA_PAYLOAD(tb[IFLA_ADDRESS]) != len ||
1120                            memcmp(RTA_DATA(tb[IFLA_PERM_ADDRESS]),
1121                                   RTA_DATA(tb[IFLA_ADDRESS]), len)) {
1122                                print_string(PRINT_FP, NULL, " permaddr ", NULL);
1123                                print_color_string(PRINT_ANY,
1124                                                   COLOR_MAC,
1125                                                   "permaddr",
1126                                                   "%s",
1127                                                   ll_addr_n2a(RTA_DATA(tb[IFLA_PERM_ADDRESS]),
1128                                                               RTA_PAYLOAD(tb[IFLA_PERM_ADDRESS]),
1129                                                               ifi->ifi_type,
1130                                                               b1, sizeof(b1)));
1131                        }
1132                }
1133        }
1134
1135        if (tb[IFLA_LINK_NETNSID]) {
1136                int id = rta_getattr_u32(tb[IFLA_LINK_NETNSID]);
1137
1138                if (is_json_context()) {
1139                        print_int(PRINT_JSON, "link_netnsid", NULL, id);
1140                } else {
1141                        if (id >= 0) {
1142                                char *name = get_name_from_nsid(id);
1143
1144                                if (name)
1145                                        print_string(PRINT_FP, NULL,
1146                                                     " link-netns %s", name);
1147                                else
1148                                        print_int(PRINT_FP, NULL,
1149                                                  " link-netnsid %d", id);
1150                        } else
1151                                print_string(PRINT_FP, NULL,
1152                                             " link-netnsid %s", "unknown");
1153                }
1154        }
1155
1156        if (tb[IFLA_NEW_NETNSID]) {
1157                int id = rta_getattr_u32(tb[IFLA_NEW_NETNSID]);
1158                char *name = get_name_from_nsid(id);
1159
1160                if (name)
1161                        print_string(PRINT_FP, NULL, " new-netns %s", name);
1162                else
1163                        print_int(PRINT_FP, NULL, " new-netnsid %d", id);
1164        }
1165        if (tb[IFLA_NEW_IFINDEX]) {
1166                int id = rta_getattr_u32(tb[IFLA_NEW_IFINDEX]);
1167
1168                print_int(PRINT_FP, NULL, " new-ifindex %d", id);
1169        }
1170
1171        if (tb[IFLA_PROTO_DOWN])
1172                print_proto_down(fp, tb);
1173
1174        if (show_details) {
1175                if (tb[IFLA_PROMISCUITY])
1176                        print_uint(PRINT_ANY,
1177                                   "promiscuity",
1178                                   " promiscuity %u ",
1179                                   rta_getattr_u32(tb[IFLA_PROMISCUITY]));
1180
1181                if (tb[IFLA_MIN_MTU])
1182                        print_uint(PRINT_ANY,
1183                                   "min_mtu", "minmtu %u ",
1184                                   rta_getattr_u32(tb[IFLA_MIN_MTU]));
1185
1186                if (tb[IFLA_MAX_MTU])
1187                        print_uint(PRINT_ANY,
1188                                   "max_mtu", "maxmtu %u ",
1189                                   rta_getattr_u32(tb[IFLA_MAX_MTU]));
1190
1191                if (tb[IFLA_LINKINFO])
1192                        print_linktype(fp, tb[IFLA_LINKINFO]);
1193
1194                if (do_link && tb[IFLA_AF_SPEC])
1195                        print_af_spec(fp, tb[IFLA_AF_SPEC]);
1196
1197                if (tb[IFLA_NUM_TX_QUEUES])
1198                        print_uint(PRINT_ANY,
1199                                   "num_tx_queues",
1200                                   "numtxqueues %u ",
1201                                   rta_getattr_u32(tb[IFLA_NUM_TX_QUEUES]));
1202
1203                if (tb[IFLA_NUM_RX_QUEUES])
1204                        print_uint(PRINT_ANY,
1205                                   "num_rx_queues",
1206                                   "numrxqueues %u ",
1207                                   rta_getattr_u32(tb[IFLA_NUM_RX_QUEUES]));
1208
1209                if (tb[IFLA_GSO_MAX_SIZE])
1210                        print_uint(PRINT_ANY,
1211                                   "gso_max_size",
1212                                   "gso_max_size %u ",
1213                                   rta_getattr_u32(tb[IFLA_GSO_MAX_SIZE]));
1214
1215                if (tb[IFLA_GSO_MAX_SEGS])
1216                        print_uint(PRINT_ANY,
1217                                   "gso_max_segs",
1218                                   "gso_max_segs %u ",
1219                                   rta_getattr_u32(tb[IFLA_GSO_MAX_SEGS]));
1220
1221                if (tb[IFLA_PHYS_PORT_NAME])
1222                        print_string(PRINT_ANY,
1223                                     "phys_port_name",
1224                                     "portname %s ",
1225                                     rta_getattr_str(tb[IFLA_PHYS_PORT_NAME]));
1226
1227                if (tb[IFLA_PHYS_PORT_ID]) {
1228                        print_string(PRINT_ANY,
1229                                     "phys_port_id",
1230                                     "portid %s ",
1231                                     hexstring_n2a(
1232                                             RTA_DATA(tb[IFLA_PHYS_PORT_ID]),
1233                                             RTA_PAYLOAD(tb[IFLA_PHYS_PORT_ID]),
1234                                             b1, sizeof(b1)));
1235                }
1236
1237                if (tb[IFLA_PHYS_SWITCH_ID]) {
1238                        print_string(PRINT_ANY,
1239                                     "phys_switch_id",
1240                                     "switchid %s ",
1241                                     hexstring_n2a(RTA_DATA(tb[IFLA_PHYS_SWITCH_ID]),
1242                                                   RTA_PAYLOAD(tb[IFLA_PHYS_SWITCH_ID]),
1243                                                   b1, sizeof(b1)));
1244                }
1245
1246                if (tb[IFLA_PARENT_DEV_BUS_NAME]) {
1247                        print_string(PRINT_ANY,
1248                                     "parentbus",
1249                                     "parentbus %s ",
1250                                     rta_getattr_str(tb[IFLA_PARENT_DEV_BUS_NAME]));
1251                }
1252
1253                if (tb[IFLA_PARENT_DEV_NAME]) {
1254                        print_string(PRINT_ANY,
1255                                     "parentdev",
1256                                     "parentdev %s ",
1257                                     rta_getattr_str(tb[IFLA_PARENT_DEV_NAME]));
1258                }
1259        }
1260
1261        if ((do_link || show_details) && tb[IFLA_IFALIAS]) {
1262                print_string(PRINT_FP, NULL, "%s    ", _SL_);
1263                print_string(PRINT_ANY,
1264                             "ifalias",
1265                             "alias %s",
1266                             rta_getattr_str(tb[IFLA_IFALIAS]));
1267        }
1268
1269        if ((do_link || show_details) && tb[IFLA_XDP])
1270                xdp_dump(fp, tb[IFLA_XDP], true, true);
1271
1272        if (do_link && show_stats) {
1273                print_nl();
1274                __print_link_stats(fp, tb);
1275        }
1276
1277        if ((do_link || show_details) && tb[IFLA_VFINFO_LIST] && tb[IFLA_NUM_VF]) {
1278                struct rtattr *i, *vflist = tb[IFLA_VFINFO_LIST];
1279                int rem = RTA_PAYLOAD(vflist), count = 0;
1280
1281                open_json_array(PRINT_JSON, "vfinfo_list");
1282                for (i = RTA_DATA(vflist); RTA_OK(i, rem); i = RTA_NEXT(i, rem)) {
1283                        open_json_object(NULL);
1284                        print_vfinfo(fp, ifi, i);
1285                        close_json_object();
1286                        count++;
1287                }
1288                close_json_array(PRINT_JSON, NULL);
1289                if (count != rta_getattr_u32(tb[IFLA_NUM_VF]))
1290                        truncated_vfs = true;
1291        }
1292
1293        if (tb[IFLA_PROP_LIST]) {
1294                struct rtattr *i, *proplist = tb[IFLA_PROP_LIST];
1295                int rem = RTA_PAYLOAD(proplist);
1296
1297                open_json_array(PRINT_JSON, "altnames");
1298                for (i = RTA_DATA(proplist); RTA_OK(i, rem);
1299                     i = RTA_NEXT(i, rem)) {
1300                        if (i->rta_type != IFLA_ALT_IFNAME)
1301                                continue;
1302                        print_string(PRINT_FP, NULL, "%s    altname ", _SL_);
1303                        print_string(PRINT_ANY, NULL,
1304                                     "%s", rta_getattr_str(i));
1305                }
1306                close_json_array(PRINT_JSON, NULL);
1307        }
1308
1309        print_string(PRINT_FP, NULL, "%s", "\n");
1310        fflush(fp);
1311        /* prettier here if stderr and stdout go to the same place */
1312        if (truncated_vfs)
1313                fprintf(stderr, "Truncated VF list: %s\n", name);
1314        return 1;
1315}
1316
1317static int flush_update(void)
1318{
1319
1320        /*
1321         * Note that the kernel may delete multiple addresses for one
1322         * delete request (e.g. if ipv4 address promotion is disabled).
1323         * Since a flush operation is really a series of delete requests
1324         * its possible that we may request an address delete that has
1325         * already been done by the kernel. Therefore, ignore EADDRNOTAVAIL
1326         * errors returned from a flush request
1327         */
1328        if ((rtnl_send_check(&rth, filter.flushb, filter.flushp) < 0) &&
1329            (errno != EADDRNOTAVAIL)) {
1330                perror("Failed to send flush request");
1331                return -1;
1332        }
1333        filter.flushp = 0;
1334        return 0;
1335}
1336
1337static int set_lifetime(unsigned int *lifetime, char *argv)
1338{
1339        if (strcmp(argv, "forever") == 0)
1340                *lifetime = INFINITY_LIFE_TIME;
1341        else if (get_u32(lifetime, argv, 0))
1342                return -1;
1343
1344        return 0;
1345}
1346
1347static unsigned int get_ifa_flags(struct ifaddrmsg *ifa,
1348                                  struct rtattr *ifa_flags_attr)
1349{
1350        return ifa_flags_attr ? rta_getattr_u32(ifa_flags_attr) :
1351                ifa->ifa_flags;
1352}
1353
1354/* Mapping from argument to address flag mask and attributes */
1355static const struct ifa_flag_data_t {
1356        const char *name;
1357        unsigned long mask;
1358        bool readonly;
1359        bool v6only;
1360} ifa_flag_data[] = {
1361        { .name = "secondary",          .mask = IFA_F_SECONDARY,        .readonly = true,       .v6only = false},
1362        { .name = "temporary",          .mask = IFA_F_SECONDARY,        .readonly = true,       .v6only = false},
1363        { .name = "nodad",              .mask = IFA_F_NODAD,            .readonly = false,      .v6only = true},
1364        { .name = "optimistic",         .mask = IFA_F_OPTIMISTIC,       .readonly = false,      .v6only = true},
1365        { .name = "dadfailed",          .mask = IFA_F_DADFAILED,        .readonly = true,       .v6only = true},
1366        { .name = "home",               .mask = IFA_F_HOMEADDRESS,      .readonly = false,      .v6only = true},
1367        { .name = "deprecated",         .mask = IFA_F_DEPRECATED,       .readonly = true,       .v6only = true},
1368        { .name = "tentative",          .mask = IFA_F_TENTATIVE,        .readonly = true,       .v6only = true},
1369        { .name = "permanent",          .mask = IFA_F_PERMANENT,        .readonly = true,       .v6only = true},
1370        { .name = "mngtmpaddr",         .mask = IFA_F_MANAGETEMPADDR,   .readonly = false,      .v6only = true},
1371        { .name = "noprefixroute",      .mask = IFA_F_NOPREFIXROUTE,    .readonly = false,      .v6only = false},
1372        { .name = "autojoin",           .mask = IFA_F_MCAUTOJOIN,       .readonly = false,      .v6only = false},
1373        { .name = "stable-privacy",     .mask = IFA_F_STABLE_PRIVACY,   .readonly = true,       .v6only = true},
1374};
1375
1376/* Returns a pointer to the data structure for a particular interface flag, or null if no flag could be found */
1377static const struct ifa_flag_data_t* lookup_flag_data_by_name(const char* flag_name) {
1378        unsigned int i;
1379
1380        for (i = 0; i < ARRAY_SIZE(ifa_flag_data); ++i) {
1381                if (strcmp(flag_name, ifa_flag_data[i].name) == 0)
1382                        return &ifa_flag_data[i];
1383        }
1384        return NULL;
1385}
1386
1387static void print_ifa_flags(FILE *fp, const struct ifaddrmsg *ifa,
1388                            unsigned int flags)
1389{
1390        unsigned int i;
1391
1392        for (i = 0; i < ARRAY_SIZE(ifa_flag_data); i++) {
1393                const struct ifa_flag_data_t* flag_data = &ifa_flag_data[i];
1394
1395                if (flag_data->mask == IFA_F_PERMANENT) {
1396                        if (!(flags & flag_data->mask))
1397                                print_bool(PRINT_ANY,
1398                                           "dynamic", "dynamic ", true);
1399                } else if (flags & flag_data->mask) {
1400                        if (flag_data->mask == IFA_F_SECONDARY &&
1401                            ifa->ifa_family == AF_INET6) {
1402                                print_bool(PRINT_ANY,
1403                                           "temporary", "temporary ", true);
1404                        } else {
1405                                print_string(PRINT_FP, NULL,
1406                                             "%s ", flag_data->name);
1407                                print_bool(PRINT_JSON,
1408                                           flag_data->name, NULL, true);
1409                        }
1410                }
1411
1412                flags &= ~flag_data->mask;
1413        }
1414
1415        if (flags) {
1416                if (is_json_context()) {
1417                        SPRINT_BUF(b1);
1418
1419                        snprintf(b1, sizeof(b1), "%02x", flags);
1420                        print_string(PRINT_JSON, "ifa_flags", NULL, b1);
1421                } else {
1422                        fprintf(fp, "flags %02x ", flags);
1423                }
1424        }
1425
1426}
1427
1428static int get_filter(const char *arg)
1429{
1430        bool inv = false;
1431
1432        if (arg[0] == '-') {
1433                inv = true;
1434                arg++;
1435        }
1436
1437        /* Special cases */
1438        if (strcmp(arg, "dynamic") == 0) {
1439                inv = !inv;
1440                arg = "permanent";
1441        } else if (strcmp(arg, "primary") == 0) {
1442                inv = !inv;
1443                arg = "secondary";
1444        }
1445
1446        const struct ifa_flag_data_t* flag_data = lookup_flag_data_by_name(arg);
1447        if (flag_data == NULL)
1448                return -1;
1449
1450        if (inv)
1451                filter.flags &= ~flag_data->mask;
1452        else
1453                filter.flags |= flag_data->mask;
1454        filter.flagmask |= flag_data->mask;
1455        return 0;
1456}
1457
1458static int ifa_label_match_rta(int ifindex, const struct rtattr *rta)
1459{
1460        const char *label;
1461
1462        if (!filter.label)
1463                return 0;
1464
1465        if (rta)
1466                label = RTA_DATA(rta);
1467        else
1468                label = ll_index_to_name(ifindex);
1469
1470        return fnmatch(filter.label, label, 0);
1471}
1472
1473int print_addrinfo(struct nlmsghdr *n, void *arg)
1474{
1475        FILE *fp = arg;
1476        struct ifaddrmsg *ifa = NLMSG_DATA(n);
1477        int len = n->nlmsg_len;
1478        unsigned int ifa_flags;
1479        struct rtattr *rta_tb[IFA_MAX+1];
1480
1481        SPRINT_BUF(b1);
1482
1483        if (n->nlmsg_type != RTM_NEWADDR && n->nlmsg_type != RTM_DELADDR)
1484                return 0;
1485        len -= NLMSG_LENGTH(sizeof(*ifa));
1486        if (len < 0) {
1487                fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
1488                return -1;
1489        }
1490
1491        if (filter.flushb && n->nlmsg_type != RTM_NEWADDR)
1492                return 0;
1493
1494        parse_rtattr(rta_tb, IFA_MAX, IFA_RTA(ifa),
1495                     n->nlmsg_len - NLMSG_LENGTH(sizeof(*ifa)));
1496
1497        ifa_flags = get_ifa_flags(ifa, rta_tb[IFA_FLAGS]);
1498
1499        if (!rta_tb[IFA_LOCAL])
1500                rta_tb[IFA_LOCAL] = rta_tb[IFA_ADDRESS];
1501        if (!rta_tb[IFA_ADDRESS])
1502                rta_tb[IFA_ADDRESS] = rta_tb[IFA_LOCAL];
1503
1504        if (filter.ifindex && filter.ifindex != ifa->ifa_index)
1505                return 0;
1506        if ((filter.scope^ifa->ifa_scope)&filter.scopemask)
1507                return 0;
1508        if ((filter.flags ^ ifa_flags) & filter.flagmask)
1509                return 0;
1510
1511        if (filter.family && filter.family != ifa->ifa_family)
1512                return 0;
1513
1514        if (ifa_label_match_rta(ifa->ifa_index, rta_tb[IFA_LABEL]))
1515                return 0;
1516
1517        if (inet_addr_match_rta(&filter.pfx, rta_tb[IFA_LOCAL]))
1518                return 0;
1519
1520        if (filter.flushb) {
1521                struct nlmsghdr *fn;
1522
1523                if (NLMSG_ALIGN(filter.flushp) + n->nlmsg_len > filter.flushe) {
1524                        if (flush_update())
1525                                return -1;
1526                }
1527                fn = (struct nlmsghdr *)(filter.flushb + NLMSG_ALIGN(filter.flushp));
1528                memcpy(fn, n, n->nlmsg_len);
1529                fn->nlmsg_type = RTM_DELADDR;
1530                fn->nlmsg_flags = NLM_F_REQUEST;
1531                fn->nlmsg_seq = ++rth.seq;
1532                filter.flushp = (((char *)fn) + n->nlmsg_len) - filter.flushb;
1533                filter.flushed++;
1534                if (show_stats < 2)
1535                        return 0;
1536        }
1537
1538        if (n->nlmsg_type == RTM_DELADDR)
1539                print_bool(PRINT_ANY, "deleted", "Deleted ", true);
1540
1541        if (!brief) {
1542                const char *name;
1543
1544                if (filter.oneline || filter.flushb) {
1545                        const char *dev = ll_index_to_name(ifa->ifa_index);
1546
1547                        if (is_json_context()) {
1548                                print_int(PRINT_JSON,
1549                                          "index", NULL, ifa->ifa_index);
1550                                print_string(PRINT_JSON, "dev", NULL, dev);
1551                        } else {
1552                                fprintf(fp, "%u: %s", ifa->ifa_index, dev);
1553                        }
1554                }
1555
1556                name = family_name(ifa->ifa_family);
1557                if (*name != '?') {
1558                        print_string(PRINT_ANY, "family", "    %s ", name);
1559                } else {
1560                        print_int(PRINT_ANY, "family_index", "    family %d ",
1561                                  ifa->ifa_family);
1562                }
1563        }
1564
1565        if (rta_tb[IFA_LOCAL]) {
1566                print_color_string(PRINT_ANY,
1567                                   ifa_family_color(ifa->ifa_family),
1568                                   "local", "%s",
1569                                   format_host_rta(ifa->ifa_family,
1570                                                   rta_tb[IFA_LOCAL]));
1571                if (rta_tb[IFA_ADDRESS] &&
1572                    memcmp(RTA_DATA(rta_tb[IFA_ADDRESS]),
1573                           RTA_DATA(rta_tb[IFA_LOCAL]),
1574                           ifa->ifa_family == AF_INET ? 4 : 16)) {
1575                        print_string(PRINT_FP, NULL, " %s ", "peer");
1576                        print_color_string(PRINT_ANY,
1577                                           ifa_family_color(ifa->ifa_family),
1578                                           "address",
1579                                           "%s",
1580                                           format_host_rta(ifa->ifa_family,
1581                                                           rta_tb[IFA_ADDRESS]));
1582                }
1583                print_int(PRINT_ANY, "prefixlen", "/%d ", ifa->ifa_prefixlen);
1584
1585                if (rta_tb[IFA_RT_PRIORITY])
1586                        print_uint(PRINT_ANY, "metric", "metric %u ",
1587                                   rta_getattr_u32(rta_tb[IFA_RT_PRIORITY]));
1588        }
1589
1590        if (brief)
1591                goto brief_exit;
1592
1593        if (rta_tb[IFA_BROADCAST]) {
1594                print_string(PRINT_FP, NULL, "%s ", "brd");
1595                print_color_string(PRINT_ANY,
1596                                   ifa_family_color(ifa->ifa_family),
1597                                   "broadcast",
1598                                   "%s ",
1599                                   format_host_rta(ifa->ifa_family,
1600                                                   rta_tb[IFA_BROADCAST]));
1601        }
1602
1603        if (rta_tb[IFA_ANYCAST]) {
1604                print_string(PRINT_FP, NULL, "%s ", "any");
1605                print_color_string(PRINT_ANY,
1606                                   ifa_family_color(ifa->ifa_family),
1607                                   "anycast",
1608                                   "%s ",
1609                                   format_host_rta(ifa->ifa_family,
1610                                                   rta_tb[IFA_ANYCAST]));
1611        }
1612
1613        print_string(PRINT_ANY,
1614                     "scope",
1615                     "scope %s ",
1616                     rtnl_rtscope_n2a(ifa->ifa_scope, b1, sizeof(b1)));
1617
1618        print_ifa_flags(fp, ifa, ifa_flags);
1619
1620        if (rta_tb[IFA_LABEL])
1621                print_string(PRINT_ANY,
1622                             "label",
1623                             "%s",
1624                             rta_getattr_str(rta_tb[IFA_LABEL]));
1625
1626        if (rta_tb[IFA_CACHEINFO]) {
1627                struct ifa_cacheinfo *ci = RTA_DATA(rta_tb[IFA_CACHEINFO]);
1628
1629                print_nl();
1630                print_string(PRINT_FP, NULL, "       valid_lft ", NULL);
1631
1632                if (ci->ifa_valid == INFINITY_LIFE_TIME) {
1633                        print_uint(PRINT_JSON,
1634                                   "valid_life_time",
1635                                   NULL, INFINITY_LIFE_TIME);
1636                        print_string(PRINT_FP, NULL, "%s", "forever");
1637                } else {
1638                        print_uint(PRINT_ANY,
1639                                   "valid_life_time", "%usec", ci->ifa_valid);
1640                }
1641
1642                print_string(PRINT_FP, NULL, " preferred_lft ", NULL);
1643                if (ci->ifa_prefered == INFINITY_LIFE_TIME) {
1644                        print_uint(PRINT_JSON,
1645                                   "preferred_life_time",
1646                                   NULL, INFINITY_LIFE_TIME);
1647                        print_string(PRINT_FP, NULL, "%s", "forever");
1648                } else {
1649                        if (ifa_flags & IFA_F_DEPRECATED)
1650                                print_int(PRINT_ANY,
1651                                          "preferred_life_time",
1652                                          "%dsec",
1653                                          ci->ifa_prefered);
1654                        else
1655                                print_uint(PRINT_ANY,
1656                                           "preferred_life_time",
1657                                           "%usec",
1658                                           ci->ifa_prefered);
1659                }
1660        }
1661        print_string(PRINT_FP, NULL, "%s", "\n");
1662brief_exit:
1663        fflush(fp);
1664        return 0;
1665}
1666
1667static int print_selected_addrinfo(struct ifinfomsg *ifi,
1668                                   struct nlmsg_list *ainfo, FILE *fp)
1669{
1670        open_json_array(PRINT_JSON, "addr_info");
1671        for ( ; ainfo ;  ainfo = ainfo->next) {
1672                struct nlmsghdr *n = &ainfo->h;
1673                struct ifaddrmsg *ifa = NLMSG_DATA(n);
1674
1675                if (n->nlmsg_type != RTM_NEWADDR)
1676                        continue;
1677
1678                if (n->nlmsg_len < NLMSG_LENGTH(sizeof(*ifa)))
1679                        return -1;
1680
1681                if (ifa->ifa_index != ifi->ifi_index ||
1682                    (filter.family && filter.family != ifa->ifa_family))
1683                        continue;
1684
1685                if (filter.up && !(ifi->ifi_flags&IFF_UP))
1686                        continue;
1687
1688                open_json_object(NULL);
1689                print_addrinfo(n, fp);
1690                close_json_object();
1691        }
1692        close_json_array(PRINT_JSON, NULL);
1693
1694        if (brief) {
1695                print_string(PRINT_FP, NULL, "%s", "\n");
1696                fflush(fp);
1697        }
1698        return 0;
1699}
1700
1701
1702static int store_nlmsg(struct nlmsghdr *n, void *arg)
1703{
1704        struct nlmsg_chain *lchain = (struct nlmsg_chain *)arg;
1705        struct nlmsg_list *h;
1706
1707        h = malloc(n->nlmsg_len+sizeof(void *));
1708        if (h == NULL)
1709                return -1;
1710
1711        memcpy(&h->h, n, n->nlmsg_len);
1712        h->next = NULL;
1713
1714        if (lchain->tail)
1715                lchain->tail->next = h;
1716        else
1717                lchain->head = h;
1718        lchain->tail = h;
1719
1720        ll_remember_index(n, NULL);
1721        return 0;
1722}
1723
1724static __u32 ipadd_dump_magic = 0x47361222;
1725
1726static int ipadd_save_prep(void)
1727{
1728        int ret;
1729
1730        if (isatty(STDOUT_FILENO)) {
1731                fprintf(stderr, "Not sending a binary stream to stdout\n");
1732                return -1;
1733        }
1734
1735        ret = write(STDOUT_FILENO, &ipadd_dump_magic, sizeof(ipadd_dump_magic));
1736        if (ret != sizeof(ipadd_dump_magic)) {
1737                fprintf(stderr, "Can't write magic to dump file\n");
1738                return -1;
1739        }
1740
1741        return 0;
1742}
1743
1744static int ipadd_dump_check_magic(void)
1745{
1746        int ret;
1747        __u32 magic = 0;
1748
1749        if (isatty(STDIN_FILENO)) {
1750                fprintf(stderr, "Can't restore address dump from a terminal\n");
1751                return -1;
1752        }
1753
1754        ret = fread(&magic, sizeof(magic), 1, stdin);
1755        if (magic != ipadd_dump_magic) {
1756                fprintf(stderr, "Magic mismatch (%d elems, %x magic)\n", ret, magic);
1757                return -1;
1758        }
1759
1760        return 0;
1761}
1762
1763static int save_nlmsg(struct nlmsghdr *n, void *arg)
1764{
1765        int ret;
1766
1767        ret = write(STDOUT_FILENO, n, n->nlmsg_len);
1768        if ((ret > 0) && (ret != n->nlmsg_len)) {
1769                fprintf(stderr, "Short write while saving nlmsg\n");
1770                ret = -EIO;
1771        }
1772
1773        return ret == n->nlmsg_len ? 0 : ret;
1774}
1775
1776static int show_handler(struct rtnl_ctrl_data *ctrl,
1777                        struct nlmsghdr *n, void *arg)
1778{
1779        struct ifaddrmsg *ifa = NLMSG_DATA(n);
1780
1781        open_json_object(NULL);
1782        print_int(PRINT_ANY, "index", "if%d:", ifa->ifa_index);
1783        print_nl();
1784        print_addrinfo(n, stdout);
1785        close_json_object();
1786        return 0;
1787}
1788
1789static int ipaddr_showdump(void)
1790{
1791        int err;
1792
1793        if (ipadd_dump_check_magic())
1794                exit(-1);
1795
1796        new_json_obj(json);
1797        open_json_object(NULL);
1798        open_json_array(PRINT_JSON, "addr_info");
1799
1800        err = rtnl_from_file(stdin, &show_handler, NULL);
1801
1802        close_json_array(PRINT_JSON, NULL);
1803        close_json_object();
1804        delete_json_obj();
1805
1806        exit(err);
1807}
1808
1809static int restore_handler(struct rtnl_ctrl_data *ctrl,
1810                           struct nlmsghdr *n, void *arg)
1811{
1812        int ret;
1813
1814        n->nlmsg_flags |= NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK;
1815
1816        ll_init_map(&rth);
1817
1818        ret = rtnl_talk(&rth, n, NULL);
1819        if ((ret < 0) && (errno == EEXIST))
1820                ret = 0;
1821
1822        return ret;
1823}
1824
1825static int ipaddr_restore(void)
1826{
1827        if (ipadd_dump_check_magic())
1828                exit(-1);
1829
1830        exit(rtnl_from_file(stdin, &restore_handler, NULL));
1831}
1832
1833void free_nlmsg_chain(struct nlmsg_chain *info)
1834{
1835        struct nlmsg_list *l, *n;
1836
1837        for (l = info->head; l; l = n) {
1838                n = l->next;
1839                free(l);
1840        }
1841}
1842
1843static void ipaddr_filter(struct nlmsg_chain *linfo, struct nlmsg_chain *ainfo)
1844{
1845        struct nlmsg_list *l, **lp;
1846
1847        lp = &linfo->head;
1848        while ((l = *lp) != NULL) {
1849                int ok = 0;
1850                int missing_net_address = 1;
1851                struct ifinfomsg *ifi = NLMSG_DATA(&l->h);
1852                struct nlmsg_list *a;
1853
1854                for (a = ainfo->head; a; a = a->next) {
1855                        struct nlmsghdr *n = &a->h;
1856                        struct ifaddrmsg *ifa = NLMSG_DATA(n);
1857                        struct rtattr *tb[IFA_MAX + 1];
1858                        unsigned int ifa_flags;
1859
1860                        if (ifa->ifa_index != ifi->ifi_index)
1861                                continue;
1862                        missing_net_address = 0;
1863                        if (filter.family && filter.family != ifa->ifa_family)
1864                                continue;
1865                        if ((filter.scope^ifa->ifa_scope)&filter.scopemask)
1866                                continue;
1867
1868                        parse_rtattr(tb, IFA_MAX, IFA_RTA(ifa), IFA_PAYLOAD(n));
1869                        ifa_flags = get_ifa_flags(ifa, tb[IFA_FLAGS]);
1870
1871                        if ((filter.flags ^ ifa_flags) & filter.flagmask)
1872                                continue;
1873
1874                        if (ifa_label_match_rta(ifa->ifa_index, tb[IFA_LABEL]))
1875                                continue;
1876
1877                        if (!tb[IFA_LOCAL])
1878                                tb[IFA_LOCAL] = tb[IFA_ADDRESS];
1879                        if (inet_addr_match_rta(&filter.pfx, tb[IFA_LOCAL]))
1880                                continue;
1881
1882                        ok = 1;
1883                        break;
1884                }
1885                if (missing_net_address &&
1886                    (filter.family == AF_UNSPEC || filter.family == AF_PACKET))
1887                        ok = 1;
1888                if (!ok) {
1889                        *lp = l->next;
1890                        free(l);
1891                } else
1892                        lp = &l->next;
1893        }
1894}
1895
1896static int ipaddr_dump_filter(struct nlmsghdr *nlh, int reqlen)
1897{
1898        struct ifaddrmsg *ifa = NLMSG_DATA(nlh);
1899
1900        ifa->ifa_index = filter.ifindex;
1901
1902        return 0;
1903}
1904
1905static int ipaddr_flush(void)
1906{
1907        int round = 0;
1908        char flushb[4096-512];
1909
1910        filter.flushb = flushb;
1911        filter.flushp = 0;
1912        filter.flushe = sizeof(flushb);
1913
1914        while ((max_flush_loops == 0) || (round < max_flush_loops)) {
1915                if (rtnl_addrdump_req(&rth, filter.family,
1916                                      ipaddr_dump_filter) < 0) {
1917                        perror("Cannot send dump request");
1918                        exit(1);
1919                }
1920                filter.flushed = 0;
1921                if (rtnl_dump_filter_nc(&rth, print_addrinfo,
1922                                        stdout, NLM_F_DUMP_INTR) < 0) {
1923                        fprintf(stderr, "Flush terminated\n");
1924                        exit(1);
1925                }
1926                if (filter.flushed == 0) {
1927 flush_done:
1928                        if (show_stats) {
1929                                if (round == 0)
1930                                        printf("Nothing to flush.\n");
1931                                else
1932                                        printf("*** Flush is complete after %d round%s ***\n", round, round > 1?"s":"");
1933                        }
1934                        fflush(stdout);
1935                        return 0;
1936                }
1937                round++;
1938                if (flush_update() < 0)
1939                        return 1;
1940
1941                if (show_stats) {
1942                        printf("\n*** Round %d, deleting %d addresses ***\n", round, filter.flushed);
1943                        fflush(stdout);
1944                }
1945
1946                /* If we are flushing, and specifying primary, then we
1947                 * want to flush only a single round.  Otherwise, we'll
1948                 * start flushing secondaries that were promoted to
1949                 * primaries.
1950                 */
1951                if (!(filter.flags & IFA_F_SECONDARY) && (filter.flagmask & IFA_F_SECONDARY))
1952                        goto flush_done;
1953        }
1954        fprintf(stderr, "*** Flush remains incomplete after %d rounds. ***\n", max_flush_loops);
1955        fflush(stderr);
1956        return 1;
1957}
1958
1959static int iplink_filter_req(struct nlmsghdr *nlh, int reqlen)
1960{
1961        int err;
1962
1963        err = addattr32(nlh, reqlen, IFLA_EXT_MASK, RTEXT_FILTER_VF);
1964        if (err)
1965                return err;
1966
1967        if (filter.master) {
1968                err = addattr32(nlh, reqlen, IFLA_MASTER, filter.master);
1969                if (err)
1970                        return err;
1971        }
1972
1973        if (filter.kind) {
1974                struct rtattr *linkinfo;
1975
1976                linkinfo = addattr_nest(nlh, reqlen, IFLA_LINKINFO);
1977
1978                err = addattr_l(nlh, reqlen, IFLA_INFO_KIND, filter.kind,
1979                                strlen(filter.kind));
1980                if (err)
1981                        return err;
1982
1983                addattr_nest_end(nlh, linkinfo);
1984        }
1985
1986        return 0;
1987}
1988
1989static int ipaddr_link_get(int index, struct nlmsg_chain *linfo)
1990{
1991        struct iplink_req req = {
1992                .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
1993                .n.nlmsg_flags = NLM_F_REQUEST,
1994                .n.nlmsg_type = RTM_GETLINK,
1995                .i.ifi_family = filter.family,
1996                .i.ifi_index = index,
1997        };
1998        __u32 filt_mask = RTEXT_FILTER_VF;
1999        struct nlmsghdr *answer;
2000
2001        if (!show_stats)
2002                filt_mask |= RTEXT_FILTER_SKIP_STATS;
2003
2004        addattr32(&req.n, sizeof(req), IFLA_EXT_MASK, filt_mask);
2005
2006        if (rtnl_talk(&rth, &req.n, &answer) < 0) {
2007                perror("Cannot send link request");
2008                return 1;
2009        }
2010
2011        if (store_nlmsg(answer, linfo) < 0) {
2012                fprintf(stderr, "Failed to process link information\n");
2013                return 1;
2014        }
2015
2016        return 0;
2017}
2018
2019/* fills in linfo with link data and optionally ainfo with address info
2020 * caller can walk lists as desired and must call free_nlmsg_chain for
2021 * both when done
2022 */
2023int ip_link_list(req_filter_fn_t filter_fn, struct nlmsg_chain *linfo)
2024{
2025        if (rtnl_linkdump_req_filter_fn(&rth, preferred_family,
2026                                        filter_fn) < 0) {
2027                perror("Cannot send dump request");
2028                return 1;
2029        }
2030
2031        if (rtnl_dump_filter(&rth, store_nlmsg, linfo) < 0) {
2032                fprintf(stderr, "Dump terminated\n");
2033                return 1;
2034        }
2035
2036        return 0;
2037}
2038
2039static int ip_addr_list(struct nlmsg_chain *ainfo)
2040{
2041        if (rtnl_addrdump_req(&rth, filter.family, ipaddr_dump_filter) < 0) {
2042                perror("Cannot send dump request");
2043                return 1;
2044        }
2045
2046        if (rtnl_dump_filter(&rth, store_nlmsg, ainfo) < 0) {
2047                fprintf(stderr, "Dump terminated\n");
2048                return 1;
2049        }
2050
2051        return 0;
2052}
2053
2054static int ipaddr_list_flush_or_save(int argc, char **argv, int action)
2055{
2056        struct nlmsg_chain linfo = { NULL, NULL};
2057        struct nlmsg_chain _ainfo = { NULL, NULL}, *ainfo = &_ainfo;
2058        struct nlmsg_list *l;
2059        char *filter_dev = NULL;
2060        int no_link = 0;
2061
2062        ipaddr_reset_filter(oneline, 0);
2063        filter.showqueue = 1;
2064        filter.family = preferred_family;
2065
2066        if (action == IPADD_FLUSH) {
2067                if (argc <= 0) {
2068                        fprintf(stderr, "Flush requires arguments.\n");
2069
2070                        return -1;
2071                }
2072                if (filter.family == AF_PACKET) {
2073                        fprintf(stderr, "Cannot flush link addresses.\n");
2074                        return -1;
2075                }
2076        }
2077
2078        while (argc > 0) {
2079                if (strcmp(*argv, "to") == 0) {
2080                        NEXT_ARG();
2081                        if (get_prefix(&filter.pfx, *argv, filter.family))
2082                                invarg("invalid \"to\"\n", *argv);
2083                        if (filter.family == AF_UNSPEC)
2084                                filter.family = filter.pfx.family;
2085                } else if (strcmp(*argv, "scope") == 0) {
2086                        unsigned int scope = 0;
2087
2088                        NEXT_ARG();
2089                        filter.scopemask = -1;
2090                        if (rtnl_rtscope_a2n(&scope, *argv)) {
2091                                if (strcmp(*argv, "all") != 0)
2092                                        invarg("invalid \"scope\"\n", *argv);
2093                                scope = RT_SCOPE_NOWHERE;
2094                                filter.scopemask = 0;
2095                        }
2096                        filter.scope = scope;
2097                } else if (strcmp(*argv, "up") == 0) {
2098                        filter.up = 1;
2099                } else if (get_filter(*argv) == 0) {
2100
2101                } else if (strcmp(*argv, "label") == 0) {
2102                        NEXT_ARG();
2103                        filter.label = *argv;
2104                } else if (strcmp(*argv, "group") == 0) {
2105                        NEXT_ARG();
2106                        if (rtnl_group_a2n(&filter.group, *argv))
2107                                invarg("Invalid \"group\" value\n", *argv);
2108                } else if (strcmp(*argv, "master") == 0) {
2109                        int ifindex;
2110
2111                        NEXT_ARG();
2112                        ifindex = ll_name_to_index(*argv);
2113                        if (!ifindex)
2114                                invarg("Device does not exist\n", *argv);
2115                        filter.master = ifindex;
2116                } else if (strcmp(*argv, "vrf") == 0) {
2117                        int ifindex;
2118
2119                        NEXT_ARG();
2120                        ifindex = ll_name_to_index(*argv);
2121                        if (!ifindex)
2122                                invarg("Not a valid VRF name\n", *argv);
2123                        if (!name_is_vrf(*argv))
2124                                invarg("Not a valid VRF name\n", *argv);
2125                        filter.master = ifindex;
2126                } else if (strcmp(*argv, "type") == 0) {
2127                        int soff;
2128
2129                        NEXT_ARG();
2130                        soff = strlen(*argv) - strlen("_slave");
2131                        if (!strcmp(*argv + soff, "_slave")) {
2132                                (*argv)[soff] = '\0';
2133                                filter.slave_kind = *argv;
2134                        } else {
2135                                filter.kind = *argv;
2136                        }
2137                } else {
2138                        if (strcmp(*argv, "dev") == 0)
2139                                NEXT_ARG();
2140                        else if (matches(*argv, "help") == 0)
2141                                usage();
2142                        if (filter_dev)
2143                                duparg2("dev", *argv);
2144                        filter_dev = *argv;
2145                }
2146                argv++; argc--;
2147        }
2148
2149        if (filter_dev) {
2150                filter.ifindex = ll_name_to_index(filter_dev);
2151                if (filter.ifindex <= 0) {
2152                        fprintf(stderr, "Device \"%s\" does not exist.\n", filter_dev);
2153                        return -1;
2154                }
2155        }
2156
2157        if (action == IPADD_FLUSH)
2158                return ipaddr_flush();
2159
2160        if (action == IPADD_SAVE) {
2161                if (ipadd_save_prep())
2162                        exit(1);
2163
2164                if (rtnl_addrdump_req(&rth, preferred_family,
2165                                      ipaddr_dump_filter) < 0) {
2166                        perror("Cannot send dump request");
2167                        exit(1);
2168                }
2169
2170                if (rtnl_dump_filter(&rth, save_nlmsg, stdout) < 0) {
2171                        fprintf(stderr, "Save terminated\n");
2172                        exit(1);
2173                }
2174
2175                exit(0);
2176        }
2177
2178        /*
2179         * Initialize a json_writer and open an array object
2180         * if -json was specified.
2181         */
2182        new_json_obj(json);
2183
2184        /*
2185         * If only filter_dev present and none of the other
2186         * link filters are present, use RTM_GETLINK to get
2187         * the link device
2188         */
2189        if (filter_dev && filter.group == -1 && do_link == 1) {
2190                if (iplink_get(filter_dev, RTEXT_FILTER_VF) < 0) {
2191                        perror("Cannot send link get request");
2192                        delete_json_obj();
2193                        exit(1);
2194                }
2195                delete_json_obj();
2196                goto out;
2197        }
2198
2199        if (filter.ifindex) {
2200                if (ipaddr_link_get(filter.ifindex, &linfo) != 0)
2201                        goto out;
2202        } else {
2203                if (ip_link_list(iplink_filter_req, &linfo) != 0)
2204                        goto out;
2205        }
2206
2207        if (filter.family != AF_PACKET) {
2208                if (filter.oneline)
2209                        no_link = 1;
2210
2211                if (ip_addr_list(ainfo) != 0)
2212                        goto out;
2213
2214                ipaddr_filter(&linfo, ainfo);
2215        }
2216
2217        for (l = linfo.head; l; l = l->next) {
2218                struct nlmsghdr *n = &l->h;
2219                struct ifinfomsg *ifi = NLMSG_DATA(n);
2220                int res = 0;
2221
2222                open_json_object(NULL);
2223                if (brief || !no_link)
2224                        res = print_linkinfo(n, stdout);
2225                if (res >= 0 && filter.family != AF_PACKET)
2226                        print_selected_addrinfo(ifi, ainfo->head, stdout);
2227                if (res > 0 && !do_link && show_stats)
2228                        print_link_stats(stdout, n);
2229                close_json_object();
2230        }
2231        fflush(stdout);
2232
2233out:
2234        free_nlmsg_chain(ainfo);
2235        free_nlmsg_chain(&linfo);
2236        delete_json_obj();
2237        return 0;
2238}
2239
2240static void
2241ipaddr_loop_each_vf(struct rtattr *tb[], int vfnum, int *min, int *max)
2242{
2243        struct rtattr *vflist = tb[IFLA_VFINFO_LIST];
2244        struct rtattr *i, *vf[IFLA_VF_MAX+1];
2245        struct ifla_vf_rate *vf_rate;
2246        int rem;
2247
2248        rem = RTA_PAYLOAD(vflist);
2249
2250        for (i = RTA_DATA(vflist); RTA_OK(i, rem); i = RTA_NEXT(i, rem)) {
2251                parse_rtattr_nested(vf, IFLA_VF_MAX, i);
2252
2253                if (!vf[IFLA_VF_RATE]) {
2254                        fprintf(stderr, "VF min/max rate API not supported\n");
2255                        exit(1);
2256                }
2257
2258                vf_rate = RTA_DATA(vf[IFLA_VF_RATE]);
2259                if (vf_rate->vf == vfnum) {
2260                        *min = vf_rate->min_tx_rate;
2261                        *max = vf_rate->max_tx_rate;
2262                        return;
2263                }
2264        }
2265        fprintf(stderr, "Cannot find VF %d\n", vfnum);
2266        exit(1);
2267}
2268
2269void ipaddr_get_vf_rate(int vfnum, int *min, int *max, const char *dev)
2270{
2271        struct nlmsg_chain linfo = { NULL, NULL};
2272        struct rtattr *tb[IFLA_MAX+1];
2273        struct ifinfomsg *ifi;
2274        struct nlmsg_list *l;
2275        struct nlmsghdr *n;
2276        int idx, len;
2277
2278        idx = ll_name_to_index(dev);
2279        if (idx == 0) {
2280                fprintf(stderr, "Device %s does not exist\n", dev);
2281                exit(1);
2282        }
2283
2284        if (rtnl_linkdump_req(&rth, AF_UNSPEC) < 0) {
2285                perror("Cannot send dump request");
2286                exit(1);
2287        }
2288        if (rtnl_dump_filter(&rth, store_nlmsg, &linfo) < 0) {
2289                fprintf(stderr, "Dump terminated\n");
2290                exit(1);
2291        }
2292        for (l = linfo.head; l; l = l->next) {
2293                n = &l->h;
2294                ifi = NLMSG_DATA(n);
2295
2296                len = n->nlmsg_len - NLMSG_LENGTH(sizeof(*ifi));
2297                if (len < 0 || (idx && idx != ifi->ifi_index))
2298                        continue;
2299
2300                parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len);
2301
2302                if ((tb[IFLA_VFINFO_LIST] && tb[IFLA_NUM_VF])) {
2303                        ipaddr_loop_each_vf(tb, vfnum, min, max);
2304                        return;
2305                }
2306        }
2307}
2308
2309int ipaddr_list_link(int argc, char **argv)
2310{
2311        preferred_family = AF_PACKET;
2312        do_link = 1;
2313        return ipaddr_list_flush_or_save(argc, argv, IPADD_LIST);
2314}
2315
2316void ipaddr_reset_filter(int oneline, int ifindex)
2317{
2318        memset(&filter, 0, sizeof(filter));
2319        filter.oneline = oneline;
2320        filter.ifindex = ifindex;
2321        filter.group = -1;
2322}
2323
2324static int default_scope(inet_prefix *lcl)
2325{
2326        if (lcl->family == AF_INET) {
2327                if (lcl->bytelen >= 1 && *(__u8 *)&lcl->data == 127)
2328                        return RT_SCOPE_HOST;
2329        }
2330        return 0;
2331}
2332
2333static bool ipaddr_is_multicast(inet_prefix *a)
2334{
2335        if (a->family == AF_INET)
2336                return IN_MULTICAST(ntohl(a->data[0]));
2337        else if (a->family == AF_INET6)
2338                return IN6_IS_ADDR_MULTICAST(a->data);
2339        else
2340                return false;
2341}
2342
2343static bool is_valid_label(const char *dev, const char *label)
2344{
2345        size_t len = strlen(dev);
2346
2347        if (strncmp(label, dev, len) != 0)
2348                return false;
2349
2350        return label[len] == '\0' || label[len] == ':';
2351}
2352
2353static int ipaddr_modify(int cmd, int flags, int argc, char **argv)
2354{
2355        struct {
2356                struct nlmsghdr n;
2357                struct ifaddrmsg        ifa;
2358                char                    buf[256];
2359        } req = {
2360                .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)),
2361                .n.nlmsg_flags = NLM_F_REQUEST | flags,
2362                .n.nlmsg_type = cmd,
2363                .ifa.ifa_family = preferred_family,
2364        };
2365        char  *d = NULL;
2366        char  *l = NULL;
2367        char  *lcl_arg = NULL;
2368        char  *valid_lftp = NULL;
2369        char  *preferred_lftp = NULL;
2370        inet_prefix lcl = {};
2371        inet_prefix peer;
2372        int local_len = 0;
2373        int peer_len = 0;
2374        int brd_len = 0;
2375        int any_len = 0;
2376        int scoped = 0;
2377        __u32 preferred_lft = INFINITY_LIFE_TIME;
2378        __u32 valid_lft = INFINITY_LIFE_TIME;
2379        unsigned int ifa_flags = 0;
2380
2381        while (argc > 0) {
2382                if (strcmp(*argv, "peer") == 0 ||
2383                    strcmp(*argv, "remote") == 0) {
2384                        NEXT_ARG();
2385
2386                        if (peer_len)
2387                                duparg("peer", *argv);
2388                        get_prefix(&peer, *argv, req.ifa.ifa_family);
2389                        peer_len = peer.bytelen;
2390                        if (req.ifa.ifa_family == AF_UNSPEC)
2391                                req.ifa.ifa_family = peer.family;
2392                        addattr_l(&req.n, sizeof(req), IFA_ADDRESS, &peer.data, peer.bytelen);
2393                        req.ifa.ifa_prefixlen = peer.bitlen;
2394                } else if (matches(*argv, "broadcast") == 0 ||
2395                           strcmp(*argv, "brd") == 0) {
2396                        inet_prefix addr;
2397
2398                        NEXT_ARG();
2399                        if (brd_len)
2400                                duparg("broadcast", *argv);
2401                        if (strcmp(*argv, "+") == 0)
2402                                brd_len = -1;
2403                        else if (strcmp(*argv, "-") == 0)
2404                                brd_len = -2;
2405                        else {
2406                                get_addr(&addr, *argv, req.ifa.ifa_family);
2407                                if (req.ifa.ifa_family == AF_UNSPEC)
2408                                        req.ifa.ifa_family = addr.family;
2409                                addattr_l(&req.n, sizeof(req), IFA_BROADCAST, &addr.data, addr.bytelen);
2410                                brd_len = addr.bytelen;
2411                        }
2412                } else if (strcmp(*argv, "anycast") == 0) {
2413                        inet_prefix addr;
2414
2415                        NEXT_ARG();
2416                        if (any_len)
2417                                duparg("anycast", *argv);
2418                        get_addr(&addr, *argv, req.ifa.ifa_family);
2419                        if (req.ifa.ifa_family == AF_UNSPEC)
2420                                req.ifa.ifa_family = addr.family;
2421                        addattr_l(&req.n, sizeof(req), IFA_ANYCAST, &addr.data, addr.bytelen);
2422                        any_len = addr.bytelen;
2423                } else if (strcmp(*argv, "scope") == 0) {
2424                        unsigned int scope = 0;
2425
2426                        NEXT_ARG();
2427                        if (rtnl_rtscope_a2n(&scope, *argv))
2428                                invarg("invalid scope value.", *argv);
2429                        req.ifa.ifa_scope = scope;
2430                        scoped = 1;
2431                } else if (strcmp(*argv, "dev") == 0) {
2432                        NEXT_ARG();
2433                        d = *argv;
2434                } else if (strcmp(*argv, "label") == 0) {
2435                        NEXT_ARG();
2436                        l = *argv;
2437                        addattr_l(&req.n, sizeof(req), IFA_LABEL, l, strlen(l)+1);
2438                } else if (matches(*argv, "metric") == 0 ||
2439                           matches(*argv, "priority") == 0 ||
2440                           matches(*argv, "preference") == 0) {
2441                        __u32 metric;
2442
2443                        NEXT_ARG();
2444                        if (get_u32(&metric, *argv, 0))
2445                                invarg("\"metric\" value is invalid\n", *argv);
2446                        addattr32(&req.n, sizeof(req), IFA_RT_PRIORITY, metric);
2447                } else if (matches(*argv, "valid_lft") == 0) {
2448                        if (valid_lftp)
2449                                duparg("valid_lft", *argv);
2450                        NEXT_ARG();
2451                        valid_lftp = *argv;
2452                        if (set_lifetime(&valid_lft, *argv))
2453                                invarg("valid_lft value", *argv);
2454                } else if (matches(*argv, "preferred_lft") == 0) {
2455                        if (preferred_lftp)
2456                                duparg("preferred_lft", *argv);
2457                        NEXT_ARG();
2458                        preferred_lftp = *argv;
2459                        if (set_lifetime(&preferred_lft, *argv))
2460                                invarg("preferred_lft value", *argv);
2461                } else if (lookup_flag_data_by_name(*argv)) {
2462                        const struct ifa_flag_data_t* flag_data = lookup_flag_data_by_name(*argv);
2463                        if (flag_data->readonly) {
2464                                fprintf(stderr, "Warning: %s option is not mutable from userspace\n", flag_data->name);
2465                        } else if (flag_data->v6only && req.ifa.ifa_family != AF_INET6) {
2466                                fprintf(stderr, "Warning: %s option can be set only for IPv6 addresses\n", flag_data->name);
2467                        } else {
2468                                ifa_flags |= flag_data->mask;
2469                        }
2470                } else {
2471                        if (strcmp(*argv, "local") == 0)
2472                                NEXT_ARG();
2473                        if (matches(*argv, "help") == 0)
2474                                usage();
2475                        if (local_len)
2476                                duparg2("local", *argv);
2477                        lcl_arg = *argv;
2478                        get_prefix(&lcl, *argv, req.ifa.ifa_family);
2479                        if (req.ifa.ifa_family == AF_UNSPEC)
2480                                req.ifa.ifa_family = lcl.family;
2481                        addattr_l(&req.n, sizeof(req), IFA_LOCAL, &lcl.data, lcl.bytelen);
2482                        local_len = lcl.bytelen;
2483                }
2484                argc--; argv++;
2485        }
2486        if (ifa_flags <= 0xff)
2487                req.ifa.ifa_flags = ifa_flags;
2488        else
2489                addattr32(&req.n, sizeof(req), IFA_FLAGS, ifa_flags);
2490
2491        if (d == NULL) {
2492                fprintf(stderr, "Not enough information: \"dev\" argument is required.\n");
2493                return -1;
2494        }
2495        if (l && !is_valid_label(d, l)) {
2496                fprintf(stderr,
2497                        "\"label\" (%s) must match \"dev\" (%s) or be prefixed by \"dev\" with a colon.\n",
2498                        l, d);
2499                return -1;
2500        }
2501
2502        if (peer_len == 0 && local_len) {
2503                if (cmd == RTM_DELADDR && lcl.family == AF_INET && !(lcl.flags & PREFIXLEN_SPECIFIED)) {
2504                        fprintf(stderr,
2505                            "Warning: Executing wildcard deletion to stay compatible with old scripts.\n"
2506                            "         Explicitly specify the prefix length (%s/%d) to avoid this warning.\n"
2507                            "         This special behaviour is likely to disappear in further releases,\n"
2508                            "         fix your scripts!\n", lcl_arg, local_len*8);
2509                } else {
2510                        peer = lcl;
2511                        addattr_l(&req.n, sizeof(req), IFA_ADDRESS, &lcl.data, lcl.bytelen);
2512                }
2513        }
2514        if (req.ifa.ifa_prefixlen == 0)
2515                req.ifa.ifa_prefixlen = lcl.bitlen;
2516
2517        if (brd_len < 0 && cmd != RTM_DELADDR) {
2518                inet_prefix brd;
2519                int i;
2520
2521                if (req.ifa.ifa_family != AF_INET) {
2522                        fprintf(stderr, "Broadcast can be set only for IPv4 addresses\n");
2523                        return -1;
2524                }
2525                brd = peer;
2526                if (brd.bitlen <= 30) {
2527                        for (i = 31; i >= brd.bitlen; i--) {
2528                                if (brd_len == -1)
2529                                        brd.data[0] |= htonl(1<<(31-i));
2530                                else
2531                                        brd.data[0] &= ~htonl(1<<(31-i));
2532                        }
2533                        addattr_l(&req.n, sizeof(req), IFA_BROADCAST, &brd.data, brd.bytelen);
2534                        brd_len = brd.bytelen;
2535                }
2536        }
2537        if (!scoped && cmd != RTM_DELADDR)
2538                req.ifa.ifa_scope = default_scope(&lcl);
2539
2540        req.ifa.ifa_index = ll_name_to_index(d);
2541        if (!req.ifa.ifa_index)
2542                return nodev(d);
2543
2544        if (valid_lftp || preferred_lftp) {
2545                struct ifa_cacheinfo cinfo = {};
2546
2547                if (!valid_lft) {
2548                        fprintf(stderr, "valid_lft is zero\n");
2549                        return -1;
2550                }
2551                if (valid_lft < preferred_lft) {
2552                        fprintf(stderr, "preferred_lft is greater than valid_lft\n");
2553                        return -1;
2554                }
2555
2556                cinfo.ifa_prefered = preferred_lft;
2557                cinfo.ifa_valid = valid_lft;
2558                addattr_l(&req.n, sizeof(req), IFA_CACHEINFO, &cinfo,
2559                          sizeof(cinfo));
2560        }
2561
2562        if ((ifa_flags & IFA_F_MCAUTOJOIN) && !ipaddr_is_multicast(&lcl)) {
2563                fprintf(stderr, "autojoin needs multicast address\n");
2564                return -1;
2565        }
2566
2567        if (rtnl_talk(&rth, &req.n, NULL) < 0)
2568                return -2;
2569
2570        return 0;
2571}
2572
2573int do_ipaddr(int argc, char **argv)
2574{
2575        if (argc < 1)
2576                return ipaddr_list_flush_or_save(0, NULL, IPADD_LIST);
2577        if (matches(*argv, "add") == 0)
2578                return ipaddr_modify(RTM_NEWADDR, NLM_F_CREATE|NLM_F_EXCL, argc-1, argv+1);
2579        if (matches(*argv, "change") == 0 ||
2580                strcmp(*argv, "chg") == 0)
2581                return ipaddr_modify(RTM_NEWADDR, NLM_F_REPLACE, argc-1, argv+1);
2582        if (matches(*argv, "replace") == 0)
2583                return ipaddr_modify(RTM_NEWADDR, NLM_F_CREATE|NLM_F_REPLACE, argc-1, argv+1);
2584        if (matches(*argv, "delete") == 0)
2585                return ipaddr_modify(RTM_DELADDR, 0, argc-1, argv+1);
2586        if (matches(*argv, "list") == 0 || matches(*argv, "show") == 0
2587            || matches(*argv, "lst") == 0)
2588                return ipaddr_list_flush_or_save(argc-1, argv+1, IPADD_LIST);
2589        if (matches(*argv, "flush") == 0)
2590                return ipaddr_list_flush_or_save(argc-1, argv+1, IPADD_FLUSH);
2591        if (matches(*argv, "save") == 0)
2592                return ipaddr_list_flush_or_save(argc-1, argv+1, IPADD_SAVE);
2593        if (matches(*argv, "showdump") == 0)
2594                return ipaddr_showdump();
2595        if (matches(*argv, "restore") == 0)
2596                return ipaddr_restore();
2597        if (matches(*argv, "help") == 0)
2598                usage();
2599        fprintf(stderr, "Command \"%s\" is unknown, try \"ip address help\".\n", *argv);
2600        exit(-1);
2601}
2602