]>
git.proxmox.com Git - mirror_iproute2.git/blob - ip/ipnetns.c
da019d76202294acba5dbfb42ac9462b1f4738f6
1 /* SPDX-License-Identifier: GPL-2.0 */
6 #include <sys/inotify.h>
8 #include <sys/syscall.h>
12 #include <bsd/string.h>
20 #include <linux/limits.h>
22 #include <linux/net_namespace.h>
26 #include "ip_common.h"
27 #include "namespace.h"
28 #include "json_print.h"
30 static int usage(void)
32 fprintf(stderr
, "Usage: ip netns list\n");
33 fprintf(stderr
, " ip netns add NAME\n");
34 fprintf(stderr
, " ip netns set NAME NETNSID\n");
35 fprintf(stderr
, " ip [-all] netns delete [NAME]\n");
36 fprintf(stderr
, " ip netns identify [PID]\n");
37 fprintf(stderr
, " ip netns pids NAME\n");
38 fprintf(stderr
, " ip [-all] netns exec [NAME] cmd ...\n");
39 fprintf(stderr
, " ip netns monitor\n");
40 fprintf(stderr
, " ip netns list-id\n");
44 /* This socket is used to get nsid */
45 static struct rtnl_handle rtnsh
= { .fd
= -1 };
47 static int have_rtnl_getnsid
= -1;
49 static int ipnetns_accept_msg(struct rtnl_ctrl_data
*ctrl
,
50 struct nlmsghdr
*n
, void *arg
)
52 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(n
);
54 if (n
->nlmsg_type
== NLMSG_ERROR
&&
55 (err
->error
== -EOPNOTSUPP
|| err
->error
== -EINVAL
))
56 have_rtnl_getnsid
= 0;
58 have_rtnl_getnsid
= 1;
62 static int ipnetns_have_nsid(void)
69 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
70 .n
.nlmsg_flags
= NLM_F_REQUEST
,
71 .n
.nlmsg_type
= RTM_GETNSID
,
72 .g
.rtgen_family
= AF_UNSPEC
,
76 if (have_rtnl_getnsid
< 0) {
77 fd
= open("/proc/self/ns/net", O_RDONLY
);
79 have_rtnl_getnsid
= 0;
83 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
85 if (rtnl_send(&rth
, &req
.n
, req
.n
.nlmsg_len
) < 0) {
86 perror("request send failed");
89 rtnl_listen(&rth
, ipnetns_accept_msg
, NULL
);
93 return have_rtnl_getnsid
;
96 int get_netnsid_from_name(const char *name
)
103 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
104 .n
.nlmsg_flags
= NLM_F_REQUEST
,
105 .n
.nlmsg_type
= RTM_GETNSID
,
106 .g
.rtgen_family
= AF_UNSPEC
,
108 struct nlmsghdr
*answer
;
109 struct rtattr
*tb
[NETNSA_MAX
+ 1];
110 struct rtgenmsg
*rthdr
;
113 netns_nsid_socket_init();
115 fd
= netns_get_fd(name
);
119 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
120 if (rtnl_talk(&rtnsh
, &req
.n
, &answer
) < 0) {
126 /* Validate message and parse attributes */
127 if (answer
->nlmsg_type
== NLMSG_ERROR
)
130 rthdr
= NLMSG_DATA(answer
);
131 len
= answer
->nlmsg_len
- NLMSG_SPACE(sizeof(*rthdr
));
135 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
137 if (tb
[NETNSA_NSID
]) {
139 return rta_getattr_u32(tb
[NETNSA_NSID
]);
148 struct hlist_node nsid_hash
;
149 struct hlist_node name_hash
;
154 #define NSIDMAP_SIZE 128
155 #define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
156 #define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
158 static struct hlist_head nsid_head
[NSIDMAP_SIZE
];
159 static struct hlist_head name_head
[NSIDMAP_SIZE
];
161 static struct nsid_cache
*netns_map_get_by_nsid(int nsid
)
163 uint32_t h
= NSID_HASH_NSID(nsid
);
164 struct hlist_node
*n
;
166 hlist_for_each(n
, &nsid_head
[h
]) {
167 struct nsid_cache
*c
= container_of(n
, struct nsid_cache
,
176 char *get_name_from_nsid(int nsid
)
178 struct nsid_cache
*c
;
180 netns_nsid_socket_init();
183 c
= netns_map_get_by_nsid(nsid
);
190 static int netns_map_add(int nsid
, const char *name
)
192 struct nsid_cache
*c
;
195 if (netns_map_get_by_nsid(nsid
) != NULL
)
198 c
= malloc(sizeof(*c
) + strlen(name
) + 1);
204 strcpy(c
->name
, name
);
206 h
= NSID_HASH_NSID(nsid
);
207 hlist_add_head(&c
->nsid_hash
, &nsid_head
[h
]);
209 h
= NSID_HASH_NAME(name
);
210 hlist_add_head(&c
->name_hash
, &name_head
[h
]);
215 static void netns_map_del(struct nsid_cache
*c
)
217 hlist_del(&c
->name_hash
);
218 hlist_del(&c
->nsid_hash
);
222 void netns_nsid_socket_init(void)
224 if (rtnsh
.fd
> -1 || !ipnetns_have_nsid())
227 if (rtnl_open(&rtnsh
, 0) < 0) {
228 fprintf(stderr
, "Cannot open rtnetlink\n");
234 void netns_map_init(void)
236 static int initialized
;
237 struct dirent
*entry
;
241 if (initialized
|| !ipnetns_have_nsid())
244 dir
= opendir(NETNS_RUN_DIR
);
248 while ((entry
= readdir(dir
)) != NULL
) {
249 if (strcmp(entry
->d_name
, ".") == 0)
251 if (strcmp(entry
->d_name
, "..") == 0)
253 nsid
= get_netnsid_from_name(entry
->d_name
);
256 netns_map_add(nsid
, entry
->d_name
);
262 static int netns_get_name(int nsid
, char *name
)
264 struct dirent
*entry
;
268 dir
= opendir(NETNS_RUN_DIR
);
272 while ((entry
= readdir(dir
)) != NULL
) {
273 if (strcmp(entry
->d_name
, ".") == 0)
275 if (strcmp(entry
->d_name
, "..") == 0)
277 id
= get_netnsid_from_name(entry
->d_name
);
280 strcpy(name
, entry
->d_name
);
289 int print_nsid(struct nlmsghdr
*n
, void *arg
)
291 struct rtgenmsg
*rthdr
= NLMSG_DATA(n
);
292 struct rtattr
*tb
[NETNSA_MAX
+1];
293 int len
= n
->nlmsg_len
;
294 FILE *fp
= (FILE *)arg
;
295 struct nsid_cache
*c
;
299 if (n
->nlmsg_type
!= RTM_NEWNSID
&& n
->nlmsg_type
!= RTM_DELNSID
)
302 len
-= NLMSG_SPACE(sizeof(*rthdr
));
304 fprintf(stderr
, "BUG: wrong nlmsg len %d in %s\n", len
,
309 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
310 if (tb
[NETNSA_NSID
] == NULL
) {
311 fprintf(stderr
, "BUG: NETNSA_NSID is missing %s\n", __func__
);
315 open_json_object(NULL
);
316 if (n
->nlmsg_type
== RTM_DELNSID
)
317 print_bool(PRINT_ANY
, "deleted", "Deleted ", true);
319 nsid
= rta_getattr_u32(tb
[NETNSA_NSID
]);
320 print_uint(PRINT_ANY
, "nsid", "nsid %u ", nsid
);
322 c
= netns_map_get_by_nsid(nsid
);
324 print_string(PRINT_ANY
, "name",
325 "(iproute2 netns name: %s)", c
->name
);
329 /* During 'ip monitor nsid', no chance to have new nsid in cache. */
330 if (c
== NULL
&& n
->nlmsg_type
== RTM_NEWNSID
)
331 if (netns_get_name(nsid
, name
) == 0) {
332 print_string(PRINT_ANY
, "name",
333 "(iproute2 netns name: %s)", name
);
334 netns_map_add(nsid
, name
);
337 print_string(PRINT_FP
, NULL
, "\n", NULL
);
343 static int netns_list_id(int argc
, char **argv
)
345 if (!ipnetns_have_nsid()) {
347 "RTM_GETNSID is not supported by the kernel.\n");
351 if (rtnl_nsiddump_req(&rth
, AF_UNSPEC
) < 0) {
352 perror("Cannot send dump request");
357 if (rtnl_dump_filter(&rth
, print_nsid
, stdout
) < 0) {
359 fprintf(stderr
, "Dump terminated\n");
366 static int netns_list(int argc
, char **argv
)
368 struct dirent
*entry
;
372 dir
= opendir(NETNS_RUN_DIR
);
377 while ((entry
= readdir(dir
)) != NULL
) {
378 if (strcmp(entry
->d_name
, ".") == 0)
380 if (strcmp(entry
->d_name
, "..") == 0)
383 open_json_object(NULL
);
384 print_string(PRINT_ANY
, "name",
385 "%s", entry
->d_name
);
386 if (ipnetns_have_nsid()) {
387 id
= get_netnsid_from_name(entry
->d_name
);
389 print_uint(PRINT_ANY
, "id",
392 print_string(PRINT_FP
, NULL
, "\n", NULL
);
400 static int on_netns_exec(char *nsname
, void *arg
)
404 cmd_exec(argv
[1], argv
+ 1, true);
408 static int netns_exec(int argc
, char **argv
)
410 /* Setup the proper environment for apps that are not netns
411 * aware, and execute a program in that environment.
415 if (argc
< 1 && !do_all
) {
416 fprintf(stderr
, "No netns name specified\n");
419 if ((argc
< 2 && !do_all
) || (argc
< 1 && do_all
)) {
420 fprintf(stderr
, "No command specified\n");
425 return do_each_netns(on_netns_exec
, --argv
, 1);
427 if (netns_switch(argv
[0]))
430 /* we just changed namespaces. clear any vrf association
431 * with prior namespace before exec'ing command
435 /* ip must return the status of the child,
436 * but do_cmd() will add a minus to this,
437 * so let's add another one here to cancel it.
440 return -cmd_exec(cmd
, argv
+ 1, !!batch_mode
);
443 static int is_pid(const char *str
)
447 for (; (ch
= *str
); str
++) {
454 static int netns_pids(int argc
, char **argv
)
457 char net_path
[PATH_MAX
];
461 struct dirent
*entry
;
464 fprintf(stderr
, "No netns name specified\n");
468 fprintf(stderr
, "extra arguments specified\n");
473 snprintf(net_path
, sizeof(net_path
), "%s/%s", NETNS_RUN_DIR
, name
);
474 netns
= open(net_path
, O_RDONLY
);
476 fprintf(stderr
, "Cannot open network namespace: %s\n",
480 if (fstat(netns
, &netst
) < 0) {
481 fprintf(stderr
, "Stat of netns failed: %s\n",
485 dir
= opendir("/proc/");
487 fprintf(stderr
, "Open of /proc failed: %s\n",
491 while ((entry
= readdir(dir
))) {
492 char pid_net_path
[PATH_MAX
];
495 if (!is_pid(entry
->d_name
))
497 snprintf(pid_net_path
, sizeof(pid_net_path
), "/proc/%s/ns/net",
499 if (stat(pid_net_path
, &st
) != 0)
501 if ((st
.st_dev
== netst
.st_dev
) &&
502 (st
.st_ino
== netst
.st_ino
)) {
503 printf("%s\n", entry
->d_name
);
511 int netns_identify_pid(const char *pidstr
, char *name
, int len
)
513 char net_path
[PATH_MAX
];
517 struct dirent
*entry
;
521 snprintf(net_path
, sizeof(net_path
), "/proc/%s/ns/net", pidstr
);
522 netns
= open(net_path
, O_RDONLY
);
524 fprintf(stderr
, "Cannot open network namespace: %s\n",
528 if (fstat(netns
, &netst
) < 0) {
529 fprintf(stderr
, "Stat of netns failed: %s\n",
533 dir
= opendir(NETNS_RUN_DIR
);
535 /* Succeed treat a missing directory as an empty directory */
539 fprintf(stderr
, "Failed to open directory %s:%s\n",
540 NETNS_RUN_DIR
, strerror(errno
));
544 while ((entry
= readdir(dir
))) {
545 char name_path
[PATH_MAX
];
548 if (strcmp(entry
->d_name
, ".") == 0)
550 if (strcmp(entry
->d_name
, "..") == 0)
553 snprintf(name_path
, sizeof(name_path
), "%s/%s", NETNS_RUN_DIR
,
556 if (stat(name_path
, &st
) != 0)
559 if ((st
.st_dev
== netst
.st_dev
) &&
560 (st
.st_ino
== netst
.st_ino
)) {
561 strlcpy(name
, entry
->d_name
, len
);
569 static int netns_identify(int argc
, char **argv
)
577 } else if (argc
> 1) {
578 fprintf(stderr
, "extra arguments specified\n");
582 if (!is_pid(pidstr
)) {
583 fprintf(stderr
, "Specified string '%s' is not a pid\n",
589 rc
= netns_identify_pid(pidstr
, name
, sizeof(name
));
591 printf("%s\n", name
);
596 static int on_netns_del(char *nsname
, void *arg
)
598 char netns_path
[PATH_MAX
];
600 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, nsname
);
601 umount2(netns_path
, MNT_DETACH
);
602 if (unlink(netns_path
) < 0) {
603 fprintf(stderr
, "Cannot remove namespace file \"%s\": %s\n",
604 netns_path
, strerror(errno
));
610 static int netns_delete(int argc
, char **argv
)
612 if (argc
< 1 && !do_all
) {
613 fprintf(stderr
, "No netns name specified\n");
618 return netns_foreach(on_netns_del
, NULL
);
620 return on_netns_del(argv
[0], NULL
);
623 static int create_netns_dir(void)
625 /* Create the base netns directory if it doesn't exist */
626 if (mkdir(NETNS_RUN_DIR
, S_IRWXU
|S_IRGRP
|S_IXGRP
|S_IROTH
|S_IXOTH
)) {
627 if (errno
!= EEXIST
) {
628 fprintf(stderr
, "mkdir %s failed: %s\n",
629 NETNS_RUN_DIR
, strerror(errno
));
637 static int netns_add(int argc
, char **argv
)
639 /* This function creates a new network namespace and
640 * a new mount namespace and bind them into a well known
641 * location in the filesystem based on the name provided.
643 * The mount namespace is created so that any necessary
644 * userspace tweaks like remounting /sys, or bind mounting
645 * a new /etc/resolv.conf can be shared between uers.
647 char netns_path
[PATH_MAX
];
650 int made_netns_run_dir_mount
= 0;
653 fprintf(stderr
, "No netns name specified\n");
658 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
660 if (create_netns_dir())
663 /* Make it possible for network namespace mounts to propagate between
664 * mount namespaces. This makes it likely that a unmounting a network
665 * namespace file in one namespace will unmount the network namespace
666 * file in all namespaces allowing the network namespace to be freed
669 while (mount("", NETNS_RUN_DIR
, "none", MS_SHARED
| MS_REC
, NULL
)) {
670 /* Fail unless we need to make the mount point */
671 if (errno
!= EINVAL
|| made_netns_run_dir_mount
) {
672 fprintf(stderr
, "mount --make-shared %s failed: %s\n",
673 NETNS_RUN_DIR
, strerror(errno
));
677 /* Upgrade NETNS_RUN_DIR to a mount point */
678 if (mount(NETNS_RUN_DIR
, NETNS_RUN_DIR
, "none", MS_BIND
| MS_REC
, NULL
)) {
679 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
680 NETNS_RUN_DIR
, NETNS_RUN_DIR
, strerror(errno
));
683 made_netns_run_dir_mount
= 1;
686 /* Create the filesystem state */
687 fd
= open(netns_path
, O_RDONLY
|O_CREAT
|O_EXCL
, 0);
689 fprintf(stderr
, "Cannot create namespace file \"%s\": %s\n",
690 netns_path
, strerror(errno
));
694 if (unshare(CLONE_NEWNET
) < 0) {
695 fprintf(stderr
, "Failed to create a new network namespace \"%s\": %s\n",
696 name
, strerror(errno
));
700 /* Bind the netns last so I can watch for it */
701 if (mount("/proc/self/ns/net", netns_path
, "none", MS_BIND
, NULL
) < 0) {
702 fprintf(stderr
, "Bind /proc/self/ns/net -> %s failed: %s\n",
703 netns_path
, strerror(errno
));
708 netns_delete(argc
, argv
);
712 int set_netnsid_from_name(const char *name
, int nsid
)
719 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
720 .n
.nlmsg_flags
= NLM_F_REQUEST
,
721 .n
.nlmsg_type
= RTM_NEWNSID
,
722 .g
.rtgen_family
= AF_UNSPEC
,
726 netns_nsid_socket_init();
728 fd
= netns_get_fd(name
);
732 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
733 addattr32(&req
.n
, 1024, NETNSA_NSID
, nsid
);
734 if (rtnl_talk(&rth
, &req
.n
, NULL
) < 0)
741 static int netns_set(int argc
, char **argv
)
743 char netns_path
[PATH_MAX
];
749 fprintf(stderr
, "No netns name specified\n");
753 fprintf(stderr
, "No nsid specified\n");
757 /* If a negative nsid is specified the kernel will select the nsid. */
758 if (strcmp(argv
[1], "auto") == 0)
760 else if (get_unsigned(&nsid
, argv
[1], 0))
761 invarg("Invalid \"netnsid\" value\n", argv
[1]);
763 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
764 netns
= open(netns_path
, O_RDONLY
| O_CLOEXEC
);
766 fprintf(stderr
, "Cannot open network namespace \"%s\": %s\n",
767 name
, strerror(errno
));
771 return set_netnsid_from_name(name
, nsid
);
774 static int netns_monitor(int argc
, char **argv
)
777 struct inotify_event
*event
;
782 fprintf(stderr
, "inotify_init failed: %s\n",
787 if (create_netns_dir())
790 if (inotify_add_watch(fd
, NETNS_RUN_DIR
, IN_CREATE
| IN_DELETE
) < 0) {
791 fprintf(stderr
, "inotify_add_watch failed: %s\n",
796 ssize_t len
= read(fd
, buf
, sizeof(buf
));
799 fprintf(stderr
, "read failed: %s\n",
803 for (event
= (struct inotify_event
*)buf
;
804 (char *)event
< &buf
[len
];
805 event
= (struct inotify_event
*)((char *)event
+ sizeof(*event
) + event
->len
)) {
806 if (event
->mask
& IN_CREATE
)
807 printf("add %s\n", event
->name
);
808 if (event
->mask
& IN_DELETE
)
809 printf("delete %s\n", event
->name
);
815 static int invalid_name(const char *name
)
817 return !*name
|| strlen(name
) > NAME_MAX
||
818 strchr(name
, '/') || !strcmp(name
, ".") || !strcmp(name
, "..");
821 int do_netns(int argc
, char **argv
)
823 netns_nsid_socket_init();
827 return netns_list(0, NULL
);
830 if (argc
> 1 && invalid_name(argv
[1])) {
831 fprintf(stderr
, "Invalid netns name \"%s\"\n", argv
[1]);
835 if ((matches(*argv
, "list") == 0) || (matches(*argv
, "show") == 0) ||
836 (matches(*argv
, "lst") == 0)) {
838 return netns_list(argc
-1, argv
+1);
841 if ((matches(*argv
, "list-id") == 0)) {
843 return netns_list_id(argc
-1, argv
+1);
846 if (matches(*argv
, "help") == 0)
849 if (matches(*argv
, "add") == 0)
850 return netns_add(argc
-1, argv
+1);
852 if (matches(*argv
, "set") == 0)
853 return netns_set(argc
-1, argv
+1);
855 if (matches(*argv
, "delete") == 0)
856 return netns_delete(argc
-1, argv
+1);
858 if (matches(*argv
, "identify") == 0)
859 return netns_identify(argc
-1, argv
+1);
861 if (matches(*argv
, "pids") == 0)
862 return netns_pids(argc
-1, argv
+1);
864 if (matches(*argv
, "exec") == 0)
865 return netns_exec(argc
-1, argv
+1);
867 if (matches(*argv
, "monitor") == 0)
868 return netns_monitor(argc
-1, argv
+1);
870 fprintf(stderr
, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv
);