]> git.proxmox.com Git - mirror_iproute2.git/blob - ip/ipnetns.c
devlink: Add ability to bind policer to trap group
[mirror_iproute2.git] / ip / ipnetns.c
1 /* SPDX-License-Identifier: GPL-2.0 */
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>
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>
16 #include <ctype.h>
17 #include <linux/limits.h>
18
19 #include <linux/net_namespace.h>
20
21 #include "utils.h"
22 #include "list.h"
23 #include "ip_common.h"
24 #include "namespace.h"
25 #include "json_print.h"
26
27 static int usage(void)
28 {
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"
39 " ip netns list-id [target-nsid POSITIVE-INT] [nsid POSITIVE-INT]\n"
40 "NETNSID := auto | POSITIVE-INT\n");
41 exit(-1);
42 }
43
44 /* This socket is used to get nsid */
45 static struct rtnl_handle rtnsh = { .fd = -1 };
46
47 static int have_rtnl_getnsid = -1;
48 static int saved_netns = -1;
49 static struct link_filter filter;
50
51 static int ipnetns_accept_msg(struct rtnl_ctrl_data *ctrl,
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
64 static int ipnetns_have_nsid(void)
65 {
66 struct {
67 struct nlmsghdr n;
68 struct rtgenmsg g;
69 char buf[1024];
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 };
76 int fd;
77
78 if (have_rtnl_getnsid < 0) {
79 fd = open("/proc/self/ns/net", O_RDONLY);
80 if (fd < 0) {
81 have_rtnl_getnsid = 0;
82 return 0;
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
98 int get_netnsid_from_name(const char *name)
99 {
100 struct {
101 struct nlmsghdr n;
102 struct rtgenmsg g;
103 char buf[1024];
104 } req = {
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 };
110 struct nlmsghdr *answer;
111 struct rtattr *tb[NETNSA_MAX + 1];
112 struct rtgenmsg *rthdr;
113 int len, fd, ret = -1;
114
115 netns_nsid_socket_init();
116
117 fd = netns_get_fd(name);
118 if (fd < 0)
119 return fd;
120
121 addattr32(&req.n, 1024, NETNSA_FD, fd);
122 if (rtnl_talk(&rtnsh, &req.n, &answer) < 0) {
123 close(fd);
124 return -2;
125 }
126 close(fd);
127
128 /* Validate message and parse attributes */
129 if (answer->nlmsg_type == NLMSG_ERROR)
130 goto out;
131
132 rthdr = NLMSG_DATA(answer);
133 len = answer->nlmsg_len - NLMSG_SPACE(sizeof(*rthdr));
134 if (len < 0)
135 goto out;
136
137 parse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len);
138
139 if (tb[NETNSA_NSID]) {
140 ret = rta_getattr_s32(tb[NETNSA_NSID]);
141 }
142
143 out:
144 free(answer);
145 return ret;
146 }
147
148 struct nsid_cache {
149 struct hlist_node nsid_hash;
150 struct hlist_node name_hash;
151 int nsid;
152 char name[0];
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
159 static struct hlist_head nsid_head[NSIDMAP_SIZE];
160 static struct hlist_head name_head[NSIDMAP_SIZE];
161
162 static struct nsid_cache *netns_map_get_by_nsid(int nsid)
163 {
164 struct hlist_node *n;
165 uint32_t h;
166
167 if (nsid < 0)
168 return NULL;
169
170 h = NSID_HASH_NSID(nsid);
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
181 char *get_name_from_nsid(int nsid)
182 {
183 struct nsid_cache *c;
184
185 if (nsid < 0)
186 return NULL;
187
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
198 static int netns_map_add(int nsid, const char *name)
199 {
200 struct nsid_cache *c;
201 uint32_t h;
202
203 if (netns_map_get_by_nsid(nsid) != NULL)
204 return -EEXIST;
205
206 c = malloc(sizeof(*c) + strlen(name) + 1);
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
223 static 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
230 void 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
242 void 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
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
270 static int netns_get_name(int nsid, char *name)
271 {
272 struct dirent *entry;
273 DIR *dir;
274 int id;
275
276 if (nsid < 0)
277 return -EINVAL;
278
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
290 if (id >= 0 && nsid == id) {
291 strcpy(name, entry->d_name);
292 closedir(dir);
293 return 0;
294 }
295 }
296 closedir(dir);
297 return -ENOENT;
298 }
299
300 int print_nsid(struct nlmsghdr *n, void *arg)
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];
308 int nsid, current;
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
326 open_json_object(NULL);
327 if (n->nlmsg_type == RTM_DELNSID)
328 print_bool(PRINT_ANY, "deleted", "Deleted ", true);
329
330 nsid = rta_getattr_s32(tb[NETNSA_NSID]);
331 if (nsid < 0)
332 print_string(PRINT_FP, NULL, "nsid unassigned ", NULL);
333 else
334 print_int(PRINT_ANY, "nsid", "nsid %d ", nsid);
335
336 if (tb[NETNSA_CURRENT_NSID]) {
337 current = rta_getattr_s32(tb[NETNSA_CURRENT_NSID]);
338 if (current < 0)
339 print_string(PRINT_FP, NULL,
340 "current-nsid unassigned ", NULL);
341 else
342 print_int(PRINT_ANY, "current-nsid",
343 "current-nsid %d ", current);
344 }
345
346 c = netns_map_get_by_nsid(tb[NETNSA_CURRENT_NSID] ? current : nsid);
347 if (c != NULL) {
348 print_string(PRINT_ANY, "name",
349 "(iproute2 netns name: %s)", c->name);
350 netns_map_del(c);
351 }
352
353 /* nsid might not be in cache */
354 if (c == NULL && n->nlmsg_type == RTM_NEWNSID)
355 if (netns_get_name(nsid, name) == 0) {
356 print_string(PRINT_ANY, "name",
357 "(iproute2 netns name: %s)", name);
358 netns_map_add(nsid, name);
359 }
360
361 print_string(PRINT_FP, NULL, "\n", NULL);
362 close_json_object();
363 fflush(fp);
364 return 0;
365 }
366
367 static 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();
405 err_out:
406 free(answer);
407 return err;
408 }
409
410 static 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
424 static int netns_list_id(int argc, char **argv)
425 {
426 int nsid = -1;
427
428 if (!ipnetns_have_nsid()) {
429 fprintf(stderr,
430 "RTM_GETNSID is not supported by the kernel.\n");
431 return -ENOTSUP;
432 }
433
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))
442 invarg("\"target-nsid\" value is invalid",
443 *argv);
444 else if (filter.target_nsid < 0)
445 invarg("\"target-nsid\" value should be >= 0",
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))
453 invarg("\"nsid\" value is invalid", *argv);
454 else if (nsid < 0)
455 invarg("\"nsid\" value should be >= 0",
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) {
467 perror("Cannot send dump request");
468 exit(1);
469 }
470
471 new_json_obj(json);
472 if (rtnl_dump_filter(&rth, print_nsid, stdout) < 0) {
473 delete_json_obj();
474 fprintf(stderr, "Dump terminated\n");
475 exit(1);
476 }
477 delete_json_obj();
478 return 0;
479 }
480
481 static int netns_list(int argc, char **argv)
482 {
483 struct dirent *entry;
484 DIR *dir;
485 int id;
486
487 dir = opendir(NETNS_RUN_DIR);
488 if (!dir)
489 return 0;
490
491 new_json_obj(json);
492 while ((entry = readdir(dir)) != NULL) {
493 if (strcmp(entry->d_name, ".") == 0)
494 continue;
495 if (strcmp(entry->d_name, "..") == 0)
496 continue;
497
498 open_json_object(NULL);
499 print_string(PRINT_ANY, "name",
500 "%s", entry->d_name);
501 if (ipnetns_have_nsid()) {
502 id = get_netnsid_from_name(entry->d_name);
503 if (id >= 0)
504 print_int(PRINT_ANY, "id", " (id: %d)", id);
505 }
506 print_string(PRINT_FP, NULL, "\n", NULL);
507 close_json_object();
508 }
509 closedir(dir);
510 delete_json_obj();
511 return 0;
512 }
513
514 static 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
526 static int on_netns_exec(char *nsname, void *arg)
527 {
528 char **argv = arg;
529
530 printf("\nnetns: %s\n", nsname);
531 cmd_exec(argv[0], argv, true, do_switch, nsname);
532 return 0;
533 }
534
535 static 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 */
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)
550 return netns_foreach(on_netns_exec, argv);
551
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 */
556 return -cmd_exec(argv[1], argv + 1, !!batch_mode, do_switch, argv[0]);
557 }
558
559 static int is_pid(const char *str)
560 {
561 int ch;
562
563 for (; (ch = *str); str++) {
564 if (!isdigit(ch))
565 return 0;
566 }
567 return 1;
568 }
569
570 static int netns_pids(int argc, char **argv)
571 {
572 const char *name;
573 char net_path[PATH_MAX];
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");
581 return -1;
582 }
583 if (argc > 1) {
584 fprintf(stderr, "extra arguments specified\n");
585 return -1;
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));
594 return -1;
595 }
596 if (fstat(netns, &netst) < 0) {
597 fprintf(stderr, "Stat of netns failed: %s\n",
598 strerror(errno));
599 return -1;
600 }
601 dir = opendir("/proc/");
602 if (!dir) {
603 fprintf(stderr, "Open of /proc failed: %s\n",
604 strerror(errno));
605 return -1;
606 }
607 while ((entry = readdir(dir))) {
608 char pid_net_path[PATH_MAX];
609 struct stat st;
610
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);
623 return 0;
624
625 }
626
627 int netns_identify_pid(const char *pidstr, char *name, int len)
628 {
629 char net_path[PATH_MAX];
630 int netns;
631 struct stat netst;
632 DIR *dir;
633 struct dirent *entry;
634
635 name[0] = '\0';
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));
642 return -1;
643 }
644 if (fstat(netns, &netst) < 0) {
645 fprintf(stderr, "Stat of netns failed: %s\n",
646 strerror(errno));
647 return -1;
648 }
649 dir = opendir(NETNS_RUN_DIR);
650 if (!dir) {
651 /* Succeed treat a missing directory as an empty directory */
652 if (errno == ENOENT)
653 return 0;
654
655 fprintf(stderr, "Failed to open directory %s:%s\n",
656 NETNS_RUN_DIR, strerror(errno));
657 return -1;
658 }
659
660 while ((entry = readdir(dir))) {
661 char name_path[PATH_MAX];
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)) {
677 strlcpy(name, entry->d_name, len);
678 }
679 }
680 closedir(dir);
681 return 0;
682
683 }
684
685 static 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
712 static int on_netns_del(char *nsname, void *arg)
713 {
714 char netns_path[PATH_MAX];
715
716 snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, nsname);
717 umount2(netns_path, MNT_DETACH);
718 if (unlink(netns_path) < 0) {
719 fprintf(stderr, "Cannot remove namespace file \"%s\": %s\n",
720 netns_path, strerror(errno));
721 return -1;
722 }
723 return 0;
724 }
725
726 static 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
739 static 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
753 /* Obtain a FD for the current namespace, so we can reenter it later */
754 static 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
766 static 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
780 static int netns_add(int argc, char **argv, bool create)
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 *
786 * If create is true, a new namespace will be created,
787 * otherwise an existing one will be attached to the file.
788 *
789 * The mount namespace is created so that any necessary
790 * userspace tweaks like remounting /sys, or bind mounting
791 * a new /etc/resolv.conf can be shared between users.
792 */
793 char netns_path[PATH_MAX], proc_path[PATH_MAX];
794 const char *name;
795 pid_t pid;
796 int fd;
797 int made_netns_run_dir_mount = 0;
798
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 }
814 }
815 name = argv[0];
816
817 snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, name);
818
819 if (create_netns_dir())
820 return -1;
821
822 /* Make it possible for network namespace mounts to propagate between
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));
833 return -1;
834 }
835
836 /* Upgrade NETNS_RUN_DIR to a mount point */
837 if (mount(NETNS_RUN_DIR, NETNS_RUN_DIR, "none", MS_BIND | MS_REC, NULL)) {
838 fprintf(stderr, "mount --bind %s %s failed: %s\n",
839 NETNS_RUN_DIR, NETNS_RUN_DIR, strerror(errno));
840 return -1;
841 }
842 made_netns_run_dir_mount = 1;
843 }
844
845 /* Create the filesystem state */
846 fd = open(netns_path, O_RDONLY|O_CREAT|O_EXCL, 0);
847 if (fd < 0) {
848 fprintf(stderr, "Cannot create namespace file \"%s\": %s\n",
849 netns_path, strerror(errno));
850 return -1;
851 }
852 close(fd);
853
854 if (create) {
855 netns_save();
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);
865 }
866
867 /* Bind the netns last so I can watch for it */
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));
871 goto out_delete;
872 }
873 netns_restore();
874
875 return 0;
876 out_delete:
877 if (create) {
878 netns_restore();
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 }
884 return -1;
885 }
886
887 int set_netnsid_from_name(const char *name, int nsid)
888 {
889 struct {
890 struct nlmsghdr n;
891 struct rtgenmsg g;
892 char buf[1024];
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 };
899 int fd, err = 0;
900
901 netns_nsid_socket_init();
902
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);
909 if (rtnl_talk(&rth, &req.n, NULL) < 0)
910 err = -2;
911
912 close(fd);
913 return err;
914 }
915
916 static int netns_set(int argc, char **argv)
917 {
918 char netns_path[PATH_MAX];
919 const char *name;
920 int netns, nsid;
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];
931 /* If a negative nsid is specified the kernel will select the nsid. */
932 if (strcmp(argv[1], "auto") == 0)
933 nsid = -1;
934 else if (get_integer(&nsid, argv[1], 0))
935 invarg("Invalid \"netnsid\" value", argv[1]);
936 else if (nsid < 0)
937 invarg("\"netnsid\" value should be >= 0", argv[1]);
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 }
949
950 static int netns_monitor(int argc, char **argv)
951 {
952 char buf[4096];
953 struct inotify_event *event;
954 int fd;
955
956 fd = inotify_init();
957 if (fd < 0) {
958 fprintf(stderr, "inotify_init failed: %s\n",
959 strerror(errno));
960 return -1;
961 }
962
963 if (create_netns_dir())
964 return -1;
965
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));
969 return -1;
970 }
971 for (;;) {
972 ssize_t len = read(fd, buf, sizeof(buf));
973
974 if (len < 0) {
975 fprintf(stderr, "read failed: %s\n",
976 strerror(errno));
977 return -1;
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 }
988 return 0;
989 }
990
991 static int invalid_name(const char *name)
992 {
993 return !*name || strlen(name) > NAME_MAX ||
994 strchr(name, '/') || !strcmp(name, ".") || !strcmp(name, "..");
995 }
996
997 int do_netns(int argc, char **argv)
998 {
999 netns_nsid_socket_init();
1000
1001 if (argc < 1) {
1002 netns_map_init();
1003 return netns_list(0, NULL);
1004 }
1005
1006 if (!do_all && argc > 1 && invalid_name(argv[1])) {
1007 fprintf(stderr, "Invalid netns name \"%s\"\n", argv[1]);
1008 exit(-1);
1009 }
1010
1011 if ((matches(*argv, "list") == 0) || (matches(*argv, "show") == 0) ||
1012 (matches(*argv, "lst") == 0)) {
1013 netns_map_init();
1014 return netns_list(argc-1, argv+1);
1015 }
1016
1017 if ((matches(*argv, "list-id") == 0)) {
1018 netns_map_init();
1019 return netns_list_id(argc-1, argv+1);
1020 }
1021
1022 if (matches(*argv, "help") == 0)
1023 return usage();
1024
1025 if (matches(*argv, "add") == 0)
1026 return netns_add(argc-1, argv+1, true);
1027
1028 if (matches(*argv, "set") == 0)
1029 return netns_set(argc-1, argv+1);
1030
1031 if (matches(*argv, "delete") == 0)
1032 return netns_delete(argc-1, argv+1);
1033
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
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
1046 if (matches(*argv, "attach") == 0)
1047 return netns_add(argc-1, argv+1, false);
1048
1049 fprintf(stderr, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv);
1050 exit(-1);
1051 }