]>
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"
26 static int usage(void)
28 fprintf(stderr
, "Usage: ip netns list\n");
29 fprintf(stderr
, " ip netns add NAME\n");
30 fprintf(stderr
, " ip netns set NAME NETNSID\n");
31 fprintf(stderr
, " ip [-all] netns delete [NAME]\n");
32 fprintf(stderr
, " ip netns identify [PID]\n");
33 fprintf(stderr
, " ip netns pids NAME\n");
34 fprintf(stderr
, " ip [-all] netns exec [NAME] cmd ...\n");
35 fprintf(stderr
, " ip netns monitor\n");
36 fprintf(stderr
, " ip netns list-id\n");
40 /* This socket is used to get nsid */
41 static struct rtnl_handle rtnsh
= { .fd
= -1 };
43 static int have_rtnl_getnsid
= -1;
45 static int ipnetns_accept_msg(const struct sockaddr_nl
*who
,
46 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 static 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 fd
= netns_get_fd(name
);
114 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
115 if (rtnl_talk(&rtnsh
, &req
.n
, &answer
) < 0) {
121 /* Validate message and parse attributes */
122 if (answer
->nlmsg_type
== NLMSG_ERROR
)
125 rthdr
= NLMSG_DATA(answer
);
126 len
= answer
->nlmsg_len
- NLMSG_SPACE(sizeof(*rthdr
));
130 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
132 if (tb
[NETNSA_NSID
]) {
134 return rta_getattr_u32(tb
[NETNSA_NSID
]);
143 struct hlist_node nsid_hash
;
144 struct hlist_node name_hash
;
149 #define NSIDMAP_SIZE 128
150 #define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
151 #define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
153 static struct hlist_head nsid_head
[NSIDMAP_SIZE
];
154 static struct hlist_head name_head
[NSIDMAP_SIZE
];
156 static struct nsid_cache
*netns_map_get_by_nsid(int nsid
)
158 uint32_t h
= NSID_HASH_NSID(nsid
);
159 struct hlist_node
*n
;
161 hlist_for_each(n
, &nsid_head
[h
]) {
162 struct nsid_cache
*c
= container_of(n
, struct nsid_cache
,
171 static int netns_map_add(int nsid
, const char *name
)
173 struct nsid_cache
*c
;
176 if (netns_map_get_by_nsid(nsid
) != NULL
)
179 c
= malloc(sizeof(*c
) + strlen(name
) + 1);
185 strcpy(c
->name
, name
);
187 h
= NSID_HASH_NSID(nsid
);
188 hlist_add_head(&c
->nsid_hash
, &nsid_head
[h
]);
190 h
= NSID_HASH_NAME(name
);
191 hlist_add_head(&c
->name_hash
, &name_head
[h
]);
196 static void netns_map_del(struct nsid_cache
*c
)
198 hlist_del(&c
->name_hash
);
199 hlist_del(&c
->nsid_hash
);
203 void netns_nsid_socket_init(void)
205 if (rtnsh
.fd
> -1 || !ipnetns_have_nsid())
208 if (rtnl_open(&rtnsh
, 0) < 0) {
209 fprintf(stderr
, "Cannot open rtnetlink\n");
215 void netns_map_init(void)
217 static int initialized
;
218 struct dirent
*entry
;
222 if (initialized
|| !ipnetns_have_nsid())
225 dir
= opendir(NETNS_RUN_DIR
);
229 while ((entry
= readdir(dir
)) != NULL
) {
230 if (strcmp(entry
->d_name
, ".") == 0)
232 if (strcmp(entry
->d_name
, "..") == 0)
234 nsid
= get_netnsid_from_name(entry
->d_name
);
237 netns_map_add(nsid
, entry
->d_name
);
243 static int netns_get_name(int nsid
, char *name
)
245 struct dirent
*entry
;
249 dir
= opendir(NETNS_RUN_DIR
);
253 while ((entry
= readdir(dir
)) != NULL
) {
254 if (strcmp(entry
->d_name
, ".") == 0)
256 if (strcmp(entry
->d_name
, "..") == 0)
258 id
= get_netnsid_from_name(entry
->d_name
);
261 strcpy(name
, entry
->d_name
);
270 int print_nsid(const struct sockaddr_nl
*who
, struct nlmsghdr
*n
, void *arg
)
272 struct rtgenmsg
*rthdr
= NLMSG_DATA(n
);
273 struct rtattr
*tb
[NETNSA_MAX
+1];
274 int len
= n
->nlmsg_len
;
275 FILE *fp
= (FILE *)arg
;
276 struct nsid_cache
*c
;
280 if (n
->nlmsg_type
!= RTM_NEWNSID
&& n
->nlmsg_type
!= RTM_DELNSID
)
283 len
-= NLMSG_SPACE(sizeof(*rthdr
));
285 fprintf(stderr
, "BUG: wrong nlmsg len %d in %s\n", len
,
290 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
291 if (tb
[NETNSA_NSID
] == NULL
) {
292 fprintf(stderr
, "BUG: NETNSA_NSID is missing %s\n", __func__
);
296 if (n
->nlmsg_type
== RTM_DELNSID
)
297 fprintf(fp
, "Deleted ");
299 nsid
= rta_getattr_u32(tb
[NETNSA_NSID
]);
300 fprintf(fp
, "nsid %u ", nsid
);
302 c
= netns_map_get_by_nsid(nsid
);
304 fprintf(fp
, "(iproute2 netns name: %s)", c
->name
);
308 /* During 'ip monitor nsid', no chance to have new nsid in cache. */
309 if (c
== NULL
&& n
->nlmsg_type
== RTM_NEWNSID
)
310 if (netns_get_name(nsid
, name
) == 0) {
311 fprintf(fp
, "(iproute2 netns name: %s)", name
);
312 netns_map_add(nsid
, name
);
320 static int netns_list_id(int argc
, char **argv
)
322 if (!ipnetns_have_nsid()) {
324 "RTM_GETNSID is not supported by the kernel.\n");
328 if (rtnl_wilddump_request(&rth
, AF_UNSPEC
, RTM_GETNSID
) < 0) {
329 perror("Cannot send dump request");
332 if (rtnl_dump_filter(&rth
, print_nsid
, stdout
) < 0) {
333 fprintf(stderr
, "Dump terminated\n");
339 static int netns_list(int argc
, char **argv
)
341 struct dirent
*entry
;
345 dir
= opendir(NETNS_RUN_DIR
);
349 while ((entry
= readdir(dir
)) != NULL
) {
350 if (strcmp(entry
->d_name
, ".") == 0)
352 if (strcmp(entry
->d_name
, "..") == 0)
354 printf("%s", entry
->d_name
);
355 if (ipnetns_have_nsid()) {
356 id
= get_netnsid_from_name(entry
->d_name
);
358 printf(" (id: %d)", id
);
366 static int on_netns_exec(char *nsname
, void *arg
)
370 cmd_exec(argv
[1], argv
+ 1, true);
374 static int netns_exec(int argc
, char **argv
)
376 /* Setup the proper environment for apps that are not netns
377 * aware, and execute a program in that environment.
381 if (argc
< 1 && !do_all
) {
382 fprintf(stderr
, "No netns name specified\n");
385 if ((argc
< 2 && !do_all
) || (argc
< 1 && do_all
)) {
386 fprintf(stderr
, "No command specified\n");
391 return do_each_netns(on_netns_exec
, --argv
, 1);
393 if (netns_switch(argv
[0]))
396 /* we just changed namespaces. clear any vrf association
397 * with prior namespace before exec'ing command
401 /* ip must return the status of the child,
402 * but do_cmd() will add a minus to this,
403 * so let's add another one here to cancel it.
406 return -cmd_exec(cmd
, argv
+ 1, !!batch_mode
);
409 static int is_pid(const char *str
)
413 for (; (ch
= *str
); str
++) {
420 static int netns_pids(int argc
, char **argv
)
423 char net_path
[PATH_MAX
];
427 struct dirent
*entry
;
430 fprintf(stderr
, "No netns name specified\n");
434 fprintf(stderr
, "extra arguments specified\n");
439 snprintf(net_path
, sizeof(net_path
), "%s/%s", NETNS_RUN_DIR
, name
);
440 netns
= open(net_path
, O_RDONLY
);
442 fprintf(stderr
, "Cannot open network namespace: %s\n",
446 if (fstat(netns
, &netst
) < 0) {
447 fprintf(stderr
, "Stat of netns failed: %s\n",
451 dir
= opendir("/proc/");
453 fprintf(stderr
, "Open of /proc failed: %s\n",
457 while ((entry
= readdir(dir
))) {
458 char pid_net_path
[PATH_MAX
];
461 if (!is_pid(entry
->d_name
))
463 snprintf(pid_net_path
, sizeof(pid_net_path
), "/proc/%s/ns/net",
465 if (stat(pid_net_path
, &st
) != 0)
467 if ((st
.st_dev
== netst
.st_dev
) &&
468 (st
.st_ino
== netst
.st_ino
)) {
469 printf("%s\n", entry
->d_name
);
477 int netns_identify_pid(const char *pidstr
, char *name
, int len
)
479 char net_path
[PATH_MAX
];
483 struct dirent
*entry
;
487 snprintf(net_path
, sizeof(net_path
), "/proc/%s/ns/net", pidstr
);
488 netns
= open(net_path
, O_RDONLY
);
490 fprintf(stderr
, "Cannot open network namespace: %s\n",
494 if (fstat(netns
, &netst
) < 0) {
495 fprintf(stderr
, "Stat of netns failed: %s\n",
499 dir
= opendir(NETNS_RUN_DIR
);
501 /* Succeed treat a missing directory as an empty directory */
505 fprintf(stderr
, "Failed to open directory %s:%s\n",
506 NETNS_RUN_DIR
, strerror(errno
));
510 while ((entry
= readdir(dir
))) {
511 char name_path
[PATH_MAX
];
514 if (strcmp(entry
->d_name
, ".") == 0)
516 if (strcmp(entry
->d_name
, "..") == 0)
519 snprintf(name_path
, sizeof(name_path
), "%s/%s", NETNS_RUN_DIR
,
522 if (stat(name_path
, &st
) != 0)
525 if ((st
.st_dev
== netst
.st_dev
) &&
526 (st
.st_ino
== netst
.st_ino
)) {
527 strlcpy(name
, entry
->d_name
, len
);
535 static int netns_identify(int argc
, char **argv
)
543 } else if (argc
> 1) {
544 fprintf(stderr
, "extra arguments specified\n");
548 if (!is_pid(pidstr
)) {
549 fprintf(stderr
, "Specified string '%s' is not a pid\n",
555 rc
= netns_identify_pid(pidstr
, name
, sizeof(name
));
557 printf("%s\n", name
);
562 static int on_netns_del(char *nsname
, void *arg
)
564 char netns_path
[PATH_MAX
];
566 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, nsname
);
567 umount2(netns_path
, MNT_DETACH
);
568 if (unlink(netns_path
) < 0) {
569 fprintf(stderr
, "Cannot remove namespace file \"%s\": %s\n",
570 netns_path
, strerror(errno
));
576 static int netns_delete(int argc
, char **argv
)
578 if (argc
< 1 && !do_all
) {
579 fprintf(stderr
, "No netns name specified\n");
584 return netns_foreach(on_netns_del
, NULL
);
586 return on_netns_del(argv
[0], NULL
);
589 static int create_netns_dir(void)
591 /* Create the base netns directory if it doesn't exist */
592 if (mkdir(NETNS_RUN_DIR
, S_IRWXU
|S_IRGRP
|S_IXGRP
|S_IROTH
|S_IXOTH
)) {
593 if (errno
!= EEXIST
) {
594 fprintf(stderr
, "mkdir %s failed: %s\n",
595 NETNS_RUN_DIR
, strerror(errno
));
603 static int netns_add(int argc
, char **argv
)
605 /* This function creates a new network namespace and
606 * a new mount namespace and bind them into a well known
607 * location in the filesystem based on the name provided.
609 * The mount namespace is created so that any necessary
610 * userspace tweaks like remounting /sys, or bind mounting
611 * a new /etc/resolv.conf can be shared between uers.
613 char netns_path
[PATH_MAX
];
616 int made_netns_run_dir_mount
= 0;
619 fprintf(stderr
, "No netns name specified\n");
624 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
626 if (create_netns_dir())
629 /* Make it possible for network namespace mounts to propagate between
630 * mount namespaces. This makes it likely that a unmounting a network
631 * namespace file in one namespace will unmount the network namespace
632 * file in all namespaces allowing the network namespace to be freed
635 while (mount("", NETNS_RUN_DIR
, "none", MS_SHARED
| MS_REC
, NULL
)) {
636 /* Fail unless we need to make the mount point */
637 if (errno
!= EINVAL
|| made_netns_run_dir_mount
) {
638 fprintf(stderr
, "mount --make-shared %s failed: %s\n",
639 NETNS_RUN_DIR
, strerror(errno
));
643 /* Upgrade NETNS_RUN_DIR to a mount point */
644 if (mount(NETNS_RUN_DIR
, NETNS_RUN_DIR
, "none", MS_BIND
| MS_REC
, NULL
)) {
645 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
646 NETNS_RUN_DIR
, NETNS_RUN_DIR
, strerror(errno
));
649 made_netns_run_dir_mount
= 1;
652 /* Create the filesystem state */
653 fd
= open(netns_path
, O_RDONLY
|O_CREAT
|O_EXCL
, 0);
655 fprintf(stderr
, "Cannot create namespace file \"%s\": %s\n",
656 netns_path
, strerror(errno
));
660 if (unshare(CLONE_NEWNET
) < 0) {
661 fprintf(stderr
, "Failed to create a new network namespace \"%s\": %s\n",
662 name
, strerror(errno
));
666 /* Bind the netns last so I can watch for it */
667 if (mount("/proc/self/ns/net", netns_path
, "none", MS_BIND
, NULL
) < 0) {
668 fprintf(stderr
, "Bind /proc/self/ns/net -> %s failed: %s\n",
669 netns_path
, strerror(errno
));
674 netns_delete(argc
, argv
);
678 static int set_netnsid_from_name(const char *name
, int nsid
)
685 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
686 .n
.nlmsg_flags
= NLM_F_REQUEST
,
687 .n
.nlmsg_type
= RTM_NEWNSID
,
688 .g
.rtgen_family
= AF_UNSPEC
,
692 fd
= netns_get_fd(name
);
696 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
697 addattr32(&req
.n
, 1024, NETNSA_NSID
, nsid
);
698 if (rtnl_talk(&rth
, &req
.n
, NULL
) < 0)
705 static int netns_set(int argc
, char **argv
)
707 char netns_path
[PATH_MAX
];
713 fprintf(stderr
, "No netns name specified\n");
717 fprintf(stderr
, "No nsid specified\n");
721 /* If a negative nsid is specified the kernel will select the nsid. */
722 if (strcmp(argv
[1], "auto") == 0)
724 else if (get_unsigned(&nsid
, argv
[1], 0))
725 invarg("Invalid \"netnsid\" value\n", argv
[1]);
727 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
728 netns
= open(netns_path
, O_RDONLY
| O_CLOEXEC
);
730 fprintf(stderr
, "Cannot open network namespace \"%s\": %s\n",
731 name
, strerror(errno
));
735 return set_netnsid_from_name(name
, nsid
);
738 static int netns_monitor(int argc
, char **argv
)
741 struct inotify_event
*event
;
746 fprintf(stderr
, "inotify_init failed: %s\n",
751 if (create_netns_dir())
754 if (inotify_add_watch(fd
, NETNS_RUN_DIR
, IN_CREATE
| IN_DELETE
) < 0) {
755 fprintf(stderr
, "inotify_add_watch failed: %s\n",
760 ssize_t len
= read(fd
, buf
, sizeof(buf
));
763 fprintf(stderr
, "read failed: %s\n",
767 for (event
= (struct inotify_event
*)buf
;
768 (char *)event
< &buf
[len
];
769 event
= (struct inotify_event
*)((char *)event
+ sizeof(*event
) + event
->len
)) {
770 if (event
->mask
& IN_CREATE
)
771 printf("add %s\n", event
->name
);
772 if (event
->mask
& IN_DELETE
)
773 printf("delete %s\n", event
->name
);
779 static int invalid_name(const char *name
)
781 return !*name
|| strlen(name
) > NAME_MAX
||
782 strchr(name
, '/') || !strcmp(name
, ".") || !strcmp(name
, "..");
785 int do_netns(int argc
, char **argv
)
787 netns_nsid_socket_init();
791 return netns_list(0, NULL
);
794 if (argc
> 1 && invalid_name(argv
[1])) {
795 fprintf(stderr
, "Invalid netns name \"%s\"\n", argv
[1]);
799 if ((matches(*argv
, "list") == 0) || (matches(*argv
, "show") == 0) ||
800 (matches(*argv
, "lst") == 0)) {
802 return netns_list(argc
-1, argv
+1);
805 if ((matches(*argv
, "list-id") == 0)) {
807 return netns_list_id(argc
-1, argv
+1);
810 if (matches(*argv
, "help") == 0)
813 if (matches(*argv
, "add") == 0)
814 return netns_add(argc
-1, argv
+1);
816 if (matches(*argv
, "set") == 0)
817 return netns_set(argc
-1, argv
+1);
819 if (matches(*argv
, "delete") == 0)
820 return netns_delete(argc
-1, argv
+1);
822 if (matches(*argv
, "identify") == 0)
823 return netns_identify(argc
-1, argv
+1);
825 if (matches(*argv
, "pids") == 0)
826 return netns_pids(argc
-1, argv
+1);
828 if (matches(*argv
, "exec") == 0)
829 return netns_exec(argc
-1, argv
+1);
831 if (matches(*argv
, "monitor") == 0)
832 return netns_monitor(argc
-1, argv
+1);
834 fprintf(stderr
, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv
);