]>
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(const struct sockaddr_nl
*who
,
47 struct rtnl_ctrl_data
*ctrl
,
48 struct nlmsghdr
*n
, void *arg
)
50 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(n
);
52 if (n
->nlmsg_type
== NLMSG_ERROR
&&
53 (err
->error
== -EOPNOTSUPP
|| err
->error
== -EINVAL
))
54 have_rtnl_getnsid
= 0;
56 have_rtnl_getnsid
= 1;
60 static int ipnetns_have_nsid(void)
67 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
68 .n
.nlmsg_flags
= NLM_F_REQUEST
,
69 .n
.nlmsg_type
= RTM_GETNSID
,
70 .g
.rtgen_family
= AF_UNSPEC
,
74 if (have_rtnl_getnsid
< 0) {
75 fd
= open("/proc/self/ns/net", O_RDONLY
);
77 have_rtnl_getnsid
= 0;
81 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
83 if (rtnl_send(&rth
, &req
.n
, req
.n
.nlmsg_len
) < 0) {
84 perror("request send failed");
87 rtnl_listen(&rth
, ipnetns_accept_msg
, NULL
);
91 return have_rtnl_getnsid
;
94 static int get_netnsid_from_name(const char *name
)
101 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
102 .n
.nlmsg_flags
= NLM_F_REQUEST
,
103 .n
.nlmsg_type
= RTM_GETNSID
,
104 .g
.rtgen_family
= AF_UNSPEC
,
106 struct nlmsghdr
*answer
;
107 struct rtattr
*tb
[NETNSA_MAX
+ 1];
108 struct rtgenmsg
*rthdr
;
111 fd
= netns_get_fd(name
);
115 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
116 if (rtnl_talk(&rtnsh
, &req
.n
, &answer
) < 0) {
122 /* Validate message and parse attributes */
123 if (answer
->nlmsg_type
== NLMSG_ERROR
)
126 rthdr
= NLMSG_DATA(answer
);
127 len
= answer
->nlmsg_len
- NLMSG_SPACE(sizeof(*rthdr
));
131 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
133 if (tb
[NETNSA_NSID
]) {
135 return rta_getattr_u32(tb
[NETNSA_NSID
]);
144 struct hlist_node nsid_hash
;
145 struct hlist_node name_hash
;
150 #define NSIDMAP_SIZE 128
151 #define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
152 #define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
154 static struct hlist_head nsid_head
[NSIDMAP_SIZE
];
155 static struct hlist_head name_head
[NSIDMAP_SIZE
];
157 static struct nsid_cache
*netns_map_get_by_nsid(int nsid
)
159 uint32_t h
= NSID_HASH_NSID(nsid
);
160 struct hlist_node
*n
;
162 hlist_for_each(n
, &nsid_head
[h
]) {
163 struct nsid_cache
*c
= container_of(n
, struct nsid_cache
,
172 static int netns_map_add(int nsid
, const char *name
)
174 struct nsid_cache
*c
;
177 if (netns_map_get_by_nsid(nsid
) != NULL
)
180 c
= malloc(sizeof(*c
) + strlen(name
) + 1);
186 strcpy(c
->name
, name
);
188 h
= NSID_HASH_NSID(nsid
);
189 hlist_add_head(&c
->nsid_hash
, &nsid_head
[h
]);
191 h
= NSID_HASH_NAME(name
);
192 hlist_add_head(&c
->name_hash
, &name_head
[h
]);
197 static void netns_map_del(struct nsid_cache
*c
)
199 hlist_del(&c
->name_hash
);
200 hlist_del(&c
->nsid_hash
);
204 void netns_nsid_socket_init(void)
206 if (rtnsh
.fd
> -1 || !ipnetns_have_nsid())
209 if (rtnl_open(&rtnsh
, 0) < 0) {
210 fprintf(stderr
, "Cannot open rtnetlink\n");
216 void netns_map_init(void)
218 static int initialized
;
219 struct dirent
*entry
;
223 if (initialized
|| !ipnetns_have_nsid())
226 dir
= opendir(NETNS_RUN_DIR
);
230 while ((entry
= readdir(dir
)) != NULL
) {
231 if (strcmp(entry
->d_name
, ".") == 0)
233 if (strcmp(entry
->d_name
, "..") == 0)
235 nsid
= get_netnsid_from_name(entry
->d_name
);
238 netns_map_add(nsid
, entry
->d_name
);
244 static int netns_get_name(int nsid
, char *name
)
246 struct dirent
*entry
;
250 dir
= opendir(NETNS_RUN_DIR
);
254 while ((entry
= readdir(dir
)) != NULL
) {
255 if (strcmp(entry
->d_name
, ".") == 0)
257 if (strcmp(entry
->d_name
, "..") == 0)
259 id
= get_netnsid_from_name(entry
->d_name
);
262 strcpy(name
, entry
->d_name
);
271 int print_nsid(const struct sockaddr_nl
*who
, struct nlmsghdr
*n
, void *arg
)
273 struct rtgenmsg
*rthdr
= NLMSG_DATA(n
);
274 struct rtattr
*tb
[NETNSA_MAX
+1];
275 int len
= n
->nlmsg_len
;
276 FILE *fp
= (FILE *)arg
;
277 struct nsid_cache
*c
;
281 if (n
->nlmsg_type
!= RTM_NEWNSID
&& n
->nlmsg_type
!= RTM_DELNSID
)
284 len
-= NLMSG_SPACE(sizeof(*rthdr
));
286 fprintf(stderr
, "BUG: wrong nlmsg len %d in %s\n", len
,
291 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
292 if (tb
[NETNSA_NSID
] == NULL
) {
293 fprintf(stderr
, "BUG: NETNSA_NSID is missing %s\n", __func__
);
297 open_json_object(NULL
);
298 if (n
->nlmsg_type
== RTM_DELNSID
)
299 print_bool(PRINT_ANY
, "deleted", "Deleted ", true);
301 nsid
= rta_getattr_u32(tb
[NETNSA_NSID
]);
302 print_uint(PRINT_ANY
, "nsid", "nsid %u ", nsid
);
304 c
= netns_map_get_by_nsid(nsid
);
306 print_string(PRINT_ANY
, "name",
307 "(iproute2 netns name: %s)", c
->name
);
311 /* During 'ip monitor nsid', no chance to have new nsid in cache. */
312 if (c
== NULL
&& n
->nlmsg_type
== RTM_NEWNSID
)
313 if (netns_get_name(nsid
, name
) == 0) {
314 print_string(PRINT_ANY
, "name",
315 "(iproute2 netns name: %s)", name
);
316 netns_map_add(nsid
, name
);
319 print_string(PRINT_FP
, NULL
, "\n", NULL
);
325 static int netns_list_id(int argc
, char **argv
)
327 if (!ipnetns_have_nsid()) {
329 "RTM_GETNSID is not supported by the kernel.\n");
333 if (rtnl_wilddump_request(&rth
, AF_UNSPEC
, RTM_GETNSID
) < 0) {
334 perror("Cannot send dump request");
339 if (rtnl_dump_filter(&rth
, print_nsid
, stdout
) < 0) {
341 fprintf(stderr
, "Dump terminated\n");
348 static int netns_list(int argc
, char **argv
)
350 struct dirent
*entry
;
354 dir
= opendir(NETNS_RUN_DIR
);
359 while ((entry
= readdir(dir
)) != NULL
) {
360 if (strcmp(entry
->d_name
, ".") == 0)
362 if (strcmp(entry
->d_name
, "..") == 0)
365 open_json_object(NULL
);
366 print_string(PRINT_ANY
, "name",
367 "%s", entry
->d_name
);
368 if (ipnetns_have_nsid()) {
369 id
= get_netnsid_from_name(entry
->d_name
);
371 print_uint(PRINT_ANY
, "id",
374 print_string(PRINT_FP
, NULL
, "\n", NULL
);
382 static int on_netns_exec(char *nsname
, void *arg
)
386 cmd_exec(argv
[1], argv
+ 1, true);
390 static int netns_exec(int argc
, char **argv
)
392 /* Setup the proper environment for apps that are not netns
393 * aware, and execute a program in that environment.
397 if (argc
< 1 && !do_all
) {
398 fprintf(stderr
, "No netns name specified\n");
401 if ((argc
< 2 && !do_all
) || (argc
< 1 && do_all
)) {
402 fprintf(stderr
, "No command specified\n");
407 return do_each_netns(on_netns_exec
, --argv
, 1);
409 if (netns_switch(argv
[0]))
412 /* we just changed namespaces. clear any vrf association
413 * with prior namespace before exec'ing command
417 /* ip must return the status of the child,
418 * but do_cmd() will add a minus to this,
419 * so let's add another one here to cancel it.
422 return -cmd_exec(cmd
, argv
+ 1, !!batch_mode
);
425 static int is_pid(const char *str
)
429 for (; (ch
= *str
); str
++) {
436 static int netns_pids(int argc
, char **argv
)
439 char net_path
[PATH_MAX
];
443 struct dirent
*entry
;
446 fprintf(stderr
, "No netns name specified\n");
450 fprintf(stderr
, "extra arguments specified\n");
455 snprintf(net_path
, sizeof(net_path
), "%s/%s", NETNS_RUN_DIR
, name
);
456 netns
= open(net_path
, O_RDONLY
);
458 fprintf(stderr
, "Cannot open network namespace: %s\n",
462 if (fstat(netns
, &netst
) < 0) {
463 fprintf(stderr
, "Stat of netns failed: %s\n",
467 dir
= opendir("/proc/");
469 fprintf(stderr
, "Open of /proc failed: %s\n",
473 while ((entry
= readdir(dir
))) {
474 char pid_net_path
[PATH_MAX
];
477 if (!is_pid(entry
->d_name
))
479 snprintf(pid_net_path
, sizeof(pid_net_path
), "/proc/%s/ns/net",
481 if (stat(pid_net_path
, &st
) != 0)
483 if ((st
.st_dev
== netst
.st_dev
) &&
484 (st
.st_ino
== netst
.st_ino
)) {
485 printf("%s\n", entry
->d_name
);
493 int netns_identify_pid(const char *pidstr
, char *name
, int len
)
495 char net_path
[PATH_MAX
];
499 struct dirent
*entry
;
503 snprintf(net_path
, sizeof(net_path
), "/proc/%s/ns/net", pidstr
);
504 netns
= open(net_path
, O_RDONLY
);
506 fprintf(stderr
, "Cannot open network namespace: %s\n",
510 if (fstat(netns
, &netst
) < 0) {
511 fprintf(stderr
, "Stat of netns failed: %s\n",
515 dir
= opendir(NETNS_RUN_DIR
);
517 /* Succeed treat a missing directory as an empty directory */
521 fprintf(stderr
, "Failed to open directory %s:%s\n",
522 NETNS_RUN_DIR
, strerror(errno
));
526 while ((entry
= readdir(dir
))) {
527 char name_path
[PATH_MAX
];
530 if (strcmp(entry
->d_name
, ".") == 0)
532 if (strcmp(entry
->d_name
, "..") == 0)
535 snprintf(name_path
, sizeof(name_path
), "%s/%s", NETNS_RUN_DIR
,
538 if (stat(name_path
, &st
) != 0)
541 if ((st
.st_dev
== netst
.st_dev
) &&
542 (st
.st_ino
== netst
.st_ino
)) {
543 strlcpy(name
, entry
->d_name
, len
);
551 static int netns_identify(int argc
, char **argv
)
559 } else if (argc
> 1) {
560 fprintf(stderr
, "extra arguments specified\n");
564 if (!is_pid(pidstr
)) {
565 fprintf(stderr
, "Specified string '%s' is not a pid\n",
571 rc
= netns_identify_pid(pidstr
, name
, sizeof(name
));
573 printf("%s\n", name
);
578 static int on_netns_del(char *nsname
, void *arg
)
580 char netns_path
[PATH_MAX
];
582 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, nsname
);
583 umount2(netns_path
, MNT_DETACH
);
584 if (unlink(netns_path
) < 0) {
585 fprintf(stderr
, "Cannot remove namespace file \"%s\": %s\n",
586 netns_path
, strerror(errno
));
592 static int netns_delete(int argc
, char **argv
)
594 if (argc
< 1 && !do_all
) {
595 fprintf(stderr
, "No netns name specified\n");
600 return netns_foreach(on_netns_del
, NULL
);
602 return on_netns_del(argv
[0], NULL
);
605 static int create_netns_dir(void)
607 /* Create the base netns directory if it doesn't exist */
608 if (mkdir(NETNS_RUN_DIR
, S_IRWXU
|S_IRGRP
|S_IXGRP
|S_IROTH
|S_IXOTH
)) {
609 if (errno
!= EEXIST
) {
610 fprintf(stderr
, "mkdir %s failed: %s\n",
611 NETNS_RUN_DIR
, strerror(errno
));
619 static int netns_add(int argc
, char **argv
)
621 /* This function creates a new network namespace and
622 * a new mount namespace and bind them into a well known
623 * location in the filesystem based on the name provided.
625 * The mount namespace is created so that any necessary
626 * userspace tweaks like remounting /sys, or bind mounting
627 * a new /etc/resolv.conf can be shared between uers.
629 char netns_path
[PATH_MAX
];
632 int made_netns_run_dir_mount
= 0;
635 fprintf(stderr
, "No netns name specified\n");
640 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
642 if (create_netns_dir())
645 /* Make it possible for network namespace mounts to propagate between
646 * mount namespaces. This makes it likely that a unmounting a network
647 * namespace file in one namespace will unmount the network namespace
648 * file in all namespaces allowing the network namespace to be freed
651 while (mount("", NETNS_RUN_DIR
, "none", MS_SHARED
| MS_REC
, NULL
)) {
652 /* Fail unless we need to make the mount point */
653 if (errno
!= EINVAL
|| made_netns_run_dir_mount
) {
654 fprintf(stderr
, "mount --make-shared %s failed: %s\n",
655 NETNS_RUN_DIR
, strerror(errno
));
659 /* Upgrade NETNS_RUN_DIR to a mount point */
660 if (mount(NETNS_RUN_DIR
, NETNS_RUN_DIR
, "none", MS_BIND
| MS_REC
, NULL
)) {
661 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
662 NETNS_RUN_DIR
, NETNS_RUN_DIR
, strerror(errno
));
665 made_netns_run_dir_mount
= 1;
668 /* Create the filesystem state */
669 fd
= open(netns_path
, O_RDONLY
|O_CREAT
|O_EXCL
, 0);
671 fprintf(stderr
, "Cannot create namespace file \"%s\": %s\n",
672 netns_path
, strerror(errno
));
676 if (unshare(CLONE_NEWNET
) < 0) {
677 fprintf(stderr
, "Failed to create a new network namespace \"%s\": %s\n",
678 name
, strerror(errno
));
682 /* Bind the netns last so I can watch for it */
683 if (mount("/proc/self/ns/net", netns_path
, "none", MS_BIND
, NULL
) < 0) {
684 fprintf(stderr
, "Bind /proc/self/ns/net -> %s failed: %s\n",
685 netns_path
, strerror(errno
));
690 netns_delete(argc
, argv
);
694 static int set_netnsid_from_name(const char *name
, int nsid
)
701 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
702 .n
.nlmsg_flags
= NLM_F_REQUEST
,
703 .n
.nlmsg_type
= RTM_NEWNSID
,
704 .g
.rtgen_family
= AF_UNSPEC
,
708 fd
= netns_get_fd(name
);
712 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
713 addattr32(&req
.n
, 1024, NETNSA_NSID
, nsid
);
714 if (rtnl_talk(&rth
, &req
.n
, NULL
) < 0)
721 static int netns_set(int argc
, char **argv
)
723 char netns_path
[PATH_MAX
];
729 fprintf(stderr
, "No netns name specified\n");
733 fprintf(stderr
, "No nsid specified\n");
737 /* If a negative nsid is specified the kernel will select the nsid. */
738 if (strcmp(argv
[1], "auto") == 0)
740 else if (get_unsigned(&nsid
, argv
[1], 0))
741 invarg("Invalid \"netnsid\" value\n", argv
[1]);
743 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
744 netns
= open(netns_path
, O_RDONLY
| O_CLOEXEC
);
746 fprintf(stderr
, "Cannot open network namespace \"%s\": %s\n",
747 name
, strerror(errno
));
751 return set_netnsid_from_name(name
, nsid
);
754 static int netns_monitor(int argc
, char **argv
)
757 struct inotify_event
*event
;
762 fprintf(stderr
, "inotify_init failed: %s\n",
767 if (create_netns_dir())
770 if (inotify_add_watch(fd
, NETNS_RUN_DIR
, IN_CREATE
| IN_DELETE
) < 0) {
771 fprintf(stderr
, "inotify_add_watch failed: %s\n",
776 ssize_t len
= read(fd
, buf
, sizeof(buf
));
779 fprintf(stderr
, "read failed: %s\n",
783 for (event
= (struct inotify_event
*)buf
;
784 (char *)event
< &buf
[len
];
785 event
= (struct inotify_event
*)((char *)event
+ sizeof(*event
) + event
->len
)) {
786 if (event
->mask
& IN_CREATE
)
787 printf("add %s\n", event
->name
);
788 if (event
->mask
& IN_DELETE
)
789 printf("delete %s\n", event
->name
);
795 static int invalid_name(const char *name
)
797 return !*name
|| strlen(name
) > NAME_MAX
||
798 strchr(name
, '/') || !strcmp(name
, ".") || !strcmp(name
, "..");
801 int do_netns(int argc
, char **argv
)
803 netns_nsid_socket_init();
807 return netns_list(0, NULL
);
810 if (argc
> 1 && invalid_name(argv
[1])) {
811 fprintf(stderr
, "Invalid netns name \"%s\"\n", argv
[1]);
815 if ((matches(*argv
, "list") == 0) || (matches(*argv
, "show") == 0) ||
816 (matches(*argv
, "lst") == 0)) {
818 return netns_list(argc
-1, argv
+1);
821 if ((matches(*argv
, "list-id") == 0)) {
823 return netns_list_id(argc
-1, argv
+1);
826 if (matches(*argv
, "help") == 0)
829 if (matches(*argv
, "add") == 0)
830 return netns_add(argc
-1, argv
+1);
832 if (matches(*argv
, "set") == 0)
833 return netns_set(argc
-1, argv
+1);
835 if (matches(*argv
, "delete") == 0)
836 return netns_delete(argc
-1, argv
+1);
838 if (matches(*argv
, "identify") == 0)
839 return netns_identify(argc
-1, argv
+1);
841 if (matches(*argv
, "pids") == 0)
842 return netns_pids(argc
-1, argv
+1);
844 if (matches(*argv
, "exec") == 0)
845 return netns_exec(argc
-1, argv
+1);
847 if (matches(*argv
, "monitor") == 0)
848 return netns_monitor(argc
-1, argv
+1);
850 fprintf(stderr
, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv
);