]>
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 rtattr
*tb
[NETNSA_MAX
+ 1];
105 struct rtgenmsg
*rthdr
;
108 fd
= netns_get_fd(name
);
112 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
113 if (rtnl_talk(&rtnsh
, &req
.n
, &answer
.n
, sizeof(answer
)) < 0) {
119 /* Validate message and parse attributes */
120 if (answer
.n
.nlmsg_type
== NLMSG_ERROR
)
123 rthdr
= NLMSG_DATA(&answer
.n
);
124 len
= answer
.n
.nlmsg_len
- NLMSG_SPACE(sizeof(*rthdr
));
128 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
131 return rta_getattr_u32(tb
[NETNSA_NSID
]);
137 struct hlist_node nsid_hash
;
138 struct hlist_node name_hash
;
143 #define NSIDMAP_SIZE 128
144 #define NSID_HASH_NSID(nsid) (nsid & (NSIDMAP_SIZE - 1))
145 #define NSID_HASH_NAME(name) (namehash(name) & (NSIDMAP_SIZE - 1))
147 static struct hlist_head nsid_head
[NSIDMAP_SIZE
];
148 static struct hlist_head name_head
[NSIDMAP_SIZE
];
150 static struct nsid_cache
*netns_map_get_by_nsid(int nsid
)
152 uint32_t h
= NSID_HASH_NSID(nsid
);
153 struct hlist_node
*n
;
155 hlist_for_each(n
, &nsid_head
[h
]) {
156 struct nsid_cache
*c
= container_of(n
, struct nsid_cache
,
165 static int netns_map_add(int nsid
, const char *name
)
167 struct nsid_cache
*c
;
170 if (netns_map_get_by_nsid(nsid
) != NULL
)
173 c
= malloc(sizeof(*c
) + strlen(name
) + 1);
179 strcpy(c
->name
, name
);
181 h
= NSID_HASH_NSID(nsid
);
182 hlist_add_head(&c
->nsid_hash
, &nsid_head
[h
]);
184 h
= NSID_HASH_NAME(name
);
185 hlist_add_head(&c
->name_hash
, &name_head
[h
]);
190 static void netns_map_del(struct nsid_cache
*c
)
192 hlist_del(&c
->name_hash
);
193 hlist_del(&c
->nsid_hash
);
197 void netns_nsid_socket_init(void)
199 if (rtnsh
.fd
> -1 || !ipnetns_have_nsid())
202 if (rtnl_open(&rtnsh
, 0) < 0) {
203 fprintf(stderr
, "Cannot open rtnetlink\n");
209 void netns_map_init(void)
211 static int initialized
;
212 struct dirent
*entry
;
216 if (initialized
|| !ipnetns_have_nsid())
219 dir
= opendir(NETNS_RUN_DIR
);
223 while ((entry
= readdir(dir
)) != NULL
) {
224 if (strcmp(entry
->d_name
, ".") == 0)
226 if (strcmp(entry
->d_name
, "..") == 0)
228 nsid
= get_netnsid_from_name(entry
->d_name
);
231 netns_map_add(nsid
, entry
->d_name
);
237 static int netns_get_name(int nsid
, char *name
)
239 struct dirent
*entry
;
243 dir
= opendir(NETNS_RUN_DIR
);
247 while ((entry
= readdir(dir
)) != NULL
) {
248 if (strcmp(entry
->d_name
, ".") == 0)
250 if (strcmp(entry
->d_name
, "..") == 0)
252 id
= get_netnsid_from_name(entry
->d_name
);
255 strcpy(name
, entry
->d_name
);
264 int print_nsid(const struct sockaddr_nl
*who
, struct nlmsghdr
*n
, void *arg
)
266 struct rtgenmsg
*rthdr
= NLMSG_DATA(n
);
267 struct rtattr
*tb
[NETNSA_MAX
+1];
268 int len
= n
->nlmsg_len
;
269 FILE *fp
= (FILE *)arg
;
270 struct nsid_cache
*c
;
274 if (n
->nlmsg_type
!= RTM_NEWNSID
&& n
->nlmsg_type
!= RTM_DELNSID
)
277 len
-= NLMSG_SPACE(sizeof(*rthdr
));
279 fprintf(stderr
, "BUG: wrong nlmsg len %d in %s\n", len
,
284 parse_rtattr(tb
, NETNSA_MAX
, NETNS_RTA(rthdr
), len
);
285 if (tb
[NETNSA_NSID
] == NULL
) {
286 fprintf(stderr
, "BUG: NETNSA_NSID is missing %s\n", __func__
);
290 if (n
->nlmsg_type
== RTM_DELNSID
)
291 fprintf(fp
, "Deleted ");
293 nsid
= rta_getattr_u32(tb
[NETNSA_NSID
]);
294 fprintf(fp
, "nsid %u ", nsid
);
296 c
= netns_map_get_by_nsid(nsid
);
298 fprintf(fp
, "(iproute2 netns name: %s)", c
->name
);
302 /* During 'ip monitor nsid', no chance to have new nsid in cache. */
303 if (c
== NULL
&& n
->nlmsg_type
== RTM_NEWNSID
)
304 if (netns_get_name(nsid
, name
) == 0) {
305 fprintf(fp
, "(iproute2 netns name: %s)", name
);
306 netns_map_add(nsid
, name
);
314 static int netns_list_id(int argc
, char **argv
)
316 if (!ipnetns_have_nsid()) {
318 "RTM_GETNSID is not supported by the kernel.\n");
322 if (rtnl_wilddump_request(&rth
, AF_UNSPEC
, RTM_GETNSID
) < 0) {
323 perror("Cannot send dump request");
326 if (rtnl_dump_filter(&rth
, print_nsid
, stdout
) < 0) {
327 fprintf(stderr
, "Dump terminated\n");
333 static int netns_list(int argc
, char **argv
)
335 struct dirent
*entry
;
339 dir
= opendir(NETNS_RUN_DIR
);
343 while ((entry
= readdir(dir
)) != NULL
) {
344 if (strcmp(entry
->d_name
, ".") == 0)
346 if (strcmp(entry
->d_name
, "..") == 0)
348 printf("%s", entry
->d_name
);
349 if (ipnetns_have_nsid()) {
350 id
= get_netnsid_from_name(entry
->d_name
);
352 printf(" (id: %d)", id
);
360 static int on_netns_exec(char *nsname
, void *arg
)
364 cmd_exec(argv
[1], argv
+ 1, true);
368 static int netns_exec(int argc
, char **argv
)
370 /* Setup the proper environment for apps that are not netns
371 * aware, and execute a program in that environment.
375 if (argc
< 1 && !do_all
) {
376 fprintf(stderr
, "No netns name specified\n");
379 if ((argc
< 2 && !do_all
) || (argc
< 1 && do_all
)) {
380 fprintf(stderr
, "No command specified\n");
385 return do_each_netns(on_netns_exec
, --argv
, 1);
387 if (netns_switch(argv
[0]))
390 /* we just changed namespaces. clear any vrf association
391 * with prior namespace before exec'ing command
395 /* ip must return the status of the child,
396 * but do_cmd() will add a minus to this,
397 * so let's add another one here to cancel it.
400 return -cmd_exec(cmd
, argv
+ 1, !!batch_mode
);
403 static int is_pid(const char *str
)
407 for (; (ch
= *str
); str
++) {
414 static int netns_pids(int argc
, char **argv
)
417 char net_path
[PATH_MAX
];
421 struct dirent
*entry
;
424 fprintf(stderr
, "No netns name specified\n");
428 fprintf(stderr
, "extra arguments specified\n");
433 snprintf(net_path
, sizeof(net_path
), "%s/%s", NETNS_RUN_DIR
, name
);
434 netns
= open(net_path
, O_RDONLY
);
436 fprintf(stderr
, "Cannot open network namespace: %s\n",
440 if (fstat(netns
, &netst
) < 0) {
441 fprintf(stderr
, "Stat of netns failed: %s\n",
445 dir
= opendir("/proc/");
447 fprintf(stderr
, "Open of /proc failed: %s\n",
451 while ((entry
= readdir(dir
))) {
452 char pid_net_path
[PATH_MAX
];
455 if (!is_pid(entry
->d_name
))
457 snprintf(pid_net_path
, sizeof(pid_net_path
), "/proc/%s/ns/net",
459 if (stat(pid_net_path
, &st
) != 0)
461 if ((st
.st_dev
== netst
.st_dev
) &&
462 (st
.st_ino
== netst
.st_ino
)) {
463 printf("%s\n", entry
->d_name
);
471 int netns_identify_pid(const char *pidstr
, char *name
, int len
)
473 char net_path
[PATH_MAX
];
477 struct dirent
*entry
;
481 snprintf(net_path
, sizeof(net_path
), "/proc/%s/ns/net", pidstr
);
482 netns
= open(net_path
, O_RDONLY
);
484 fprintf(stderr
, "Cannot open network namespace: %s\n",
488 if (fstat(netns
, &netst
) < 0) {
489 fprintf(stderr
, "Stat of netns failed: %s\n",
493 dir
= opendir(NETNS_RUN_DIR
);
495 /* Succeed treat a missing directory as an empty directory */
499 fprintf(stderr
, "Failed to open directory %s:%s\n",
500 NETNS_RUN_DIR
, strerror(errno
));
504 while ((entry
= readdir(dir
))) {
505 char name_path
[PATH_MAX
];
508 if (strcmp(entry
->d_name
, ".") == 0)
510 if (strcmp(entry
->d_name
, "..") == 0)
513 snprintf(name_path
, sizeof(name_path
), "%s/%s", NETNS_RUN_DIR
,
516 if (stat(name_path
, &st
) != 0)
519 if ((st
.st_dev
== netst
.st_dev
) &&
520 (st
.st_ino
== netst
.st_ino
)) {
521 strncpy(name
, entry
->d_name
, len
- 1);
522 name
[len
- 1] = '\0';
530 static int netns_identify(int argc
, char **argv
)
538 } else if (argc
> 1) {
539 fprintf(stderr
, "extra arguments specified\n");
543 if (!is_pid(pidstr
)) {
544 fprintf(stderr
, "Specified string '%s' is not a pid\n",
550 rc
= netns_identify_pid(pidstr
, name
, sizeof(name
));
552 printf("%s\n", name
);
557 static int on_netns_del(char *nsname
, void *arg
)
559 char netns_path
[PATH_MAX
];
561 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, nsname
);
562 umount2(netns_path
, MNT_DETACH
);
563 if (unlink(netns_path
) < 0) {
564 fprintf(stderr
, "Cannot remove namespace file \"%s\": %s\n",
565 netns_path
, strerror(errno
));
571 static int netns_delete(int argc
, char **argv
)
573 if (argc
< 1 && !do_all
) {
574 fprintf(stderr
, "No netns name specified\n");
579 return netns_foreach(on_netns_del
, NULL
);
581 return on_netns_del(argv
[0], NULL
);
584 static int create_netns_dir(void)
586 /* Create the base netns directory if it doesn't exist */
587 if (mkdir(NETNS_RUN_DIR
, S_IRWXU
|S_IRGRP
|S_IXGRP
|S_IROTH
|S_IXOTH
)) {
588 if (errno
!= EEXIST
) {
589 fprintf(stderr
, "mkdir %s failed: %s\n",
590 NETNS_RUN_DIR
, strerror(errno
));
598 static int netns_add(int argc
, char **argv
)
600 /* This function creates a new network namespace and
601 * a new mount namespace and bind them into a well known
602 * location in the filesystem based on the name provided.
604 * The mount namespace is created so that any necessary
605 * userspace tweaks like remounting /sys, or bind mounting
606 * a new /etc/resolv.conf can be shared between uers.
608 char netns_path
[PATH_MAX
];
611 int made_netns_run_dir_mount
= 0;
614 fprintf(stderr
, "No netns name specified\n");
619 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
621 if (create_netns_dir())
624 /* Make it possible for network namespace mounts to propagate between
625 * mount namespaces. This makes it likely that a unmounting a network
626 * namespace file in one namespace will unmount the network namespace
627 * file in all namespaces allowing the network namespace to be freed
630 while (mount("", NETNS_RUN_DIR
, "none", MS_SHARED
| MS_REC
, NULL
)) {
631 /* Fail unless we need to make the mount point */
632 if (errno
!= EINVAL
|| made_netns_run_dir_mount
) {
633 fprintf(stderr
, "mount --make-shared %s failed: %s\n",
634 NETNS_RUN_DIR
, strerror(errno
));
638 /* Upgrade NETNS_RUN_DIR to a mount point */
639 if (mount(NETNS_RUN_DIR
, NETNS_RUN_DIR
, "none", MS_BIND
, NULL
)) {
640 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
641 NETNS_RUN_DIR
, NETNS_RUN_DIR
, strerror(errno
));
644 made_netns_run_dir_mount
= 1;
647 /* Create the filesystem state */
648 fd
= open(netns_path
, O_RDONLY
|O_CREAT
|O_EXCL
, 0);
650 fprintf(stderr
, "Cannot create namespace file \"%s\": %s\n",
651 netns_path
, strerror(errno
));
655 if (unshare(CLONE_NEWNET
) < 0) {
656 fprintf(stderr
, "Failed to create a new network namespace \"%s\": %s\n",
657 name
, strerror(errno
));
661 /* Bind the netns last so I can watch for it */
662 if (mount("/proc/self/ns/net", netns_path
, "none", MS_BIND
, NULL
) < 0) {
663 fprintf(stderr
, "Bind /proc/self/ns/net -> %s failed: %s\n",
664 netns_path
, strerror(errno
));
669 netns_delete(argc
, argv
);
673 static int set_netnsid_from_name(const char *name
, int nsid
)
680 .n
.nlmsg_len
= NLMSG_LENGTH(sizeof(struct rtgenmsg
)),
681 .n
.nlmsg_flags
= NLM_F_REQUEST
,
682 .n
.nlmsg_type
= RTM_NEWNSID
,
683 .g
.rtgen_family
= AF_UNSPEC
,
687 fd
= netns_get_fd(name
);
691 addattr32(&req
.n
, 1024, NETNSA_FD
, fd
);
692 addattr32(&req
.n
, 1024, NETNSA_NSID
, nsid
);
693 if (rtnl_talk(&rth
, &req
.n
, NULL
, 0) < 0)
700 static int netns_set(int argc
, char **argv
)
702 char netns_path
[PATH_MAX
];
707 fprintf(stderr
, "No netns name specified\n");
711 fprintf(stderr
, "No nsid specified\n");
715 nsid
= atoi(argv
[1]);
717 snprintf(netns_path
, sizeof(netns_path
), "%s/%s", NETNS_RUN_DIR
, name
);
718 netns
= open(netns_path
, O_RDONLY
| O_CLOEXEC
);
720 fprintf(stderr
, "Cannot open network namespace \"%s\": %s\n",
721 name
, strerror(errno
));
725 return set_netnsid_from_name(name
, nsid
);
728 static int netns_monitor(int argc
, char **argv
)
731 struct inotify_event
*event
;
736 fprintf(stderr
, "inotify_init failed: %s\n",
741 if (create_netns_dir())
744 if (inotify_add_watch(fd
, NETNS_RUN_DIR
, IN_CREATE
| IN_DELETE
) < 0) {
745 fprintf(stderr
, "inotify_add_watch failed: %s\n",
750 ssize_t len
= read(fd
, buf
, sizeof(buf
));
753 fprintf(stderr
, "read failed: %s\n",
757 for (event
= (struct inotify_event
*)buf
;
758 (char *)event
< &buf
[len
];
759 event
= (struct inotify_event
*)((char *)event
+ sizeof(*event
) + event
->len
)) {
760 if (event
->mask
& IN_CREATE
)
761 printf("add %s\n", event
->name
);
762 if (event
->mask
& IN_DELETE
)
763 printf("delete %s\n", event
->name
);
769 static int invalid_name(const char *name
)
771 return strchr(name
, '/') || !strcmp(name
, ".") || !strcmp(name
, "..");
774 int do_netns(int argc
, char **argv
)
776 netns_nsid_socket_init();
780 return netns_list(0, NULL
);
783 if (argc
> 1 && invalid_name(argv
[1])) {
784 fprintf(stderr
, "Invalid netns name \"%s\"\n", argv
[1]);
788 if ((matches(*argv
, "list") == 0) || (matches(*argv
, "show") == 0) ||
789 (matches(*argv
, "lst") == 0)) {
791 return netns_list(argc
-1, argv
+1);
794 if ((matches(*argv
, "list-id") == 0)) {
796 return netns_list_id(argc
-1, argv
+1);
799 if (matches(*argv
, "help") == 0)
802 if (matches(*argv
, "add") == 0)
803 return netns_add(argc
-1, argv
+1);
805 if (matches(*argv
, "set") == 0)
806 return netns_set(argc
-1, argv
+1);
808 if (matches(*argv
, "delete") == 0)
809 return netns_delete(argc
-1, argv
+1);
811 if (matches(*argv
, "identify") == 0)
812 return netns_identify(argc
-1, argv
+1);
814 if (matches(*argv
, "pids") == 0)
815 return netns_pids(argc
-1, argv
+1);
817 if (matches(*argv
, "exec") == 0)
818 return netns_exec(argc
-1, argv
+1);
820 if (matches(*argv
, "monitor") == 0)
821 return netns_monitor(argc
-1, argv
+1);
823 fprintf(stderr
, "Command \"%s\" is unknown, try \"ip netns help\".\n", *argv
);