]> git.proxmox.com Git - mirror_iproute2.git/blame - ip/ipnetns.c
mptcp: show all endpoints when no ID is specified
[mirror_iproute2.git] / ip / ipnetns.c
CommitLineData
6054c1eb 1/* SPDX-License-Identifier: GPL-2.0 */
0dc34c77
EB
2#define _ATFILE_SOURCE
3#include <sys/types.h>
4#include <sys/stat.h>
5#include <sys/wait.h>
6#include <sys/inotify.h>
7#include <sys/mount.h>
0dc34c77
EB
8#include <sys/syscall.h>
9#include <stdio.h>
10#include <string.h>
11#include <sched.h>
12#include <fcntl.h>
13#include <dirent.h>
14#include <errno.h>
15#include <unistd.h>
9a7b3d91 16#include <ctype.h>
d652ccbf 17#include <linux/limits.h>
0dc34c77 18
d182ee13
ND
19#include <linux/net_namespace.h>
20
0dc34c77 21#include "utils.h"
4952b459 22#include "list.h"
0dc34c77 23#include "ip_common.h"
eb67e449 24#include "namespace.h"
e93d9221 25#include "json_print.h"
0dc34c77 26
8e2d47dc 27static int usage(void)
0dc34c77 28{
8589eb4e
MC
29 fprintf(stderr,
30 "Usage: ip netns list\n"
31 " ip netns add NAME\n"
32 " ip netns attach NAME PID\n"
33 " ip netns set NAME NETNSID\n"
34 " ip [-all] netns delete [NAME]\n"
35 " ip netns identify [PID]\n"
36 " ip netns pids NAME\n"
37 " ip [-all] netns exec [NAME] cmd ...\n"
38 " ip netns monitor\n"
eaefb078 39 " ip netns list-id [target-nsid POSITIVE-INT] [nsid POSITIVE-INT]\n"
8589eb4e 40 "NETNSID := auto | POSITIVE-INT\n");
a05f6511 41 exit(-1);
0dc34c77
EB
42}
43
d652ccbf
ND
44/* This socket is used to get nsid */
45static struct rtnl_handle rtnsh = { .fd = -1 };
46
4c7d9a58 47static int have_rtnl_getnsid = -1;
b2e29223 48static int saved_netns = -1;
eaefb078 49static struct link_filter filter;
4c7d9a58 50
cd554f2c 51static int ipnetns_accept_msg(struct rtnl_ctrl_data *ctrl,
4c7d9a58
ND
52 struct nlmsghdr *n, void *arg)
53{
54 struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(n);
55
56 if (n->nlmsg_type == NLMSG_ERROR &&
57 (err->error == -EOPNOTSUPP || err->error == -EINVAL))
58 have_rtnl_getnsid = 0;
59 else
60 have_rtnl_getnsid = 1;
61 return -1;
62}
63
64static int ipnetns_have_nsid(void)
65{
66 struct {
67 struct nlmsghdr n;
68 struct rtgenmsg g;
69 char buf[1024];
d17b136f
PS
70 } req = {
71 .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
72 .n.nlmsg_flags = NLM_F_REQUEST,
73 .n.nlmsg_type = RTM_GETNSID,
74 .g.rtgen_family = AF_UNSPEC,
75 };
4c7d9a58
ND
76 int fd;
77
78 if (have_rtnl_getnsid < 0) {
4c7d9a58
ND
79 fd = open("/proc/self/ns/net", O_RDONLY);
80 if (fd < 0) {
c44003f7
LZ
81 have_rtnl_getnsid = 0;
82 return 0;
4c7d9a58
ND
83 }
84
85 addattr32(&req.n, 1024, NETNSA_FD, fd);
86
87 if (rtnl_send(&rth, &req.n, req.n.nlmsg_len) < 0) {
88 perror("request send failed");
89 exit(1);
90 }
91 rtnl_listen(&rth, ipnetns_accept_msg, NULL);
92 close(fd);
93 }
94
95 return have_rtnl_getnsid;
96}
97
974ef93b 98int get_netnsid_from_name(const char *name)
d182ee13
ND
99{
100 struct {
101 struct nlmsghdr n;
102 struct rtgenmsg g;
103 char buf[1024];
86bf43c7 104 } req = {
d17b136f
PS
105 .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
106 .n.nlmsg_flags = NLM_F_REQUEST,
107 .n.nlmsg_type = RTM_GETNSID,
108 .g.rtgen_family = AF_UNSPEC,
109 };
86bf43c7 110 struct nlmsghdr *answer;
d182ee13
ND
111 struct rtattr *tb[NETNSA_MAX + 1];
112 struct rtgenmsg *rthdr;
9bf2c538 113 int len, fd, ret = -1;
d182ee13 114
974ef93b
ND
115 netns_nsid_socket_init();
116
d182ee13
ND
117 fd = netns_get_fd(name);
118 if (fd < 0)
119 return fd;
120
121 addattr32(&req.n, 1024, NETNSA_FD, fd);
86bf43c7 122 if (rtnl_talk(&rtnsh, &req.n, &answer) < 0) {
d182ee13
ND
123 close(fd);
124 return -2;
125 }
126 close(fd);
127
128 /* Validate message and parse attributes */
86bf43c7 129 if (answer->nlmsg_type == NLMSG_ERROR)
9bf2c538 130 goto out;
d182ee13 131
86bf43c7
HL
132 rthdr = NLMSG_DATA(answer);
133 len = answer->nlmsg_len - NLMSG_SPACE(sizeof(*rthdr));
d182ee13 134 if (len < 0)
9bf2c538 135 goto out;
d182ee13
ND
136
137 parse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len);
138
86bf43c7 139 if (tb[NETNSA_NSID]) {
f19966ef 140 ret = rta_getattr_s32(tb[NETNSA_NSID]);
86bf43c7 141 }
d182ee13 142
9bf2c538 143out:
86bf43c7 144 free(answer);
9bf2c538 145 return ret;
d182ee13
ND
146}
147
d652ccbf
ND
148struct nsid_cache {
149 struct hlist_node nsid_hash;
150 struct hlist_node name_hash;
151 int nsid;
2f29d6bb 152 char name[0];
d652ccbf
ND
153};
154
155#define NSIDMAP_SIZE 128
156#define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
157#define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
158
159static struct hlist_head nsid_head[NSIDMAP_SIZE];
160static struct hlist_head name_head[NSIDMAP_SIZE];
161
162static struct nsid_cache *netns_map_get_by_nsid(int nsid)
163{
d652ccbf 164 struct hlist_node *n;
08ba67db
GN
165 uint32_t h;
166
167 if (nsid < 0)
168 return NULL;
d652ccbf 169
08ba67db 170 h = NSID_HASH_NSID(nsid);
d652ccbf
ND
171 hlist_for_each(n, &nsid_head[h]) {
172 struct nsid_cache *c = container_of(n, struct nsid_cache,
173 nsid_hash);
174 if (c->nsid == nsid)
175 return c;
176 }
177
178 return NULL;
179}
180
9580bad7
ND
181char *get_name_from_nsid(int nsid)
182{
183 struct nsid_cache *c;
184
08ba67db
GN
185 if (nsid < 0)
186 return NULL;
187
9580bad7
ND
188 netns_nsid_socket_init();
189 netns_map_init();
190
191 c = netns_map_get_by_nsid(nsid);
192 if (c)
193 return c->name;
194
195 return NULL;
196}
197
2f29d6bb 198static int netns_map_add(int nsid, const char *name)
d652ccbf
ND
199{
200 struct nsid_cache *c;
201 uint32_t h;
202
203 if (netns_map_get_by_nsid(nsid) != NULL)
204 return -EEXIST;
205
a1b4a274 206 c = malloc(sizeof(*c) + strlen(name) + 1);
d652ccbf
ND
207 if (c == NULL) {
208 perror("malloc");
209 return -ENOMEM;
210 }
211 c->nsid = nsid;
212 strcpy(c->name, name);
213
214 h = NSID_HASH_NSID(nsid);
215 hlist_add_head(&c->nsid_hash, &nsid_head[h]);
216
217 h = NSID_HASH_NAME(name);
218 hlist_add_head(&c->name_hash, &name_head[h]);
219
220 return 0;
221}
222
223static void netns_map_del(struct nsid_cache *c)
224{
225 hlist_del(&c->name_hash);
226 hlist_del(&c->nsid_hash);
227 free(c);
228}
229
e29a8e05
AA
230void netns_nsid_socket_init(void)
231{
232 if (rtnsh.fd > -1 || !ipnetns_have_nsid())
233 return;
234
235 if (rtnl_open(&rtnsh, 0) < 0) {
236 fprintf(stderr, "Cannot open rtnetlink\n");
237 exit(1);
238 }
239
240}
241
d652ccbf
ND
242void netns_map_init(void)
243{
244 static int initialized;
245 struct dirent *entry;
246 DIR *dir;
247 int nsid;
248
249 if (initialized || !ipnetns_have_nsid())
250 return;
251
d652ccbf
ND
252 dir = opendir(NETNS_RUN_DIR);
253 if (!dir)
254 return;
255
256 while ((entry = readdir(dir)) != NULL) {
257 if (strcmp(entry->d_name, ".") == 0)
258 continue;
259 if (strcmp(entry->d_name, "..") == 0)
260 continue;
261 nsid = get_netnsid_from_name(entry->d_name);
262
263 if (nsid >= 0)
264 netns_map_add(nsid, entry->d_name);
265 }
266 closedir(dir);
267 initialized = 1;
268}
269
270static int netns_get_name(int nsid, char *name)
271{
272 struct dirent *entry;
273 DIR *dir;
274 int id;
275
08ba67db
GN
276 if (nsid < 0)
277 return -EINVAL;
278
d652ccbf
ND
279 dir = opendir(NETNS_RUN_DIR);
280 if (!dir)
281 return -ENOENT;
282
283 while ((entry = readdir(dir)) != NULL) {
284 if (strcmp(entry->d_name, ".") == 0)
285 continue;
286 if (strcmp(entry->d_name, "..") == 0)
287 continue;
288 id = get_netnsid_from_name(entry->d_name);
289
08ba67db 290 if (id >= 0 && nsid == id) {
d652ccbf
ND
291 strcpy(name, entry->d_name);
292 closedir(dir);
293 return 0;
294 }
295 }
296 closedir(dir);
297 return -ENOENT;
298}
299
cd554f2c 300int print_nsid(struct nlmsghdr *n, void *arg)
d652ccbf
ND
301{
302 struct rtgenmsg *rthdr = NLMSG_DATA(n);
303 struct rtattr *tb[NETNSA_MAX+1];
304 int len = n->nlmsg_len;
305 FILE *fp = (FILE *)arg;
306 struct nsid_cache *c;
307 char name[NAME_MAX];
eaefb078 308 int nsid, current;
d652ccbf
ND
309
310 if (n->nlmsg_type != RTM_NEWNSID && n->nlmsg_type != RTM_DELNSID)
311 return 0;
312
313 len -= NLMSG_SPACE(sizeof(*rthdr));
314 if (len < 0) {
315 fprintf(stderr, "BUG: wrong nlmsg len %d in %s\n", len,
316 __func__);
317 return -1;
318 }
319
320 parse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len);
321 if (tb[NETNSA_NSID] == NULL) {
322 fprintf(stderr, "BUG: NETNSA_NSID is missing %s\n", __func__);
323 return -1;
324 }
325
e93d9221 326 open_json_object(NULL);
d652ccbf 327 if (n->nlmsg_type == RTM_DELNSID)
e93d9221 328 print_bool(PRINT_ANY, "deleted", "Deleted ", true);
d652ccbf 329
f19966ef 330 nsid = rta_getattr_s32(tb[NETNSA_NSID]);
eaefb078 331 if (nsid < 0)
1c9b6927 332 print_string(PRINT_FP, NULL, "nsid unassigned ", NULL);
eaefb078 333 else
f19966ef 334 print_int(PRINT_ANY, "nsid", "nsid %d ", nsid);
eaefb078
ND
335
336 if (tb[NETNSA_CURRENT_NSID]) {
f19966ef 337 current = rta_getattr_s32(tb[NETNSA_CURRENT_NSID]);
eaefb078 338 if (current < 0)
1c9b6927
GN
339 print_string(PRINT_FP, NULL,
340 "current-nsid unassigned ", NULL);
eaefb078 341 else
f19966ef
GN
342 print_int(PRINT_ANY, "current-nsid",
343 "current-nsid %d ", current);
eaefb078 344 }
d652ccbf 345
eaefb078 346 c = netns_map_get_by_nsid(tb[NETNSA_CURRENT_NSID] ? current : nsid);
d652ccbf 347 if (c != NULL) {
e93d9221
SH
348 print_string(PRINT_ANY, "name",
349 "(iproute2 netns name: %s)", c->name);
d652ccbf
ND
350 netns_map_del(c);
351 }
352
df6da60b 353 /* nsid might not be in cache */
d652ccbf
ND
354 if (c == NULL && n->nlmsg_type == RTM_NEWNSID)
355 if (netns_get_name(nsid, name) == 0) {
e93d9221
SH
356 print_string(PRINT_ANY, "name",
357 "(iproute2 netns name: %s)", name);
d652ccbf
ND
358 netns_map_add(nsid, name);
359 }
360
e93d9221
SH
361 print_string(PRINT_FP, NULL, "\n", NULL);
362 close_json_object();
d652ccbf
ND
363 fflush(fp);
364 return 0;
365}
366
eaefb078
ND
367static int get_netnsid_from_netnsid(int nsid)
368{
369 struct {
370 struct nlmsghdr n;
371 struct rtgenmsg g;
372 char buf[1024];
373 } req = {
374 .n.nlmsg_len = NLMSG_LENGTH(NLMSG_ALIGN(sizeof(struct rtgenmsg))),
375 .n.nlmsg_flags = NLM_F_REQUEST,
376 .n.nlmsg_type = RTM_GETNSID,
377 .g.rtgen_family = AF_UNSPEC,
378 };
379 struct nlmsghdr *answer;
380 int err;
381
382 netns_nsid_socket_init();
383
384 err = addattr32(&req.n, sizeof(req), NETNSA_NSID, nsid);
385 if (err)
386 return err;
387
388 if (filter.target_nsid >= 0) {
389 err = addattr32(&req.n, sizeof(req), NETNSA_TARGET_NSID,
390 filter.target_nsid);
391 if (err)
392 return err;
393 }
394
395 if (rtnl_talk(&rtnsh, &req.n, &answer) < 0)
396 return -2;
397
398 /* Validate message and parse attributes */
399 if (answer->nlmsg_type == NLMSG_ERROR)
400 goto err_out;
401
402 new_json_obj(json);
403 err = print_nsid(answer, stdout);
404 delete_json_obj();
405err_out:
406 free(answer);
407 return err;
408}
409
410static int netns_filter_req(struct nlmsghdr *nlh, int reqlen)
411{
412 int err;
413
414 if (filter.target_nsid >= 0) {
415 err = addattr32(nlh, reqlen, NETNSA_TARGET_NSID,
416 filter.target_nsid);
417 if (err)
418 return err;
419 }
420
421 return 0;
422}
423
d652ccbf
ND
424static int netns_list_id(int argc, char **argv)
425{
eaefb078
ND
426 int nsid = -1;
427
d652ccbf
ND
428 if (!ipnetns_have_nsid()) {
429 fprintf(stderr,
430 "RTM_GETNSID is not supported by the kernel.\n");
431 return -ENOTSUP;
432 }
433
eaefb078
ND
434 filter.target_nsid = -1;
435 while (argc > 0) {
436 if (strcmp(*argv, "target-nsid") == 0) {
437 if (filter.target_nsid >= 0)
438 duparg("target-nsid", *argv);
439 NEXT_ARG();
440
441 if (get_integer(&filter.target_nsid, *argv, 0))
d0b645a5 442 invarg("\"target-nsid\" value is invalid",
eaefb078
ND
443 *argv);
444 else if (filter.target_nsid < 0)
d0b645a5 445 invarg("\"target-nsid\" value should be >= 0",
eaefb078
ND
446 argv[1]);
447 } else if (strcmp(*argv, "nsid") == 0) {
448 if (nsid >= 0)
449 duparg("nsid", *argv);
450 NEXT_ARG();
451
452 if (get_integer(&nsid, *argv, 0))
d0b645a5 453 invarg("\"nsid\" value is invalid", *argv);
eaefb078 454 else if (nsid < 0)
d0b645a5 455 invarg("\"nsid\" value should be >= 0",
eaefb078
ND
456 argv[1]);
457 } else
458 usage();
459 argc--; argv++;
460 }
461
462 if (nsid >= 0)
463 return get_netnsid_from_netnsid(nsid);
464
465 if (rtnl_nsiddump_req_filter_fn(&rth, AF_UNSPEC,
466 netns_filter_req) < 0) {
d652ccbf
ND
467 perror("Cannot send dump request");
468 exit(1);
469 }
e93d9221
SH
470
471 new_json_obj(json);
d652ccbf 472 if (rtnl_dump_filter(&rth, print_nsid, stdout) < 0) {
e93d9221 473 delete_json_obj();
d652ccbf
ND
474 fprintf(stderr, "Dump terminated\n");
475 exit(1);
476 }
e93d9221 477 delete_json_obj();
d652ccbf
ND
478 return 0;
479}
480
0dc34c77
EB
481static int netns_list(int argc, char **argv)
482{
483 struct dirent *entry;
484 DIR *dir;
d182ee13 485 int id;
0dc34c77
EB
486
487 dir = opendir(NETNS_RUN_DIR);
488 if (!dir)
a05f6511 489 return 0;
0dc34c77 490
e93d9221 491 new_json_obj(json);
0dc34c77
EB
492 while ((entry = readdir(dir)) != NULL) {
493 if (strcmp(entry->d_name, ".") == 0)
494 continue;
495 if (strcmp(entry->d_name, "..") == 0)
496 continue;
e93d9221
SH
497
498 open_json_object(NULL);
499 print_string(PRINT_ANY, "name",
500 "%s", entry->d_name);
4c7d9a58
ND
501 if (ipnetns_have_nsid()) {
502 id = get_netnsid_from_name(entry->d_name);
503 if (id >= 0)
f19966ef 504 print_int(PRINT_ANY, "id", " (id: %d)", id);
4c7d9a58 505 }
e93d9221
SH
506 print_string(PRINT_FP, NULL, "\n", NULL);
507 close_json_object();
0dc34c77
EB
508 }
509 closedir(dir);
e93d9221 510 delete_json_obj();
a05f6511 511 return 0;
0dc34c77
EB
512}
513
903818fb
MC
514static int do_switch(void *arg)
515{
516 char *netns = arg;
517
518 /* we just changed namespaces. clear any vrf association
519 * with prior namespace before exec'ing command
520 */
521 vrf_reset();
522
523 return netns_switch(netns);
524}
525
b13ba03f
VK
526static int on_netns_exec(char *nsname, void *arg)
527{
528 char **argv = arg;
56f5daac 529
903818fb
MC
530 printf("\nnetns: %s\n", nsname);
531 cmd_exec(argv[0], argv, true, do_switch, nsname);
b13ba03f
VK
532 return 0;
533}
534
535static int netns_exec(int argc, char **argv)
536{
537 /* Setup the proper environment for apps that are not netns
538 * aware, and execute a program in that environment.
539 */
b13ba03f
VK
540 if (argc < 1 && !do_all) {
541 fprintf(stderr, "No netns name specified\n");
542 return -1;
543 }
544 if ((argc < 2 && !do_all) || (argc < 1 && do_all)) {
545 fprintf(stderr, "No command specified\n");
546 return -1;
547 }
548
549 if (do_all)
903818fb 550 return netns_foreach(on_netns_exec, argv);
ee9369a0 551
b13ba03f
VK
552 /* ip must return the status of the child,
553 * but do_cmd() will add a minus to this,
554 * so let's add another one here to cancel it.
555 */
903818fb 556 return -cmd_exec(argv[1], argv + 1, !!batch_mode, do_switch, argv[0]);
b13ba03f
VK
557}
558
9a7b3d91
EB
559static int is_pid(const char *str)
560{
561 int ch;
56f5daac 562
9a7b3d91
EB
563 for (; (ch = *str); str++) {
564 if (!isdigit(ch))
565 return 0;
566 }
567 return 1;
568}
569
570static int netns_pids(int argc, char **argv)
571{
572 const char *name;
ea343669 573 char net_path[PATH_MAX];
9a7b3d91
EB
574 int netns;
575 struct stat netst;
576 DIR *dir;
577 struct dirent *entry;
578
579 if (argc < 1) {
580 fprintf(stderr, "No netns name specified\n");
a05f6511 581 return -1;
9a7b3d91
EB
582 }
583 if (argc > 1) {
584 fprintf(stderr, "extra arguments specified\n");
a05f6511 585 return -1;
9a7b3d91
EB
586 }
587
588 name = argv[0];
589 snprintf(net_path, sizeof(net_path), "%s/%s", NETNS_RUN_DIR, name);
590 netns = open(net_path, O_RDONLY);
591 if (netns < 0) {
592 fprintf(stderr, "Cannot open network namespace: %s\n",
593 strerror(errno));
a05f6511 594 return -1;
9a7b3d91
EB
595 }
596 if (fstat(netns, &netst) < 0) {
597 fprintf(stderr, "Stat of netns failed: %s\n",
598 strerror(errno));
a05f6511 599 return -1;
9a7b3d91
EB
600 }
601 dir = opendir("/proc/");
602 if (!dir) {
603 fprintf(stderr, "Open of /proc failed: %s\n",
604 strerror(errno));
a05f6511 605 return -1;
9a7b3d91 606 }
56f5daac 607 while ((entry = readdir(dir))) {
ea343669 608 char pid_net_path[PATH_MAX];
9a7b3d91 609 struct stat st;
56f5daac 610
9a7b3d91
EB
611 if (!is_pid(entry->d_name))
612 continue;
613 snprintf(pid_net_path, sizeof(pid_net_path), "/proc/%s/ns/net",
614 entry->d_name);
615 if (stat(pid_net_path, &st) != 0)
616 continue;
617 if ((st.st_dev == netst.st_dev) &&
618 (st.st_ino == netst.st_ino)) {
619 printf("%s\n", entry->d_name);
620 }
621 }
622 closedir(dir);
a05f6511 623 return 0;
0612519e 624
9a7b3d91
EB
625}
626
9c49438a 627int netns_identify_pid(const char *pidstr, char *name, int len)
9a7b3d91 628{
ea343669 629 char net_path[PATH_MAX];
9a7b3d91
EB
630 int netns;
631 struct stat netst;
632 DIR *dir;
633 struct dirent *entry;
634
9c49438a 635 name[0] = '\0';
9a7b3d91
EB
636
637 snprintf(net_path, sizeof(net_path), "/proc/%s/ns/net", pidstr);
638 netns = open(net_path, O_RDONLY);
639 if (netns < 0) {
640 fprintf(stderr, "Cannot open network namespace: %s\n",
641 strerror(errno));
a05f6511 642 return -1;
9a7b3d91
EB
643 }
644 if (fstat(netns, &netst) < 0) {
645 fprintf(stderr, "Stat of netns failed: %s\n",
646 strerror(errno));
a05f6511 647 return -1;
9a7b3d91
EB
648 }
649 dir = opendir(NETNS_RUN_DIR);
650 if (!dir) {
651 /* Succeed treat a missing directory as an empty directory */
652 if (errno == ENOENT)
a05f6511 653 return 0;
9a7b3d91
EB
654
655 fprintf(stderr, "Failed to open directory %s:%s\n",
656 NETNS_RUN_DIR, strerror(errno));
a05f6511 657 return -1;
9a7b3d91
EB
658 }
659
56f5daac 660 while ((entry = readdir(dir))) {
ea343669 661 char name_path[PATH_MAX];
9a7b3d91
EB
662 struct stat st;
663
664 if (strcmp(entry->d_name, ".") == 0)
665 continue;
666 if (strcmp(entry->d_name, "..") == 0)
667 continue;
668
669 snprintf(name_path, sizeof(name_path), "%s/%s", NETNS_RUN_DIR,
670 entry->d_name);
671
672 if (stat(name_path, &st) != 0)
673 continue;
674
675 if ((st.st_dev == netst.st_dev) &&
676 (st.st_ino == netst.st_ino)) {
18f156bf 677 strlcpy(name, entry->d_name, len);
9a7b3d91
EB
678 }
679 }
680 closedir(dir);
a05f6511 681 return 0;
0612519e 682
9a7b3d91
EB
683}
684
9c49438a
DA
685static int netns_identify(int argc, char **argv)
686{
687 const char *pidstr;
688 char name[256];
689 int rc;
690
691 if (argc < 1) {
692 pidstr = "self";
693 } else if (argc > 1) {
694 fprintf(stderr, "extra arguments specified\n");
695 return -1;
696 } else {
697 pidstr = argv[0];
698 if (!is_pid(pidstr)) {
699 fprintf(stderr, "Specified string '%s' is not a pid\n",
700 pidstr);
701 return -1;
702 }
703 }
704
705 rc = netns_identify_pid(pidstr, name, sizeof(name));
706 if (!rc)
707 printf("%s\n", name);
708
709 return rc;
710}
711
33724939 712static int on_netns_del(char *nsname, void *arg)
0dc34c77 713{
ea343669 714 char netns_path[PATH_MAX];
0dc34c77 715
33724939 716 snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, nsname);
0dc34c77
EB
717 umount2(netns_path, MNT_DETACH);
718 if (unlink(netns_path) < 0) {
14645ec2 719 fprintf(stderr, "Cannot remove namespace file \"%s\": %s\n",
0dc34c77 720 netns_path, strerror(errno));
a05f6511 721 return -1;
0dc34c77 722 }
a05f6511 723 return 0;
0dc34c77
EB
724}
725
33724939
VK
726static int netns_delete(int argc, char **argv)
727{
728 if (argc < 1 && !do_all) {
729 fprintf(stderr, "No netns name specified\n");
730 return -1;
731 }
732
733 if (do_all)
734 return netns_foreach(on_netns_del, NULL);
735
736 return on_netns_del(argv[0], NULL);
737}
738
c1cbb18a 739static int create_netns_dir(void)
740{
741 /* Create the base netns directory if it doesn't exist */
742 if (mkdir(NETNS_RUN_DIR, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)) {
743 if (errno != EEXIST) {
744 fprintf(stderr, "mkdir %s failed: %s\n",
745 NETNS_RUN_DIR, strerror(errno));
746 return -1;
747 }
748 }
749
750 return 0;
751}
752
b2e29223
MC
753/* Obtain a FD for the current namespace, so we can reenter it later */
754static void netns_save(void)
755{
756 if (saved_netns != -1)
757 return;
758
759 saved_netns = open("/proc/self/ns/net", O_RDONLY | O_CLOEXEC);
760 if (saved_netns == -1) {
761 perror("Cannot open init namespace");
762 exit(1);
763 }
764}
765
766static void netns_restore(void)
767{
768 if (saved_netns == -1)
769 return;
770
771 if (setns(saved_netns, CLONE_NEWNET)) {
772 perror("setns");
773 exit(1);
774 }
775
776 close(saved_netns);
777 saved_netns = -1;
778}
779
e3dbcb2a 780static int netns_add(int argc, char **argv, bool create)
0dc34c77
EB
781{
782 /* This function creates a new network namespace and
783 * a new mount namespace and bind them into a well known
784 * location in the filesystem based on the name provided.
785 *
e3dbcb2a
MC
786 * If create is true, a new namespace will be created,
787 * otherwise an existing one will be attached to the file.
788 *
0dc34c77
EB
789 * The mount namespace is created so that any necessary
790 * userspace tweaks like remounting /sys, or bind mounting
e3dbcb2a 791 * a new /etc/resolv.conf can be shared between users.
0dc34c77 792 */
e3dbcb2a 793 char netns_path[PATH_MAX], proc_path[PATH_MAX];
0dc34c77 794 const char *name;
e3dbcb2a 795 pid_t pid;
223f4d8e 796 int fd;
58a3e827 797 int made_netns_run_dir_mount = 0;
0dc34c77 798
e3dbcb2a
MC
799 if (create) {
800 if (argc < 1) {
801 fprintf(stderr, "No netns name specified\n");
802 return -1;
803 }
804 } else {
805 if (argc < 2) {
806 fprintf(stderr, "No netns name and PID specified\n");
807 return -1;
808 }
809
810 if (get_s32(&pid, argv[1], 0) || !pid) {
811 fprintf(stderr, "Invalid PID: %s\n", argv[1]);
812 return -1;
813 }
0dc34c77
EB
814 }
815 name = argv[0];
816
817 snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, name);
818
c1cbb18a 819 if (create_netns_dir())
820 return -1;
0dc34c77 821
d259f030 822 /* Make it possible for network namespace mounts to propagate between
58a3e827
EB
823 * mount namespaces. This makes it likely that a unmounting a network
824 * namespace file in one namespace will unmount the network namespace
825 * file in all namespaces allowing the network namespace to be freed
826 * sooner.
827 */
828 while (mount("", NETNS_RUN_DIR, "none", MS_SHARED | MS_REC, NULL)) {
829 /* Fail unless we need to make the mount point */
830 if (errno != EINVAL || made_netns_run_dir_mount) {
831 fprintf(stderr, "mount --make-shared %s failed: %s\n",
832 NETNS_RUN_DIR, strerror(errno));
a05f6511 833 return -1;
58a3e827
EB
834 }
835
836 /* Upgrade NETNS_RUN_DIR to a mount point */
d6a4076b 837 if (mount(NETNS_RUN_DIR, NETNS_RUN_DIR, "none", MS_BIND | MS_REC, NULL)) {
58a3e827
EB
838 fprintf(stderr, "mount --bind %s %s failed: %s\n",
839 NETNS_RUN_DIR, NETNS_RUN_DIR, strerror(errno));
a05f6511 840 return -1;
58a3e827
EB
841 }
842 made_netns_run_dir_mount = 1;
843 }
844
0dc34c77 845 /* Create the filesystem state */
223f4d8e
EB
846 fd = open(netns_path, O_RDONLY|O_CREAT|O_EXCL, 0);
847 if (fd < 0) {
55713c8c 848 fprintf(stderr, "Cannot create namespace file \"%s\": %s\n",
0dc34c77 849 netns_path, strerror(errno));
a05f6511 850 return -1;
0dc34c77 851 }
223f4d8e 852 close(fd);
e3dbcb2a
MC
853
854 if (create) {
80a931d4 855 netns_save();
e3dbcb2a
MC
856 if (unshare(CLONE_NEWNET) < 0) {
857 fprintf(stderr, "Failed to create a new network namespace \"%s\": %s\n",
858 name, strerror(errno));
859 goto out_delete;
860 }
861
862 strcpy(proc_path, "/proc/self/ns/net");
863 } else {
864 snprintf(proc_path, sizeof(proc_path), "/proc/%d/ns/net", pid);
0dc34c77
EB
865 }
866
867 /* Bind the netns last so I can watch for it */
e3dbcb2a
MC
868 if (mount(proc_path, netns_path, "none", MS_BIND, NULL) < 0) {
869 fprintf(stderr, "Bind %s -> %s failed: %s\n",
870 proc_path, netns_path, strerror(errno));
0dc34c77
EB
871 goto out_delete;
872 }
b2e29223
MC
873 netns_restore();
874
a05f6511 875 return 0;
0dc34c77 876out_delete:
e3dbcb2a 877 if (create) {
b2e29223 878 netns_restore();
e3dbcb2a
MC
879 netns_delete(argc, argv);
880 } else if (unlink(netns_path) < 0) {
881 fprintf(stderr, "Cannot remove namespace file \"%s\": %s\n",
882 netns_path, strerror(errno));
883 }
a05f6511 884 return -1;
0dc34c77
EB
885}
886
974ef93b 887int set_netnsid_from_name(const char *name, int nsid)
d182ee13
ND
888{
889 struct {
890 struct nlmsghdr n;
891 struct rtgenmsg g;
892 char buf[1024];
d17b136f
PS
893 } req = {
894 .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)),
895 .n.nlmsg_flags = NLM_F_REQUEST,
896 .n.nlmsg_type = RTM_NEWNSID,
897 .g.rtgen_family = AF_UNSPEC,
898 };
d182ee13
ND
899 int fd, err = 0;
900
974ef93b
ND
901 netns_nsid_socket_init();
902
d182ee13
ND
903 fd = netns_get_fd(name);
904 if (fd < 0)
905 return fd;
906
907 addattr32(&req.n, 1024, NETNSA_FD, fd);
908 addattr32(&req.n, 1024, NETNSA_NSID, nsid);
86bf43c7 909 if (rtnl_talk(&rth, &req.n, NULL) < 0)
d182ee13
ND
910 err = -2;
911
912 close(fd);
913 return err;
914}
915
916static int netns_set(int argc, char **argv)
917{
ea343669 918 char netns_path[PATH_MAX];
d182ee13 919 const char *name;
ebe3ce2f 920 int netns, nsid;
d182ee13
ND
921
922 if (argc < 1) {
923 fprintf(stderr, "No netns name specified\n");
924 return -1;
925 }
926 if (argc < 2) {
927 fprintf(stderr, "No nsid specified\n");
928 return -1;
929 }
930 name = argv[0];
375d51ca
CB
931 /* If a negative nsid is specified the kernel will select the nsid. */
932 if (strcmp(argv[1], "auto") == 0)
933 nsid = -1;
ebe3ce2f 934 else if (get_integer(&nsid, argv[1], 0))
d0b645a5 935 invarg("Invalid \"netnsid\" value", argv[1]);
ebe3ce2f 936 else if (nsid < 0)
d0b645a5 937 invarg("\"netnsid\" value should be >= 0", argv[1]);
d182ee13
ND
938
939 snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, name);
940 netns = open(netns_path, O_RDONLY | O_CLOEXEC);
941 if (netns < 0) {
942 fprintf(stderr, "Cannot open network namespace \"%s\": %s\n",
943 name, strerror(errno));
944 return -1;
945 }
946
947 return set_netnsid_from_name(name, nsid);
948}
0dc34c77
EB
949
950static int netns_monitor(int argc, char **argv)
951{
952 char buf[4096];
953 struct inotify_event *event;
954 int fd;
56f5daac 955
0dc34c77
EB
956 fd = inotify_init();
957 if (fd < 0) {
958 fprintf(stderr, "inotify_init failed: %s\n",
959 strerror(errno));
a05f6511 960 return -1;
0dc34c77 961 }
c1cbb18a 962
963 if (create_netns_dir())
964 return -1;
965
0dc34c77
EB
966 if (inotify_add_watch(fd, NETNS_RUN_DIR, IN_CREATE | IN_DELETE) < 0) {
967 fprintf(stderr, "inotify_add_watch failed: %s\n",
968 strerror(errno));
a05f6511 969 return -1;
0dc34c77 970 }
56f5daac 971 for (;;) {
0dc34c77 972 ssize_t len = read(fd, buf, sizeof(buf));
56f5daac 973
0dc34c77
EB
974 if (len < 0) {
975 fprintf(stderr, "read failed: %s\n",
976 strerror(errno));
a05f6511 977 return -1;
0dc34c77
EB
978 }
979 for (event = (struct inotify_event *)buf;
980 (char *)event < &buf[len];
981 event = (struct inotify_event *)((char *)event + sizeof(*event) + event->len)) {
982 if (event->mask & IN_CREATE)
983 printf("add %s\n", event->name);
984 if (event->mask & IN_DELETE)
985 printf("delete %s\n", event->name);
986 }
987 }
a05f6511 988 return 0;
0dc34c77
EB
989}
990
79928fd0
MC
991static int invalid_name(const char *name)
992{
d3f0b091
MC
993 return !*name || strlen(name) > NAME_MAX ||
994 strchr(name, '/') || !strcmp(name, ".") || !strcmp(name, "..");
79928fd0
MC
995}
996
0dc34c77
EB
997int do_netns(int argc, char **argv)
998{
e29a8e05 999 netns_nsid_socket_init();
d652ccbf 1000
e29a8e05
AA
1001 if (argc < 1) {
1002 netns_map_init();
0dc34c77 1003 return netns_list(0, NULL);
e29a8e05 1004 }
0dc34c77 1005
b7f28e0b 1006 if (!do_all && argc > 1 && invalid_name(argv[1])) {
79928fd0
MC
1007 fprintf(stderr, "Invalid netns name \"%s\"\n", argv[1]);
1008 exit(-1);
1009 }
1010
0dc34c77 1011 if ((matches(*argv, "list") == 0) || (matches(*argv, "show") == 0) ||
e29a8e05
AA
1012 (matches(*argv, "lst") == 0)) {
1013 netns_map_init();
0dc34c77 1014 return netns_list(argc-1, argv+1);
e29a8e05 1015 }
0dc34c77 1016
e29a8e05
AA
1017 if ((matches(*argv, "list-id") == 0)) {
1018 netns_map_init();
d652ccbf 1019 return netns_list_id(argc-1, argv+1);
e29a8e05 1020 }
d652ccbf 1021
0dc34c77 1022 if (matches(*argv, "help") == 0)
8e2d47dc 1023 return usage();
0dc34c77
EB
1024
1025 if (matches(*argv, "add") == 0)
e3dbcb2a 1026 return netns_add(argc-1, argv+1, true);
0dc34c77 1027
d182ee13
ND
1028 if (matches(*argv, "set") == 0)
1029 return netns_set(argc-1, argv+1);
1030
0dc34c77
EB
1031 if (matches(*argv, "delete") == 0)
1032 return netns_delete(argc-1, argv+1);
1033
9a7b3d91
EB
1034 if (matches(*argv, "identify") == 0)
1035 return netns_identify(argc-1, argv+1);
1036
1037 if (matches(*argv, "pids") == 0)
1038 return netns_pids(argc-1, argv+1);
1039
0dc34c77
EB
1040 if (matches(*argv, "exec") == 0)
1041 return netns_exec(argc-1, argv+1);
1042
1043 if (matches(*argv, "monitor") == 0)
1044 return netns_monitor(argc-1, argv+1);
1045
e3dbcb2a
MC
1046 if (matches(*argv, "attach") == 0)
1047 return netns_add(argc-1, argv+1, false);
1048
0dc34c77 1049 fprintf(stderr, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv);
a05f6511 1050 exit(-1);
0dc34c77 1051}