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