]>
git.proxmox.com Git - mirror_iproute2.git/blob - ip/ipnetns.c
1 /* SPDX-License-Identifier: GPL-2.0 */
6 #include <sys/inotify.h>
8 #include <sys/syscall.h>
17 #include <linux/limits.h>
19 #include <linux/net_namespace.h>
23 #include "ip_common.h"
24 #include "namespace.h"
25 #include "json_print.h"
27 static int usage(void)
29 fprintf(stderr
, "Usage: ip netns list\n");
30 fprintf(stderr
, " ip netns add NAME\n");
31 fprintf(stderr
, " ip netns set NAME NETNSID\n");
32 fprintf(stderr
, " ip [-all] netns delete [NAME]\n");
33 fprintf(stderr
, " ip netns identify [PID]\n");
34 fprintf(stderr
, " ip netns pids NAME\n");
35 fprintf(stderr
, " ip [-all] netns exec [NAME] cmd ...\n");
36 fprintf(stderr
, " ip netns monitor\n");
37 fprintf(stderr
, " ip netns list-id\n");
41 /* This socket is used to get nsid */
42 static struct rtnl_handle rtnsh
= { .fd
= -1 };
44 static int have_rtnl_getnsid
= -1;
46 static int ipnetns_accept_msg(struct rtnl_ctrl_data
*ctrl
,
47 struct nlmsghdr
*n
, void *arg
)
49 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(n
);
51 if (n
->nlmsg_type
== NLMSG_ERROR
&&
52 (err
->error
== -EOPNOTSUPP
|| err
->error
== -EINVAL
))
53 have_rtnl_getnsid
= 0;
55 have_rtnl_getnsid
= 1;
59 static int ipnetns_have_nsid(void)
66 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
67 .n
.nlmsg_flags
= NLM_F_REQUEST
,
68 .n
.nlmsg_type
= RTM_GETNSID
,
69 .g
.rtgen_family
= AF_UNSPEC
,
73 if (have_rtnl_getnsid
< 0) {
74 fd
= open("/proc/self/ns/net", O_RDONLY
);
76 have_rtnl_getnsid
= 0;
80 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
82 if (rtnl_send(&rth
, &req
.n
, req
.n
.nlmsg_len
) < 0) {
83 perror("request send failed");
86 rtnl_listen(&rth
, ipnetns_accept_msg
, NULL
);
90 return have_rtnl_getnsid
;
93 int get_netnsid_from_name(const char *name
)
100 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
101 .n
.nlmsg_flags
= NLM_F_REQUEST
,
102 .n
.nlmsg_type
= RTM_GETNSID
,
103 .g
.rtgen_family
= AF_UNSPEC
,
105 struct nlmsghdr
*answer
;
106 struct rtattr
*tb
[NETNSA_MAX
+ 1];
107 struct rtgenmsg
*rthdr
;
110 netns_nsid_socket_init();
112 fd
= netns_get_fd(name
);
116 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
117 if (rtnl_talk(&rtnsh
, &req
.n
, &answer
) < 0) {
123 /* Validate message and parse attributes */
124 if (answer
->nlmsg_type
== NLMSG_ERROR
)
127 rthdr
= NLMSG_DATA(answer
);
128 len
= answer
->nlmsg_len
- NLMSG_SPACE(sizeof(*rthdr
));
132 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
134 if (tb
[NETNSA_NSID
]) {
136 return rta_getattr_u32(tb
[NETNSA_NSID
]);
145 struct hlist_node nsid_hash
;
146 struct hlist_node name_hash
;
151 #define NSIDMAP_SIZE 128
152 #define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
153 #define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
155 static struct hlist_head nsid_head
[NSIDMAP_SIZE
];
156 static struct hlist_head name_head
[NSIDMAP_SIZE
];
158 static struct nsid_cache
*netns_map_get_by_nsid(int nsid
)
160 uint32_t h
= NSID_HASH_NSID(nsid
);
161 struct hlist_node
*n
;
163 hlist_for_each(n
, &nsid_head
[h
]) {
164 struct nsid_cache
*c
= container_of(n
, struct nsid_cache
,
173 char *get_name_from_nsid(int nsid
)
175 struct nsid_cache
*c
;
177 netns_nsid_socket_init();
180 c
= netns_map_get_by_nsid(nsid
);
187 static int netns_map_add(int nsid
, const char *name
)
189 struct nsid_cache
*c
;
192 if (netns_map_get_by_nsid(nsid
) != NULL
)
195 c
= malloc(sizeof(*c
) + strlen(name
) + 1);
201 strcpy(c
->name
, name
);
203 h
= NSID_HASH_NSID(nsid
);
204 hlist_add_head(&c
->nsid_hash
, &nsid_head
[h
]);
206 h
= NSID_HASH_NAME(name
);
207 hlist_add_head(&c
->name_hash
, &name_head
[h
]);
212 static void netns_map_del(struct nsid_cache
*c
)
214 hlist_del(&c
->name_hash
);
215 hlist_del(&c
->nsid_hash
);
219 void netns_nsid_socket_init(void)
221 if (rtnsh
.fd
> -1 || !ipnetns_have_nsid())
224 if (rtnl_open(&rtnsh
, 0) < 0) {
225 fprintf(stderr
, "Cannot open rtnetlink\n");
231 void netns_map_init(void)
233 static int initialized
;
234 struct dirent
*entry
;
238 if (initialized
|| !ipnetns_have_nsid())
241 dir
= opendir(NETNS_RUN_DIR
);
245 while ((entry
= readdir(dir
)) != NULL
) {
246 if (strcmp(entry
->d_name
, ".") == 0)
248 if (strcmp(entry
->d_name
, "..") == 0)
250 nsid
= get_netnsid_from_name(entry
->d_name
);
253 netns_map_add(nsid
, entry
->d_name
);
259 static int netns_get_name(int nsid
, char *name
)
261 struct dirent
*entry
;
265 dir
= opendir(NETNS_RUN_DIR
);
269 while ((entry
= readdir(dir
)) != NULL
) {
270 if (strcmp(entry
->d_name
, ".") == 0)
272 if (strcmp(entry
->d_name
, "..") == 0)
274 id
= get_netnsid_from_name(entry
->d_name
);
277 strcpy(name
, entry
->d_name
);
286 int print_nsid(struct nlmsghdr
*n
, void *arg
)
288 struct rtgenmsg
*rthdr
= NLMSG_DATA(n
);
289 struct rtattr
*tb
[NETNSA_MAX
+1];
290 int len
= n
->nlmsg_len
;
291 FILE *fp
= (FILE *)arg
;
292 struct nsid_cache
*c
;
296 if (n
->nlmsg_type
!= RTM_NEWNSID
&& n
->nlmsg_type
!= RTM_DELNSID
)
299 len
-= NLMSG_SPACE(sizeof(*rthdr
));
301 fprintf(stderr
, "BUG: wrong nlmsg len %d in %s\n", len
,
306 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
307 if (tb
[NETNSA_NSID
] == NULL
) {
308 fprintf(stderr
, "BUG: NETNSA_NSID is missing %s\n", __func__
);
312 open_json_object(NULL
);
313 if (n
->nlmsg_type
== RTM_DELNSID
)
314 print_bool(PRINT_ANY
, "deleted", "Deleted ", true);
316 nsid
= rta_getattr_u32(tb
[NETNSA_NSID
]);
317 print_uint(PRINT_ANY
, "nsid", "nsid %u ", nsid
);
319 c
= netns_map_get_by_nsid(nsid
);
321 print_string(PRINT_ANY
, "name",
322 "(iproute2 netns name: %s)", c
->name
);
326 /* During 'ip monitor nsid', no chance to have new nsid in cache. */
327 if (c
== NULL
&& n
->nlmsg_type
== RTM_NEWNSID
)
328 if (netns_get_name(nsid
, name
) == 0) {
329 print_string(PRINT_ANY
, "name",
330 "(iproute2 netns name: %s)", name
);
331 netns_map_add(nsid
, name
);
334 print_string(PRINT_FP
, NULL
, "\n", NULL
);
340 static int netns_list_id(int argc
, char **argv
)
342 if (!ipnetns_have_nsid()) {
344 "RTM_GETNSID is not supported by the kernel.\n");
348 if (rtnl_nsiddump_req(&rth
, AF_UNSPEC
) < 0) {
349 perror("Cannot send dump request");
354 if (rtnl_dump_filter(&rth
, print_nsid
, stdout
) < 0) {
356 fprintf(stderr
, "Dump terminated\n");
363 static int netns_list(int argc
, char **argv
)
365 struct dirent
*entry
;
369 dir
= opendir(NETNS_RUN_DIR
);
374 while ((entry
= readdir(dir
)) != NULL
) {
375 if (strcmp(entry
->d_name
, ".") == 0)
377 if (strcmp(entry
->d_name
, "..") == 0)
380 open_json_object(NULL
);
381 print_string(PRINT_ANY
, "name",
382 "%s", entry
->d_name
);
383 if (ipnetns_have_nsid()) {
384 id
= get_netnsid_from_name(entry
->d_name
);
386 print_uint(PRINT_ANY
, "id",
389 print_string(PRINT_FP
, NULL
, "\n", NULL
);
397 static int on_netns_exec(char *nsname
, void *arg
)
401 cmd_exec(argv
[1], argv
+ 1, true);
405 static int netns_exec(int argc
, char **argv
)
407 /* Setup the proper environment for apps that are not netns
408 * aware, and execute a program in that environment.
412 if (argc
< 1 && !do_all
) {
413 fprintf(stderr
, "No netns name specified\n");
416 if ((argc
< 2 && !do_all
) || (argc
< 1 && do_all
)) {
417 fprintf(stderr
, "No command specified\n");
422 return do_each_netns(on_netns_exec
, --argv
, 1);
424 if (netns_switch(argv
[0]))
427 /* we just changed namespaces. clear any vrf association
428 * with prior namespace before exec'ing command
432 /* ip must return the status of the child,
433 * but do_cmd() will add a minus to this,
434 * so let's add another one here to cancel it.
437 return -cmd_exec(cmd
, argv
+ 1, !!batch_mode
);
440 static int is_pid(const char *str
)
444 for (; (ch
= *str
); str
++) {
451 static int netns_pids(int argc
, char **argv
)
454 char net_path
[PATH_MAX
];
458 struct dirent
*entry
;
461 fprintf(stderr
, "No netns name specified\n");
465 fprintf(stderr
, "extra arguments specified\n");
470 snprintf(net_path
, sizeof(net_path
), "%s/%s", NETNS_RUN_DIR
, name
);
471 netns
= open(net_path
, O_RDONLY
);
473 fprintf(stderr
, "Cannot open network namespace: %s\n",
477 if (fstat(netns
, &netst
) < 0) {
478 fprintf(stderr
, "Stat of netns failed: %s\n",
482 dir
= opendir("/proc/");
484 fprintf(stderr
, "Open of /proc failed: %s\n",
488 while ((entry
= readdir(dir
))) {
489 char pid_net_path
[PATH_MAX
];
492 if (!is_pid(entry
->d_name
))
494 snprintf(pid_net_path
, sizeof(pid_net_path
), "/proc/%s/ns/net",
496 if (stat(pid_net_path
, &st
) != 0)
498 if ((st
.st_dev
== netst
.st_dev
) &&
499 (st
.st_ino
== netst
.st_ino
)) {
500 printf("%s\n", entry
->d_name
);
508 int netns_identify_pid(const char *pidstr
, char *name
, int len
)
510 char net_path
[PATH_MAX
];
514 struct dirent
*entry
;
518 snprintf(net_path
, sizeof(net_path
), "/proc/%s/ns/net", pidstr
);
519 netns
= open(net_path
, O_RDONLY
);
521 fprintf(stderr
, "Cannot open network namespace: %s\n",
525 if (fstat(netns
, &netst
) < 0) {
526 fprintf(stderr
, "Stat of netns failed: %s\n",
530 dir
= opendir(NETNS_RUN_DIR
);
532 /* Succeed treat a missing directory as an empty directory */
536 fprintf(stderr
, "Failed to open directory %s:%s\n",
537 NETNS_RUN_DIR
, strerror(errno
));
541 while ((entry
= readdir(dir
))) {
542 char name_path
[PATH_MAX
];
545 if (strcmp(entry
->d_name
, ".") == 0)
547 if (strcmp(entry
->d_name
, "..") == 0)
550 snprintf(name_path
, sizeof(name_path
), "%s/%s", NETNS_RUN_DIR
,
553 if (stat(name_path
, &st
) != 0)
556 if ((st
.st_dev
== netst
.st_dev
) &&
557 (st
.st_ino
== netst
.st_ino
)) {
558 strlcpy(name
, entry
->d_name
, len
);
566 static int netns_identify(int argc
, char **argv
)
574 } else if (argc
> 1) {
575 fprintf(stderr
, "extra arguments specified\n");
579 if (!is_pid(pidstr
)) {
580 fprintf(stderr
, "Specified string '%s' is not a pid\n",
586 rc
= netns_identify_pid(pidstr
, name
, sizeof(name
));
588 printf("%s\n", name
);
593 static int on_netns_del(char *nsname
, void *arg
)
595 char netns_path
[PATH_MAX
];
597 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, nsname
);
598 umount2(netns_path
, MNT_DETACH
);
599 if (unlink(netns_path
) < 0) {
600 fprintf(stderr
, "Cannot remove namespace file \"%s\": %s\n",
601 netns_path
, strerror(errno
));
607 static int netns_delete(int argc
, char **argv
)
609 if (argc
< 1 && !do_all
) {
610 fprintf(stderr
, "No netns name specified\n");
615 return netns_foreach(on_netns_del
, NULL
);
617 return on_netns_del(argv
[0], NULL
);
620 static int create_netns_dir(void)
622 /* Create the base netns directory if it doesn't exist */
623 if (mkdir(NETNS_RUN_DIR
, S_IRWXU
|S_IRGRP
|S_IXGRP
|S_IROTH
|S_IXOTH
)) {
624 if (errno
!= EEXIST
) {
625 fprintf(stderr
, "mkdir %s failed: %s\n",
626 NETNS_RUN_DIR
, strerror(errno
));
634 static int netns_add(int argc
, char **argv
)
636 /* This function creates a new network namespace and
637 * a new mount namespace and bind them into a well known
638 * location in the filesystem based on the name provided.
640 * The mount namespace is created so that any necessary
641 * userspace tweaks like remounting /sys, or bind mounting
642 * a new /etc/resolv.conf can be shared between uers.
644 char netns_path
[PATH_MAX
];
647 int made_netns_run_dir_mount
= 0;
650 fprintf(stderr
, "No netns name specified\n");
655 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
657 if (create_netns_dir())
660 /* Make it possible for network namespace mounts to propagate between
661 * mount namespaces. This makes it likely that a unmounting a network
662 * namespace file in one namespace will unmount the network namespace
663 * file in all namespaces allowing the network namespace to be freed
666 while (mount("", NETNS_RUN_DIR
, "none", MS_SHARED
| MS_REC
, NULL
)) {
667 /* Fail unless we need to make the mount point */
668 if (errno
!= EINVAL
|| made_netns_run_dir_mount
) {
669 fprintf(stderr
, "mount --make-shared %s failed: %s\n",
670 NETNS_RUN_DIR
, strerror(errno
));
674 /* Upgrade NETNS_RUN_DIR to a mount point */
675 if (mount(NETNS_RUN_DIR
, NETNS_RUN_DIR
, "none", MS_BIND
| MS_REC
, NULL
)) {
676 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
677 NETNS_RUN_DIR
, NETNS_RUN_DIR
, strerror(errno
));
680 made_netns_run_dir_mount
= 1;
683 /* Create the filesystem state */
684 fd
= open(netns_path
, O_RDONLY
|O_CREAT
|O_EXCL
, 0);
686 fprintf(stderr
, "Cannot create namespace file \"%s\": %s\n",
687 netns_path
, strerror(errno
));
691 if (unshare(CLONE_NEWNET
) < 0) {
692 fprintf(stderr
, "Failed to create a new network namespace \"%s\": %s\n",
693 name
, strerror(errno
));
697 /* Bind the netns last so I can watch for it */
698 if (mount("/proc/self/ns/net", netns_path
, "none", MS_BIND
, NULL
) < 0) {
699 fprintf(stderr
, "Bind /proc/self/ns/net -> %s failed: %s\n",
700 netns_path
, strerror(errno
));
705 netns_delete(argc
, argv
);
709 int set_netnsid_from_name(const char *name
, int nsid
)
716 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
717 .n
.nlmsg_flags
= NLM_F_REQUEST
,
718 .n
.nlmsg_type
= RTM_NEWNSID
,
719 .g
.rtgen_family
= AF_UNSPEC
,
723 netns_nsid_socket_init();
725 fd
= netns_get_fd(name
);
729 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
730 addattr32(&req
.n
, 1024, NETNSA_NSID
, nsid
);
731 if (rtnl_talk(&rth
, &req
.n
, NULL
) < 0)
738 static int netns_set(int argc
, char **argv
)
740 char netns_path
[PATH_MAX
];
746 fprintf(stderr
, "No netns name specified\n");
750 fprintf(stderr
, "No nsid specified\n");
754 /* If a negative nsid is specified the kernel will select the nsid. */
755 if (strcmp(argv
[1], "auto") == 0)
757 else if (get_unsigned(&nsid
, argv
[1], 0))
758 invarg("Invalid \"netnsid\" value\n", argv
[1]);
760 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
761 netns
= open(netns_path
, O_RDONLY
| O_CLOEXEC
);
763 fprintf(stderr
, "Cannot open network namespace \"%s\": %s\n",
764 name
, strerror(errno
));
768 return set_netnsid_from_name(name
, nsid
);
771 static int netns_monitor(int argc
, char **argv
)
774 struct inotify_event
*event
;
779 fprintf(stderr
, "inotify_init failed: %s\n",
784 if (create_netns_dir())
787 if (inotify_add_watch(fd
, NETNS_RUN_DIR
, IN_CREATE
| IN_DELETE
) < 0) {
788 fprintf(stderr
, "inotify_add_watch failed: %s\n",
793 ssize_t len
= read(fd
, buf
, sizeof(buf
));
796 fprintf(stderr
, "read failed: %s\n",
800 for (event
= (struct inotify_event
*)buf
;
801 (char *)event
< &buf
[len
];
802 event
= (struct inotify_event
*)((char *)event
+ sizeof(*event
) + event
->len
)) {
803 if (event
->mask
& IN_CREATE
)
804 printf("add %s\n", event
->name
);
805 if (event
->mask
& IN_DELETE
)
806 printf("delete %s\n", event
->name
);
812 static int invalid_name(const char *name
)
814 return !*name
|| strlen(name
) > NAME_MAX
||
815 strchr(name
, '/') || !strcmp(name
, ".") || !strcmp(name
, "..");
818 int do_netns(int argc
, char **argv
)
820 netns_nsid_socket_init();
824 return netns_list(0, NULL
);
827 if (argc
> 1 && invalid_name(argv
[1])) {
828 fprintf(stderr
, "Invalid netns name \"%s\"\n", argv
[1]);
832 if ((matches(*argv
, "list") == 0) || (matches(*argv
, "show") == 0) ||
833 (matches(*argv
, "lst") == 0)) {
835 return netns_list(argc
-1, argv
+1);
838 if ((matches(*argv
, "list-id") == 0)) {
840 return netns_list_id(argc
-1, argv
+1);
843 if (matches(*argv
, "help") == 0)
846 if (matches(*argv
, "add") == 0)
847 return netns_add(argc
-1, argv
+1);
849 if (matches(*argv
, "set") == 0)
850 return netns_set(argc
-1, argv
+1);
852 if (matches(*argv
, "delete") == 0)
853 return netns_delete(argc
-1, argv
+1);
855 if (matches(*argv
, "identify") == 0)
856 return netns_identify(argc
-1, argv
+1);
858 if (matches(*argv
, "pids") == 0)
859 return netns_pids(argc
-1, argv
+1);
861 if (matches(*argv
, "exec") == 0)
862 return netns_exec(argc
-1, argv
+1);
864 if (matches(*argv
, "monitor") == 0)
865 return netns_monitor(argc
-1, argv
+1);
867 fprintf(stderr
, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv
);