]>
git.proxmox.com Git - mirror_iproute2.git/blob - ip/ipnetns.c
5 #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 nlmsghdr
*n
, void *arg
)
48 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(n
);
50 if (n
->nlmsg_type
== NLMSG_ERROR
&&
51 (err
->error
== -EOPNOTSUPP
|| err
->error
== -EINVAL
))
52 have_rtnl_getnsid
= 0;
54 have_rtnl_getnsid
= 1;
58 static int ipnetns_have_nsid(void)
67 if (have_rtnl_getnsid
< 0) {
68 memset(&req
, 0, sizeof(req
));
69 req
.n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
));
70 req
.n
.nlmsg_flags
= NLM_F_REQUEST
;
71 req
.n
.nlmsg_type
= RTM_GETNSID
;
72 req
.g
.rtgen_family
= AF_UNSPEC
;
74 fd
= open("/proc/self/ns/net", O_RDONLY
);
76 perror("open(\"/proc/self/ns/net\")");
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 struct rtattr
*tb
[NETNSA_MAX
+ 1];
101 struct rtgenmsg
*rthdr
;
104 memset(&req
, 0, sizeof(req
));
105 req
.n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
));
106 req
.n
.nlmsg_flags
= NLM_F_REQUEST
;
107 req
.n
.nlmsg_type
= RTM_GETNSID
;
108 req
.g
.rtgen_family
= AF_UNSPEC
;
110 fd
= netns_get_fd(name
);
114 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
115 if (rtnl_talk(&rtnsh
, &req
.n
, &answer
.n
, sizeof(answer
)) < 0) {
121 /* Validate message and parse attributes */
122 if (answer
.n
.nlmsg_type
== NLMSG_ERROR
)
125 rthdr
= NLMSG_DATA(&answer
.n
);
126 len
= answer
.n
.nlmsg_len
- NLMSG_SPACE(sizeof(*rthdr
));
130 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
133 return rta_getattr_u32(tb
[NETNSA_NSID
]);
139 struct hlist_node nsid_hash
;
140 struct hlist_node name_hash
;
145 #define NSIDMAP_SIZE 128
146 #define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
147 #define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
149 static struct hlist_head nsid_head
[NSIDMAP_SIZE
];
150 static struct hlist_head name_head
[NSIDMAP_SIZE
];
152 static struct nsid_cache
*netns_map_get_by_nsid(int nsid
)
154 uint32_t h
= NSID_HASH_NSID(nsid
);
155 struct hlist_node
*n
;
157 hlist_for_each(n
, &nsid_head
[h
]) {
158 struct nsid_cache
*c
= container_of(n
, struct nsid_cache
,
167 static int netns_map_add(int nsid
, char *name
)
169 struct nsid_cache
*c
;
172 if (netns_map_get_by_nsid(nsid
) != NULL
)
175 c
= malloc(sizeof(*c
));
181 strcpy(c
->name
, name
);
183 h
= NSID_HASH_NSID(nsid
);
184 hlist_add_head(&c
->nsid_hash
, &nsid_head
[h
]);
186 h
= NSID_HASH_NAME(name
);
187 hlist_add_head(&c
->name_hash
, &name_head
[h
]);
192 static void netns_map_del(struct nsid_cache
*c
)
194 hlist_del(&c
->name_hash
);
195 hlist_del(&c
->nsid_hash
);
199 void netns_map_init(void)
201 static int initialized
;
202 struct dirent
*entry
;
206 if (initialized
|| !ipnetns_have_nsid())
209 if (rtnl_open(&rtnsh
, 0) < 0) {
210 fprintf(stderr
, "Cannot open rtnetlink\n");
214 dir
= opendir(NETNS_RUN_DIR
);
218 while ((entry
= readdir(dir
)) != NULL
) {
219 if (strcmp(entry
->d_name
, ".") == 0)
221 if (strcmp(entry
->d_name
, "..") == 0)
223 nsid
= get_netnsid_from_name(entry
->d_name
);
226 netns_map_add(nsid
, entry
->d_name
);
232 static int netns_get_name(int nsid
, char *name
)
234 struct dirent
*entry
;
238 dir
= opendir(NETNS_RUN_DIR
);
242 while ((entry
= readdir(dir
)) != NULL
) {
243 if (strcmp(entry
->d_name
, ".") == 0)
245 if (strcmp(entry
->d_name
, "..") == 0)
247 id
= get_netnsid_from_name(entry
->d_name
);
250 strcpy(name
, entry
->d_name
);
259 int print_nsid(const struct sockaddr_nl
*who
, struct nlmsghdr
*n
, void *arg
)
261 struct rtgenmsg
*rthdr
= NLMSG_DATA(n
);
262 struct rtattr
*tb
[NETNSA_MAX
+1];
263 int len
= n
->nlmsg_len
;
264 FILE *fp
= (FILE *)arg
;
265 struct nsid_cache
*c
;
269 if (n
->nlmsg_type
!= RTM_NEWNSID
&& n
->nlmsg_type
!= RTM_DELNSID
)
272 len
-= NLMSG_SPACE(sizeof(*rthdr
));
274 fprintf(stderr
, "BUG: wrong nlmsg len %d in %s\n", len
,
279 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
280 if (tb
[NETNSA_NSID
] == NULL
) {
281 fprintf(stderr
, "BUG: NETNSA_NSID is missing %s\n", __func__
);
285 if (n
->nlmsg_type
== RTM_DELNSID
)
286 fprintf(fp
, "Deleted ");
288 nsid
= rta_getattr_u32(tb
[NETNSA_NSID
]);
289 fprintf(fp
, "nsid %u ", nsid
);
291 c
= netns_map_get_by_nsid(nsid
);
293 fprintf(fp
, "(iproute2 netns name: %s)", c
->name
);
297 /* During 'ip monitor nsid', no chance to have new nsid in cache. */
298 if (c
== NULL
&& n
->nlmsg_type
== RTM_NEWNSID
)
299 if (netns_get_name(nsid
, name
) == 0) {
300 fprintf(fp
, "(iproute2 netns name: %s)", name
);
301 netns_map_add(nsid
, name
);
309 static int netns_list_id(int argc
, char **argv
)
311 if (!ipnetns_have_nsid()) {
313 "RTM_GETNSID is not supported by the kernel.\n");
317 if (rtnl_wilddump_request(&rth
, AF_UNSPEC
, RTM_GETNSID
) < 0) {
318 perror("Cannot send dump request");
321 if (rtnl_dump_filter(&rth
, print_nsid
, stdout
) < 0) {
322 fprintf(stderr
, "Dump terminated\n");
328 static int netns_list(int argc
, char **argv
)
330 struct dirent
*entry
;
334 dir
= opendir(NETNS_RUN_DIR
);
338 while ((entry
= readdir(dir
)) != NULL
) {
339 if (strcmp(entry
->d_name
, ".") == 0)
341 if (strcmp(entry
->d_name
, "..") == 0)
343 printf("%s", entry
->d_name
);
344 if (ipnetns_have_nsid()) {
345 id
= get_netnsid_from_name(entry
->d_name
);
347 printf(" (id: %d)", id
);
355 static int cmd_exec(const char *cmd
, char **argv
, bool do_fork
)
370 if (waitpid(pid
, &status
, 0) < 0) {
375 if (WIFEXITED(status
)) {
376 return WEXITSTATUS(status
);
383 if (execvp(cmd
, argv
) < 0)
384 fprintf(stderr
, "exec of \"%s\" failed: %s\n",
385 cmd
, strerror(errno
));
389 static int on_netns_exec(char *nsname
, void *arg
)
392 cmd_exec(argv
[1], argv
+ 1, true);
396 static int netns_exec(int argc
, char **argv
)
398 /* Setup the proper environment for apps that are not netns
399 * aware, and execute a program in that environment.
403 if (argc
< 1 && !do_all
) {
404 fprintf(stderr
, "No netns name specified\n");
407 if ((argc
< 2 && !do_all
) || (argc
< 1 && do_all
)) {
408 fprintf(stderr
, "No command specified\n");
413 return do_each_netns(on_netns_exec
, --argv
, 1);
415 if (netns_switch(argv
[0]))
418 /* ip must return the status of the child,
419 * but do_cmd() will add a minus to this,
420 * so let's add another one here to cancel it.
423 return -cmd_exec(cmd
, argv
+ 1, !!batch_mode
);
426 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
[MAXPATHLEN
];
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
[MAXPATHLEN
];
476 if (!is_pid(entry
->d_name
))
478 snprintf(pid_net_path
, sizeof(pid_net_path
), "/proc/%s/ns/net",
480 if (stat(pid_net_path
, &st
) != 0)
482 if ((st
.st_dev
== netst
.st_dev
) &&
483 (st
.st_ino
== netst
.st_ino
)) {
484 printf("%s\n", entry
->d_name
);
492 static int netns_identify(int argc
, char **argv
)
495 char net_path
[MAXPATHLEN
];
499 struct dirent
*entry
;
503 } else if (argc
> 1) {
504 fprintf(stderr
, "extra arguments specified\n");
508 if (!is_pid(pidstr
)) {
509 fprintf(stderr
, "Specified string '%s' is not a pid\n",
515 snprintf(net_path
, sizeof(net_path
), "/proc/%s/ns/net", pidstr
);
516 netns
= open(net_path
, O_RDONLY
);
518 fprintf(stderr
, "Cannot open network namespace: %s\n",
522 if (fstat(netns
, &netst
) < 0) {
523 fprintf(stderr
, "Stat of netns failed: %s\n",
527 dir
= opendir(NETNS_RUN_DIR
);
529 /* Succeed treat a missing directory as an empty directory */
533 fprintf(stderr
, "Failed to open directory %s:%s\n",
534 NETNS_RUN_DIR
, strerror(errno
));
538 while((entry
= readdir(dir
))) {
539 char name_path
[MAXPATHLEN
];
542 if (strcmp(entry
->d_name
, ".") == 0)
544 if (strcmp(entry
->d_name
, "..") == 0)
547 snprintf(name_path
, sizeof(name_path
), "%s/%s", NETNS_RUN_DIR
,
550 if (stat(name_path
, &st
) != 0)
553 if ((st
.st_dev
== netst
.st_dev
) &&
554 (st
.st_ino
== netst
.st_ino
)) {
555 printf("%s\n", entry
->d_name
);
563 static int on_netns_del(char *nsname
, void *arg
)
565 char netns_path
[MAXPATHLEN
];
567 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, nsname
);
568 umount2(netns_path
, MNT_DETACH
);
569 if (unlink(netns_path
) < 0) {
570 fprintf(stderr
, "Cannot remove namespace file \"%s\": %s\n",
571 netns_path
, strerror(errno
));
577 static int netns_delete(int argc
, char **argv
)
579 if (argc
< 1 && !do_all
) {
580 fprintf(stderr
, "No netns name specified\n");
585 return netns_foreach(on_netns_del
, NULL
);
587 return on_netns_del(argv
[0], NULL
);
590 static int create_netns_dir(void)
592 /* Create the base netns directory if it doesn't exist */
593 if (mkdir(NETNS_RUN_DIR
, S_IRWXU
|S_IRGRP
|S_IXGRP
|S_IROTH
|S_IXOTH
)) {
594 if (errno
!= EEXIST
) {
595 fprintf(stderr
, "mkdir %s failed: %s\n",
596 NETNS_RUN_DIR
, strerror(errno
));
604 static int netns_add(int argc
, char **argv
)
606 /* This function creates a new network namespace and
607 * a new mount namespace and bind them into a well known
608 * location in the filesystem based on the name provided.
610 * The mount namespace is created so that any necessary
611 * userspace tweaks like remounting /sys, or bind mounting
612 * a new /etc/resolv.conf can be shared between uers.
614 char netns_path
[MAXPATHLEN
];
617 int made_netns_run_dir_mount
= 0;
620 fprintf(stderr
, "No netns name specified\n");
625 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
627 if (create_netns_dir())
630 /* Make it possible for network namespace mounts to propagate between
631 * mount namespaces. This makes it likely that a unmounting a network
632 * namespace file in one namespace will unmount the network namespace
633 * file in all namespaces allowing the network namespace to be freed
636 while (mount("", NETNS_RUN_DIR
, "none", MS_SHARED
| MS_REC
, NULL
)) {
637 /* Fail unless we need to make the mount point */
638 if (errno
!= EINVAL
|| made_netns_run_dir_mount
) {
639 fprintf(stderr
, "mount --make-shared %s failed: %s\n",
640 NETNS_RUN_DIR
, strerror(errno
));
644 /* Upgrade NETNS_RUN_DIR to a mount point */
645 if (mount(NETNS_RUN_DIR
, NETNS_RUN_DIR
, "none", MS_BIND
, NULL
)) {
646 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
647 NETNS_RUN_DIR
, NETNS_RUN_DIR
, strerror(errno
));
650 made_netns_run_dir_mount
= 1;
653 /* Create the filesystem state */
654 fd
= open(netns_path
, O_RDONLY
|O_CREAT
|O_EXCL
, 0);
656 fprintf(stderr
, "Cannot create namespace file \"%s\": %s\n",
657 netns_path
, strerror(errno
));
661 if (unshare(CLONE_NEWNET
) < 0) {
662 fprintf(stderr
, "Failed to create a new network namespace \"%s\": %s\n",
663 name
, strerror(errno
));
667 /* Bind the netns last so I can watch for it */
668 if (mount("/proc/self/ns/net", netns_path
, "none", MS_BIND
, NULL
) < 0) {
669 fprintf(stderr
, "Bind /proc/self/ns/net -> %s failed: %s\n",
670 netns_path
, strerror(errno
));
675 netns_delete(argc
, argv
);
679 static int set_netnsid_from_name(const char *name
, int nsid
)
688 memset(&req
, 0, sizeof(req
));
689 req
.n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
));
690 req
.n
.nlmsg_flags
= NLM_F_REQUEST
;
691 req
.n
.nlmsg_type
= RTM_NEWNSID
;
692 req
.g
.rtgen_family
= AF_UNSPEC
;
694 fd
= netns_get_fd(name
);
698 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
699 addattr32(&req
.n
, 1024, NETNSA_NSID
, nsid
);
700 if (rtnl_talk(&rth
, &req
.n
, NULL
, 0) < 0)
707 static int netns_set(int argc
, char **argv
)
709 char netns_path
[MAXPATHLEN
];
714 fprintf(stderr
, "No netns name specified\n");
718 fprintf(stderr
, "No nsid specified\n");
722 nsid
= atoi(argv
[1]);
724 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
725 netns
= open(netns_path
, O_RDONLY
| O_CLOEXEC
);
727 fprintf(stderr
, "Cannot open network namespace \"%s\": %s\n",
728 name
, strerror(errno
));
732 return set_netnsid_from_name(name
, nsid
);
735 static int netns_monitor(int argc
, char **argv
)
738 struct inotify_event
*event
;
742 fprintf(stderr
, "inotify_init failed: %s\n",
747 if (create_netns_dir())
750 if (inotify_add_watch(fd
, NETNS_RUN_DIR
, IN_CREATE
| IN_DELETE
) < 0) {
751 fprintf(stderr
, "inotify_add_watch failed: %s\n",
756 ssize_t len
= read(fd
, buf
, sizeof(buf
));
758 fprintf(stderr
, "read failed: %s\n",
762 for (event
= (struct inotify_event
*)buf
;
763 (char *)event
< &buf
[len
];
764 event
= (struct inotify_event
*)((char *)event
+ sizeof(*event
) + event
->len
)) {
765 if (event
->mask
& IN_CREATE
)
766 printf("add %s\n", event
->name
);
767 if (event
->mask
& IN_DELETE
)
768 printf("delete %s\n", event
->name
);
774 int do_netns(int argc
, char **argv
)
779 return netns_list(0, NULL
);
781 if ((matches(*argv
, "list") == 0) || (matches(*argv
, "show") == 0) ||
782 (matches(*argv
, "lst") == 0))
783 return netns_list(argc
-1, argv
+1);
785 if ((matches(*argv
, "list-id") == 0))
786 return netns_list_id(argc
-1, argv
+1);
788 if (matches(*argv
, "help") == 0)
791 if (matches(*argv
, "add") == 0)
792 return netns_add(argc
-1, argv
+1);
794 if (matches(*argv
, "set") == 0)
795 return netns_set(argc
-1, argv
+1);
797 if (matches(*argv
, "delete") == 0)
798 return netns_delete(argc
-1, argv
+1);
800 if (matches(*argv
, "identify") == 0)
801 return netns_identify(argc
-1, argv
+1);
803 if (matches(*argv
, "pids") == 0)
804 return netns_pids(argc
-1, argv
+1);
806 if (matches(*argv
, "exec") == 0)
807 return netns_exec(argc
-1, argv
+1);
809 if (matches(*argv
, "monitor") == 0)
810 return netns_monitor(argc
-1, argv
+1);
812 fprintf(stderr
, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv
);