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