]>
git.proxmox.com Git - mirror_iproute2.git/blob - ip/ipnetns.c
5 #include <sys/inotify.h>
7 #include <sys/syscall.h>
16 #include <linux/limits.h>
18 #include <linux/net_namespace.h>
22 #include "ip_common.h"
23 #include "namespace.h"
25 static int usage(void)
27 fprintf(stderr
, "Usage: ip netns list\n");
28 fprintf(stderr
, " ip netns add NAME\n");
29 fprintf(stderr
, " ip netns set NAME NETNSID\n");
30 fprintf(stderr
, " ip [-all] netns delete [NAME]\n");
31 fprintf(stderr
, " ip netns identify [PID]\n");
32 fprintf(stderr
, " ip netns pids NAME\n");
33 fprintf(stderr
, " ip [-all] netns exec [NAME] cmd ...\n");
34 fprintf(stderr
, " ip netns monitor\n");
35 fprintf(stderr
, " ip netns list-id\n");
39 /* This socket is used to get nsid */
40 static struct rtnl_handle rtnsh
= { .fd
= -1 };
42 static int have_rtnl_getnsid
= -1;
44 static int ipnetns_accept_msg(const struct sockaddr_nl
*who
,
45 struct rtnl_ctrl_data
*ctrl
,
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)
65 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
66 .n
.nlmsg_flags
= NLM_F_REQUEST
,
67 .n
.nlmsg_type
= RTM_GETNSID
,
68 .g
.rtgen_family
= AF_UNSPEC
,
72 if (have_rtnl_getnsid
< 0) {
73 fd
= open("/proc/self/ns/net", O_RDONLY
);
75 have_rtnl_getnsid
= 0;
79 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
81 if (rtnl_send(&rth
, &req
.n
, req
.n
.nlmsg_len
) < 0) {
82 perror("request send failed");
85 rtnl_listen(&rth
, ipnetns_accept_msg
, NULL
);
89 return have_rtnl_getnsid
;
92 static int get_netnsid_from_name(const char *name
)
99 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
100 .n
.nlmsg_flags
= NLM_F_REQUEST
,
101 .n
.nlmsg_type
= RTM_GETNSID
,
102 .g
.rtgen_family
= AF_UNSPEC
,
104 struct nlmsghdr
*answer
;
105 struct rtattr
*tb
[NETNSA_MAX
+ 1];
106 struct rtgenmsg
*rthdr
;
109 fd
= netns_get_fd(name
);
113 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
114 if (rtnl_talk(&rtnsh
, &req
.n
, &answer
) < 0) {
120 /* Validate message and parse attributes */
121 if (answer
->nlmsg_type
== NLMSG_ERROR
)
124 rthdr
= NLMSG_DATA(answer
);
125 len
= answer
->nlmsg_len
- NLMSG_SPACE(sizeof(*rthdr
));
129 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
131 if (tb
[NETNSA_NSID
]) {
133 return rta_getattr_u32(tb
[NETNSA_NSID
]);
142 struct hlist_node nsid_hash
;
143 struct hlist_node name_hash
;
148 #define NSIDMAP_SIZE 128
149 #define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
150 #define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
152 static struct hlist_head nsid_head
[NSIDMAP_SIZE
];
153 static struct hlist_head name_head
[NSIDMAP_SIZE
];
155 static struct nsid_cache
*netns_map_get_by_nsid(int nsid
)
157 uint32_t h
= NSID_HASH_NSID(nsid
);
158 struct hlist_node
*n
;
160 hlist_for_each(n
, &nsid_head
[h
]) {
161 struct nsid_cache
*c
= container_of(n
, struct nsid_cache
,
170 static int netns_map_add(int nsid
, const char *name
)
172 struct nsid_cache
*c
;
175 if (netns_map_get_by_nsid(nsid
) != NULL
)
178 c
= malloc(sizeof(*c
) + strlen(name
) + 1);
184 strcpy(c
->name
, name
);
186 h
= NSID_HASH_NSID(nsid
);
187 hlist_add_head(&c
->nsid_hash
, &nsid_head
[h
]);
189 h
= NSID_HASH_NAME(name
);
190 hlist_add_head(&c
->name_hash
, &name_head
[h
]);
195 static void netns_map_del(struct nsid_cache
*c
)
197 hlist_del(&c
->name_hash
);
198 hlist_del(&c
->nsid_hash
);
202 void netns_nsid_socket_init(void)
204 if (rtnsh
.fd
> -1 || !ipnetns_have_nsid())
207 if (rtnl_open(&rtnsh
, 0) < 0) {
208 fprintf(stderr
, "Cannot open rtnetlink\n");
214 void netns_map_init(void)
216 static int initialized
;
217 struct dirent
*entry
;
221 if (initialized
|| !ipnetns_have_nsid())
224 dir
= opendir(NETNS_RUN_DIR
);
228 while ((entry
= readdir(dir
)) != NULL
) {
229 if (strcmp(entry
->d_name
, ".") == 0)
231 if (strcmp(entry
->d_name
, "..") == 0)
233 nsid
= get_netnsid_from_name(entry
->d_name
);
236 netns_map_add(nsid
, entry
->d_name
);
242 static int netns_get_name(int nsid
, char *name
)
244 struct dirent
*entry
;
248 dir
= opendir(NETNS_RUN_DIR
);
252 while ((entry
= readdir(dir
)) != NULL
) {
253 if (strcmp(entry
->d_name
, ".") == 0)
255 if (strcmp(entry
->d_name
, "..") == 0)
257 id
= get_netnsid_from_name(entry
->d_name
);
260 strcpy(name
, entry
->d_name
);
269 int print_nsid(const struct sockaddr_nl
*who
, struct nlmsghdr
*n
, void *arg
)
271 struct rtgenmsg
*rthdr
= NLMSG_DATA(n
);
272 struct rtattr
*tb
[NETNSA_MAX
+1];
273 int len
= n
->nlmsg_len
;
274 FILE *fp
= (FILE *)arg
;
275 struct nsid_cache
*c
;
279 if (n
->nlmsg_type
!= RTM_NEWNSID
&& n
->nlmsg_type
!= RTM_DELNSID
)
282 len
-= NLMSG_SPACE(sizeof(*rthdr
));
284 fprintf(stderr
, "BUG: wrong nlmsg len %d in %s\n", len
,
289 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
290 if (tb
[NETNSA_NSID
] == NULL
) {
291 fprintf(stderr
, "BUG: NETNSA_NSID is missing %s\n", __func__
);
295 if (n
->nlmsg_type
== RTM_DELNSID
)
296 fprintf(fp
, "Deleted ");
298 nsid
= rta_getattr_u32(tb
[NETNSA_NSID
]);
299 fprintf(fp
, "nsid %u ", nsid
);
301 c
= netns_map_get_by_nsid(nsid
);
303 fprintf(fp
, "(iproute2 netns name: %s)", c
->name
);
307 /* During 'ip monitor nsid', no chance to have new nsid in cache. */
308 if (c
== NULL
&& n
->nlmsg_type
== RTM_NEWNSID
)
309 if (netns_get_name(nsid
, name
) == 0) {
310 fprintf(fp
, "(iproute2 netns name: %s)", name
);
311 netns_map_add(nsid
, name
);
319 static int netns_list_id(int argc
, char **argv
)
321 if (!ipnetns_have_nsid()) {
323 "RTM_GETNSID is not supported by the kernel.\n");
327 if (rtnl_wilddump_request(&rth
, AF_UNSPEC
, RTM_GETNSID
) < 0) {
328 perror("Cannot send dump request");
331 if (rtnl_dump_filter(&rth
, print_nsid
, stdout
) < 0) {
332 fprintf(stderr
, "Dump terminated\n");
338 static int netns_list(int argc
, char **argv
)
340 struct dirent
*entry
;
344 dir
= opendir(NETNS_RUN_DIR
);
348 while ((entry
= readdir(dir
)) != NULL
) {
349 if (strcmp(entry
->d_name
, ".") == 0)
351 if (strcmp(entry
->d_name
, "..") == 0)
353 printf("%s", entry
->d_name
);
354 if (ipnetns_have_nsid()) {
355 id
= get_netnsid_from_name(entry
->d_name
);
357 printf(" (id: %d)", id
);
365 static int on_netns_exec(char *nsname
, void *arg
)
369 cmd_exec(argv
[1], argv
+ 1, true);
373 static int netns_exec(int argc
, char **argv
)
375 /* Setup the proper environment for apps that are not netns
376 * aware, and execute a program in that environment.
380 if (argc
< 1 && !do_all
) {
381 fprintf(stderr
, "No netns name specified\n");
384 if ((argc
< 2 && !do_all
) || (argc
< 1 && do_all
)) {
385 fprintf(stderr
, "No command specified\n");
390 return do_each_netns(on_netns_exec
, --argv
, 1);
392 if (netns_switch(argv
[0]))
395 /* we just changed namespaces. clear any vrf association
396 * with prior namespace before exec'ing command
400 /* ip must return the status of the child,
401 * but do_cmd() will add a minus to this,
402 * so let's add another one here to cancel it.
405 return -cmd_exec(cmd
, argv
+ 1, !!batch_mode
);
408 static int is_pid(const char *str
)
412 for (; (ch
= *str
); str
++) {
419 static int netns_pids(int argc
, char **argv
)
422 char net_path
[PATH_MAX
];
426 struct dirent
*entry
;
429 fprintf(stderr
, "No netns name specified\n");
433 fprintf(stderr
, "extra arguments specified\n");
438 snprintf(net_path
, sizeof(net_path
), "%s/%s", NETNS_RUN_DIR
, name
);
439 netns
= open(net_path
, O_RDONLY
);
441 fprintf(stderr
, "Cannot open network namespace: %s\n",
445 if (fstat(netns
, &netst
) < 0) {
446 fprintf(stderr
, "Stat of netns failed: %s\n",
450 dir
= opendir("/proc/");
452 fprintf(stderr
, "Open of /proc failed: %s\n",
456 while ((entry
= readdir(dir
))) {
457 char pid_net_path
[PATH_MAX
];
460 if (!is_pid(entry
->d_name
))
462 snprintf(pid_net_path
, sizeof(pid_net_path
), "/proc/%s/ns/net",
464 if (stat(pid_net_path
, &st
) != 0)
466 if ((st
.st_dev
== netst
.st_dev
) &&
467 (st
.st_ino
== netst
.st_ino
)) {
468 printf("%s\n", entry
->d_name
);
476 int netns_identify_pid(const char *pidstr
, char *name
, int len
)
478 char net_path
[PATH_MAX
];
482 struct dirent
*entry
;
486 snprintf(net_path
, sizeof(net_path
), "/proc/%s/ns/net", pidstr
);
487 netns
= open(net_path
, O_RDONLY
);
489 fprintf(stderr
, "Cannot open network namespace: %s\n",
493 if (fstat(netns
, &netst
) < 0) {
494 fprintf(stderr
, "Stat of netns failed: %s\n",
498 dir
= opendir(NETNS_RUN_DIR
);
500 /* Succeed treat a missing directory as an empty directory */
504 fprintf(stderr
, "Failed to open directory %s:%s\n",
505 NETNS_RUN_DIR
, strerror(errno
));
509 while ((entry
= readdir(dir
))) {
510 char name_path
[PATH_MAX
];
513 if (strcmp(entry
->d_name
, ".") == 0)
515 if (strcmp(entry
->d_name
, "..") == 0)
518 snprintf(name_path
, sizeof(name_path
), "%s/%s", NETNS_RUN_DIR
,
521 if (stat(name_path
, &st
) != 0)
524 if ((st
.st_dev
== netst
.st_dev
) &&
525 (st
.st_ino
== netst
.st_ino
)) {
526 strlcpy(name
, entry
->d_name
, len
);
534 static int netns_identify(int argc
, char **argv
)
542 } else if (argc
> 1) {
543 fprintf(stderr
, "extra arguments specified\n");
547 if (!is_pid(pidstr
)) {
548 fprintf(stderr
, "Specified string '%s' is not a pid\n",
554 rc
= netns_identify_pid(pidstr
, name
, sizeof(name
));
556 printf("%s\n", name
);
561 static int on_netns_del(char *nsname
, void *arg
)
563 char netns_path
[PATH_MAX
];
565 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, nsname
);
566 umount2(netns_path
, MNT_DETACH
);
567 if (unlink(netns_path
) < 0) {
568 fprintf(stderr
, "Cannot remove namespace file \"%s\": %s\n",
569 netns_path
, strerror(errno
));
575 static int netns_delete(int argc
, char **argv
)
577 if (argc
< 1 && !do_all
) {
578 fprintf(stderr
, "No netns name specified\n");
583 return netns_foreach(on_netns_del
, NULL
);
585 return on_netns_del(argv
[0], NULL
);
588 static int create_netns_dir(void)
590 /* Create the base netns directory if it doesn't exist */
591 if (mkdir(NETNS_RUN_DIR
, S_IRWXU
|S_IRGRP
|S_IXGRP
|S_IROTH
|S_IXOTH
)) {
592 if (errno
!= EEXIST
) {
593 fprintf(stderr
, "mkdir %s failed: %s\n",
594 NETNS_RUN_DIR
, strerror(errno
));
602 static int netns_add(int argc
, char **argv
)
604 /* This function creates a new network namespace and
605 * a new mount namespace and bind them into a well known
606 * location in the filesystem based on the name provided.
608 * The mount namespace is created so that any necessary
609 * userspace tweaks like remounting /sys, or bind mounting
610 * a new /etc/resolv.conf can be shared between uers.
612 char netns_path
[PATH_MAX
];
615 int made_netns_run_dir_mount
= 0;
618 fprintf(stderr
, "No netns name specified\n");
623 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
625 if (create_netns_dir())
628 /* Make it possible for network namespace mounts to propagate between
629 * mount namespaces. This makes it likely that a unmounting a network
630 * namespace file in one namespace will unmount the network namespace
631 * file in all namespaces allowing the network namespace to be freed
634 while (mount("", NETNS_RUN_DIR
, "none", MS_SHARED
| MS_REC
, NULL
)) {
635 /* Fail unless we need to make the mount point */
636 if (errno
!= EINVAL
|| made_netns_run_dir_mount
) {
637 fprintf(stderr
, "mount --make-shared %s failed: %s\n",
638 NETNS_RUN_DIR
, strerror(errno
));
642 /* Upgrade NETNS_RUN_DIR to a mount point */
643 if (mount(NETNS_RUN_DIR
, NETNS_RUN_DIR
, "none", MS_BIND
| MS_REC
, NULL
)) {
644 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
645 NETNS_RUN_DIR
, NETNS_RUN_DIR
, strerror(errno
));
648 made_netns_run_dir_mount
= 1;
651 /* Create the filesystem state */
652 fd
= open(netns_path
, O_RDONLY
|O_CREAT
|O_EXCL
, 0);
654 fprintf(stderr
, "Cannot create namespace file \"%s\": %s\n",
655 netns_path
, strerror(errno
));
659 if (unshare(CLONE_NEWNET
) < 0) {
660 fprintf(stderr
, "Failed to create a new network namespace \"%s\": %s\n",
661 name
, strerror(errno
));
665 /* Bind the netns last so I can watch for it */
666 if (mount("/proc/self/ns/net", netns_path
, "none", MS_BIND
, NULL
) < 0) {
667 fprintf(stderr
, "Bind /proc/self/ns/net -> %s failed: %s\n",
668 netns_path
, strerror(errno
));
673 netns_delete(argc
, argv
);
677 static int set_netnsid_from_name(const char *name
, int nsid
)
684 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
685 .n
.nlmsg_flags
= NLM_F_REQUEST
,
686 .n
.nlmsg_type
= RTM_NEWNSID
,
687 .g
.rtgen_family
= AF_UNSPEC
,
691 fd
= netns_get_fd(name
);
695 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
696 addattr32(&req
.n
, 1024, NETNSA_NSID
, nsid
);
697 if (rtnl_talk(&rth
, &req
.n
, NULL
) < 0)
704 static int netns_set(int argc
, char **argv
)
706 char netns_path
[PATH_MAX
];
711 fprintf(stderr
, "No netns name specified\n");
715 fprintf(stderr
, "No nsid specified\n");
719 nsid
= atoi(argv
[1]);
721 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
722 netns
= open(netns_path
, O_RDONLY
| O_CLOEXEC
);
724 fprintf(stderr
, "Cannot open network namespace \"%s\": %s\n",
725 name
, strerror(errno
));
729 return set_netnsid_from_name(name
, nsid
);
732 static int netns_monitor(int argc
, char **argv
)
735 struct inotify_event
*event
;
740 fprintf(stderr
, "inotify_init failed: %s\n",
745 if (create_netns_dir())
748 if (inotify_add_watch(fd
, NETNS_RUN_DIR
, IN_CREATE
| IN_DELETE
) < 0) {
749 fprintf(stderr
, "inotify_add_watch failed: %s\n",
754 ssize_t len
= read(fd
, buf
, sizeof(buf
));
757 fprintf(stderr
, "read failed: %s\n",
761 for (event
= (struct inotify_event
*)buf
;
762 (char *)event
< &buf
[len
];
763 event
= (struct inotify_event
*)((char *)event
+ sizeof(*event
) + event
->len
)) {
764 if (event
->mask
& IN_CREATE
)
765 printf("add %s\n", event
->name
);
766 if (event
->mask
& IN_DELETE
)
767 printf("delete %s\n", event
->name
);
773 static int invalid_name(const char *name
)
775 return !*name
|| strlen(name
) > NAME_MAX
||
776 strchr(name
, '/') || !strcmp(name
, ".") || !strcmp(name
, "..");
779 int do_netns(int argc
, char **argv
)
781 netns_nsid_socket_init();
785 return netns_list(0, NULL
);
788 if (argc
> 1 && invalid_name(argv
[1])) {
789 fprintf(stderr
, "Invalid netns name \"%s\"\n", argv
[1]);
793 if ((matches(*argv
, "list") == 0) || (matches(*argv
, "show") == 0) ||
794 (matches(*argv
, "lst") == 0)) {
796 return netns_list(argc
-1, argv
+1);
799 if ((matches(*argv
, "list-id") == 0)) {
801 return netns_list_id(argc
-1, argv
+1);
804 if (matches(*argv
, "help") == 0)
807 if (matches(*argv
, "add") == 0)
808 return netns_add(argc
-1, argv
+1);
810 if (matches(*argv
, "set") == 0)
811 return netns_set(argc
-1, argv
+1);
813 if (matches(*argv
, "delete") == 0)
814 return netns_delete(argc
-1, argv
+1);
816 if (matches(*argv
, "identify") == 0)
817 return netns_identify(argc
-1, argv
+1);
819 if (matches(*argv
, "pids") == 0)
820 return netns_pids(argc
-1, argv
+1);
822 if (matches(*argv
, "exec") == 0)
823 return netns_exec(argc
-1, argv
+1);
825 if (matches(*argv
, "monitor") == 0)
826 return netns_monitor(argc
-1, argv
+1);
828 fprintf(stderr
, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv
);