]> git.proxmox.com Git - mirror_iproute2.git/blobdiff - ip/ipnetns.c
libnetlink: add size argument to rtnl_talk
[mirror_iproute2.git] / ip / ipnetns.c
index 90a496f7ad5acf3c841fab7035945053da282765..be0c473783c1743234fc228a6f23e337fa5b09f0 100644 (file)
 #include <errno.h>
 #include <unistd.h>
 #include <ctype.h>
+#include <linux/limits.h>
+
+#include <linux/net_namespace.h>
 
 #include "utils.h"
+#include "hlist.h"
 #include "ip_common.h"
+#include "namespace.h"
+
+static int usage(void)
+{
+       fprintf(stderr, "Usage: ip netns list\n");
+       fprintf(stderr, "       ip netns add NAME\n");
+       fprintf(stderr, "       ip netns set NAME NETNSID\n");
+       fprintf(stderr, "       ip [-all] netns delete [NAME]\n");
+       fprintf(stderr, "       ip netns identify [PID]\n");
+       fprintf(stderr, "       ip netns pids NAME\n");
+       fprintf(stderr, "       ip [-all] netns exec [NAME] cmd ...\n");
+       fprintf(stderr, "       ip netns monitor\n");
+       fprintf(stderr, "       ip netns list-id\n");
+       exit(-1);
+}
+
+/* This socket is used to get nsid */
+static struct rtnl_handle rtnsh = { .fd = -1 };
+
+static int have_rtnl_getnsid = -1;
+
+static int ipnetns_accept_msg(const struct sockaddr_nl *who,
+                             struct nlmsghdr *n, void *arg)
+{
+       struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(n);
 
-#define NETNS_RUN_DIR "/var/run/netns"
-#define NETNS_ETC_DIR "/etc/netns"
+       if (n->nlmsg_type == NLMSG_ERROR &&
+           (err->error == -EOPNOTSUPP || err->error == -EINVAL))
+               have_rtnl_getnsid = 0;
+       else
+               have_rtnl_getnsid = 1;
+       return -1;
+}
 
-#ifndef CLONE_NEWNET
-#define CLONE_NEWNET 0x40000000        /* New network namespace (lo, device, names sockets, etc) */
-#endif
+static int ipnetns_have_nsid(void)
+{
+       struct {
+               struct nlmsghdr n;
+               struct rtgenmsg g;
+               char            buf[1024];
+       } req;
+       int fd;
 
-#ifndef MNT_DETACH
-#define MNT_DETACH     0x00000002      /* Just detach from the tree */
-#endif /* MNT_DETACH */
+       if (have_rtnl_getnsid < 0) {
+               memset(&req, 0, sizeof(req));
+               req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
+               req.n.nlmsg_flags = NLM_F_REQUEST;
+               req.n.nlmsg_type = RTM_GETNSID;
+               req.g.rtgen_family = AF_UNSPEC;
 
-/* sys/mount.h may be out too old to have these */
-#ifndef MS_REC
-#define MS_REC         16384
-#endif
+               fd = open("/proc/self/ns/net", O_RDONLY);
+               if (fd < 0) {
+                       perror("open(\"/proc/self/ns/net\")");
+                       exit(1);
+               }
 
-#ifndef MS_SLAVE
-#define MS_SLAVE       (1 << 19)
-#endif
+               addattr32(&req.n, 1024, NETNSA_FD, fd);
 
-#ifndef MS_SHARED
-#define MS_SHARED      (1 << 20)
-#endif
+               if (rtnl_send(&rth, &req.n, req.n.nlmsg_len) < 0) {
+                       perror("request send failed");
+                       exit(1);
+               }
+               rtnl_listen(&rth, ipnetns_accept_msg, NULL);
+               close(fd);
+       }
 
-#ifndef HAVE_SETNS
-static int setns(int fd, int nstype)
+       return have_rtnl_getnsid;
+}
+
+static int get_netnsid_from_name(const char *name)
 {
-#ifdef __NR_setns
-       return syscall(__NR_setns, fd, nstype);
-#else
-       errno = ENOSYS;
+       struct {
+               struct nlmsghdr n;
+               struct rtgenmsg g;
+               char            buf[1024];
+       } req, answer;
+       struct rtattr *tb[NETNSA_MAX + 1];
+       struct rtgenmsg *rthdr;
+       int len, fd;
+
+       memset(&req, 0, sizeof(req));
+       req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
+       req.n.nlmsg_flags = NLM_F_REQUEST;
+       req.n.nlmsg_type = RTM_GETNSID;
+       req.g.rtgen_family = AF_UNSPEC;
+
+       fd = netns_get_fd(name);
+       if (fd < 0)
+               return fd;
+
+       addattr32(&req.n, 1024, NETNSA_FD, fd);
+       if (rtnl_talk(&rtnsh, &req.n, &answer.n, sizeof(answer)) < 0) {
+               close(fd);
+               return -2;
+       }
+       close(fd);
+
+       /* Validate message and parse attributes */
+       if (answer.n.nlmsg_type == NLMSG_ERROR)
+               return -1;
+
+       rthdr = NLMSG_DATA(&answer.n);
+       len = answer.n.nlmsg_len - NLMSG_SPACE(sizeof(*rthdr));
+       if (len < 0)
+               return -1;
+
+       parse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len);
+
+       if (tb[NETNSA_NSID])
+               return rta_getattr_u32(tb[NETNSA_NSID]);
+
        return -1;
-#endif
 }
-#endif /* HAVE_SETNS */
 
-static int usage(void)
+struct nsid_cache {
+       struct hlist_node       nsid_hash;
+       struct hlist_node       name_hash;
+       int                     nsid;
+       char                    name[NAME_MAX];
+};
+
+#define NSIDMAP_SIZE           128
+#define NSID_HASH_NSID(nsid)   (nsid & (NSIDMAP_SIZE - 1))
+#define NSID_HASH_NAME(name)   (namehash(name) & (NSIDMAP_SIZE - 1))
+
+static struct hlist_head       nsid_head[NSIDMAP_SIZE];
+static struct hlist_head       name_head[NSIDMAP_SIZE];
+
+static struct nsid_cache *netns_map_get_by_nsid(int nsid)
 {
-       fprintf(stderr, "Usage: ip netns list\n");
-       fprintf(stderr, "       ip netns add NAME\n");
-       fprintf(stderr, "       ip netns delete NAME\n");
-       fprintf(stderr, "       ip netns identify PID\n");
-       fprintf(stderr, "       ip netns pids NAME\n");
-       fprintf(stderr, "       ip netns exec NAME cmd ...\n");
-       fprintf(stderr, "       ip netns monitor\n");
-       exit(-1);
+       uint32_t h = NSID_HASH_NSID(nsid);
+       struct hlist_node *n;
+
+       hlist_for_each(n, &nsid_head[h]) {
+               struct nsid_cache *c = container_of(n, struct nsid_cache,
+                                                   nsid_hash);
+               if (c->nsid == nsid)
+                       return c;
+       }
+
+       return NULL;
 }
 
-int get_netns_fd(const char *name)
+static int netns_map_add(int nsid, char *name)
 {
-       char pathbuf[MAXPATHLEN];
-       const char *path, *ptr;
+       struct nsid_cache *c;
+       uint32_t h;
 
-       path = name;
-       ptr = strchr(name, '/');
-       if (!ptr) {
-               snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
-                       NETNS_RUN_DIR, name );
-               path = pathbuf;
+       if (netns_map_get_by_nsid(nsid) != NULL)
+               return -EEXIST;
+
+       c = malloc(sizeof(*c));
+       if (c == NULL) {
+               perror("malloc");
+               return -ENOMEM;
        }
-       return open(path, O_RDONLY);
+       c->nsid = nsid;
+       strcpy(c->name, name);
+
+       h = NSID_HASH_NSID(nsid);
+       hlist_add_head(&c->nsid_hash, &nsid_head[h]);
+
+       h = NSID_HASH_NAME(name);
+       hlist_add_head(&c->name_hash, &name_head[h]);
+
+       return 0;
 }
 
-static int netns_list(int argc, char **argv)
+static void netns_map_del(struct nsid_cache *c)
 {
+       hlist_del(&c->name_hash);
+       hlist_del(&c->nsid_hash);
+       free(c);
+}
+
+void netns_map_init(void)
+{
+       static int initialized;
        struct dirent *entry;
        DIR *dir;
+       int nsid;
+
+       if (initialized || !ipnetns_have_nsid())
+               return;
+
+       if (rtnl_open(&rtnsh, 0) < 0) {
+               fprintf(stderr, "Cannot open rtnetlink\n");
+               exit(1);
+       }
 
        dir = opendir(NETNS_RUN_DIR);
        if (!dir)
-               return 0;
+               return;
 
        while ((entry = readdir(dir)) != NULL) {
                if (strcmp(entry->d_name, ".") == 0)
                        continue;
                if (strcmp(entry->d_name, "..") == 0)
                        continue;
-               printf("%s\n", entry->d_name);
+               nsid = get_netnsid_from_name(entry->d_name);
+
+               if (nsid >= 0)
+                       netns_map_add(nsid, entry->d_name);
        }
        closedir(dir);
-       return 0;
+       initialized = 1;
 }
 
-static void bind_etc(const char *name)
+static int netns_get_name(int nsid, char *name)
 {
-       char etc_netns_path[MAXPATHLEN];
-       char netns_name[MAXPATHLEN];
-       char etc_name[MAXPATHLEN];
        struct dirent *entry;
        DIR *dir;
+       int id;
 
-       snprintf(etc_netns_path, sizeof(etc_netns_path), "%s/%s", NETNS_ETC_DIR, name);
-       dir = opendir(etc_netns_path);
+       dir = opendir(NETNS_RUN_DIR);
        if (!dir)
-               return;
+               return -ENOENT;
 
        while ((entry = readdir(dir)) != NULL) {
                if (strcmp(entry->d_name, ".") == 0)
                        continue;
                if (strcmp(entry->d_name, "..") == 0)
                        continue;
-               snprintf(netns_name, sizeof(netns_name), "%s/%s", etc_netns_path, entry->d_name);
-               snprintf(etc_name, sizeof(etc_name), "/etc/%s", entry->d_name);
-               if (mount(netns_name, etc_name, "none", MS_BIND, NULL) < 0) {
-                       fprintf(stderr, "Bind %s -> %s failed: %s\n",
-                               netns_name, etc_name, strerror(errno));
+               id = get_netnsid_from_name(entry->d_name);
+
+               if (nsid == id) {
+                       strcpy(name, entry->d_name);
+                       closedir(dir);
+                       return 0;
                }
        }
        closedir(dir);
+       return -ENOENT;
 }
 
-static int netns_exec(int argc, char **argv)
+int print_nsid(const struct sockaddr_nl *who, struct nlmsghdr *n, void *arg)
 {
-       /* Setup the proper environment for apps that are not netns
-        * aware, and execute a program in that environment.
-        */
-       const char *name, *cmd;
-       char net_path[MAXPATHLEN];
-       int netns;
+       struct rtgenmsg *rthdr = NLMSG_DATA(n);
+       struct rtattr *tb[NETNSA_MAX+1];
+       int len = n->nlmsg_len;
+       FILE *fp = (FILE *)arg;
+       struct nsid_cache *c;
+       char name[NAME_MAX];
+       int nsid;
+
+       if (n->nlmsg_type != RTM_NEWNSID && n->nlmsg_type != RTM_DELNSID)
+               return 0;
 
-       if (argc < 1) {
-               fprintf(stderr, "No netns name specified\n");
-               return -1;
-       }
-       if (argc < 2) {
-               fprintf(stderr, "No command specified\n");
+       len -= NLMSG_SPACE(sizeof(*rthdr));
+       if (len < 0) {
+               fprintf(stderr, "BUG: wrong nlmsg len %d in %s\n", len,
+                       __func__);
                return -1;
        }
 
-       name = argv[0];
-       cmd = argv[1];
-       snprintf(net_path, sizeof(net_path), "%s/%s", NETNS_RUN_DIR, name);
-       netns = open(net_path, O_RDONLY | O_CLOEXEC);
-       if (netns < 0) {
-               fprintf(stderr, "Cannot open network namespace \"%s\": %s\n",
-                       name, strerror(errno));
+       parse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len);
+       if (tb[NETNSA_NSID] == NULL) {
+               fprintf(stderr, "BUG: NETNSA_NSID is missing %s\n", __func__);
                return -1;
        }
 
-       if (setns(netns, CLONE_NEWNET) < 0) {
-               fprintf(stderr, "setting the network namespace \"%s\" failed: %s\n",
-                       name, strerror(errno));
-               return -1;
-       }
+       if (n->nlmsg_type == RTM_DELNSID)
+               fprintf(fp, "Deleted ");
 
-       if (unshare(CLONE_NEWNS) < 0) {
-               fprintf(stderr, "unshare failed: %s\n", strerror(errno));
-               return -1;
+       nsid = rta_getattr_u32(tb[NETNSA_NSID]);
+       fprintf(fp, "nsid %u ", nsid);
+
+       c = netns_map_get_by_nsid(nsid);
+       if (c != NULL) {
+               fprintf(fp, "(iproute2 netns name: %s)", c->name);
+               netns_map_del(c);
        }
-       /* Don't let any mounts propagate back to the parent */
-       if (mount("", "/", "none", MS_SLAVE | MS_REC, NULL)) {
-               fprintf(stderr, "\"mount --make-rslave /\" failed: %s\n",
-                       strerror(errno));
-               return -1;
+
+       /* During 'ip monitor nsid', no chance to have new nsid in cache. */
+       if (c == NULL && n->nlmsg_type == RTM_NEWNSID)
+               if (netns_get_name(nsid, name) == 0) {
+                       fprintf(fp, "(iproute2 netns name: %s)", name);
+                       netns_map_add(nsid, name);
+               }
+
+       fprintf(fp, "\n");
+       fflush(fp);
+       return 0;
+}
+
+static int netns_list_id(int argc, char **argv)
+{
+       if (!ipnetns_have_nsid()) {
+               fprintf(stderr,
+                       "RTM_GETNSID is not supported by the kernel.\n");
+               return -ENOTSUP;
        }
-       /* Mount a version of /sys that describes the network namespace */
-       if (umount2("/sys", MNT_DETACH) < 0) {
-               fprintf(stderr, "umount of /sys failed: %s\n", strerror(errno));
-               return -1;
+
+       if (rtnl_wilddump_request(&rth, AF_UNSPEC, RTM_GETNSID) < 0) {
+               perror("Cannot send dump request");
+               exit(1);
        }
-       if (mount(name, "/sys", "sysfs", 0, NULL) < 0) {
-               fprintf(stderr, "mount of /sys failed: %s\n",strerror(errno));
-               return -1;
+       if (rtnl_dump_filter(&rth, print_nsid, stdout) < 0) {
+               fprintf(stderr, "Dump terminated\n");
+               exit(1);
        }
+       return 0;
+}
 
-       /* Setup bind mounts for config files in /etc */
-       bind_etc(name);
+static int netns_list(int argc, char **argv)
+{
+       struct dirent *entry;
+       DIR *dir;
+       int id;
 
-       fflush(stdout);
+       dir = opendir(NETNS_RUN_DIR);
+       if (!dir)
+               return 0;
+
+       while ((entry = readdir(dir)) != NULL) {
+               if (strcmp(entry->d_name, ".") == 0)
+                       continue;
+               if (strcmp(entry->d_name, "..") == 0)
+                       continue;
+               printf("%s", entry->d_name);
+               if (ipnetns_have_nsid()) {
+                       id = get_netnsid_from_name(entry->d_name);
+                       if (id >= 0)
+                               printf(" (id: %d)", id);
+               }
+               printf("\n");
+       }
+       closedir(dir);
+       return 0;
+}
 
-       if (batch_mode) {
+static int cmd_exec(const char *cmd, char **argv, bool do_fork)
+{
+       fflush(stdout);
+       if (do_fork) {
                int status;
                pid_t pid;
 
@@ -206,23 +373,56 @@ static int netns_exec(int argc, char **argv)
                        }
 
                        if (WIFEXITED(status)) {
-                               /* ip must return the status of the child,
-                                * but do_cmd() will add a minus to this,
-                                * so let's add another one here to cancel it.
-                                */
-                               return -WEXITSTATUS(status);
+                               return WEXITSTATUS(status);
                        }
 
                        exit(1);
                }
        }
 
-       if (execvp(cmd, argv + 1)  < 0)
+       if (execvp(cmd, argv)  < 0)
                fprintf(stderr, "exec of \"%s\" failed: %s\n",
-                       cmd, strerror(errno));
+                               cmd, strerror(errno));
        _exit(1);
 }
 
+static int on_netns_exec(char *nsname, void *arg)
+{
+       char **argv = arg;
+       cmd_exec(argv[1], argv + 1, true);
+       return 0;
+}
+
+static int netns_exec(int argc, char **argv)
+{
+       /* Setup the proper environment for apps that are not netns
+        * aware, and execute a program in that environment.
+        */
+       const char *cmd;
+
+       if (argc < 1 && !do_all) {
+               fprintf(stderr, "No netns name specified\n");
+               return -1;
+       }
+       if ((argc < 2 && !do_all) || (argc < 1 && do_all)) {
+               fprintf(stderr, "No command specified\n");
+               return -1;
+       }
+
+       if (do_all)
+               return do_each_netns(on_netns_exec, --argv, 1);
+
+       if (netns_switch(argv[0]))
+               return -1;
+
+       /* ip must return the status of the child,
+        * but do_cmd() will add a minus to this,
+        * so let's add another one here to cancel it.
+        */
+       cmd = argv[1];
+       return -cmd_exec(cmd, argv + 1, !!batch_mode);
+}
+
 static int is_pid(const char *str)
 {
        int ch;
@@ -299,19 +499,17 @@ static int netns_identify(int argc, char **argv)
        struct dirent *entry;
 
        if (argc < 1) {
-               fprintf(stderr, "No pid specified\n");
-               return -1;
-       }
-       if (argc > 1) {
+               pidstr = "self";
+       } else if (argc > 1) {
                fprintf(stderr, "extra arguments specified\n");
                return -1;
-       }
-       pidstr = argv[0];
-
-       if (!is_pid(pidstr)) {
-               fprintf(stderr, "Specified string '%s' is not a pid\n",
-                       pidstr);
-               return -1;
+       } else {
+               pidstr = argv[0];
+               if (!is_pid(pidstr)) {
+                       fprintf(stderr, "Specified string '%s' is not a pid\n",
+                                       pidstr);
+                       return -1;
+               }
        }
 
        snprintf(net_path, sizeof(net_path), "/proc/%s/ns/net", pidstr);
@@ -362,18 +560,11 @@ static int netns_identify(int argc, char **argv)
 
 }
 
-static int netns_delete(int argc, char **argv)
+static int on_netns_del(char *nsname, void *arg)
 {
-       const char *name;
        char netns_path[MAXPATHLEN];
 
-       if (argc < 1) {
-               fprintf(stderr, "No netns name specified\n");
-               return -1;
-       }
-
-       name = argv[0];
-       snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, name);
+       snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, nsname);
        umount2(netns_path, MNT_DETACH);
        if (unlink(netns_path) < 0) {
                fprintf(stderr, "Cannot remove namespace file \"%s\": %s\n",
@@ -383,6 +574,19 @@ static int netns_delete(int argc, char **argv)
        return 0;
 }
 
+static int netns_delete(int argc, char **argv)
+{
+       if (argc < 1 && !do_all) {
+               fprintf(stderr, "No netns name specified\n");
+               return -1;
+       }
+
+       if (do_all)
+               return netns_foreach(on_netns_del, NULL);
+
+       return on_netns_del(argv[0], NULL);
+}
+
 static int create_netns_dir(void)
 {
        /* Create the base netns directory if it doesn't exist */
@@ -472,6 +676,61 @@ out_delete:
        return -1;
 }
 
+static int set_netnsid_from_name(const char *name, int nsid)
+{
+       struct {
+               struct nlmsghdr n;
+               struct rtgenmsg g;
+               char            buf[1024];
+       } req;
+       int fd, err = 0;
+
+       memset(&req, 0, sizeof(req));
+       req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
+       req.n.nlmsg_flags = NLM_F_REQUEST;
+       req.n.nlmsg_type = RTM_NEWNSID;
+       req.g.rtgen_family = AF_UNSPEC;
+
+       fd = netns_get_fd(name);
+       if (fd < 0)
+               return fd;
+
+       addattr32(&req.n, 1024, NETNSA_FD, fd);
+       addattr32(&req.n, 1024, NETNSA_NSID, nsid);
+       if (rtnl_talk(&rth, &req.n, NULL, 0) < 0)
+               err = -2;
+
+       close(fd);
+       return err;
+}
+
+static int netns_set(int argc, char **argv)
+{
+       char netns_path[MAXPATHLEN];
+       const char *name;
+       int netns, nsid;
+
+       if (argc < 1) {
+               fprintf(stderr, "No netns name specified\n");
+               return -1;
+       }
+       if (argc < 2) {
+               fprintf(stderr, "No nsid specified\n");
+               return -1;
+       }
+       name = argv[0];
+       nsid = atoi(argv[1]);
+
+       snprintf(netns_path, sizeof(netns_path), "%s/%s", NETNS_RUN_DIR, name);
+       netns = open(netns_path, O_RDONLY | O_CLOEXEC);
+       if (netns < 0) {
+               fprintf(stderr, "Cannot open network namespace \"%s\": %s\n",
+                       name, strerror(errno));
+               return -1;
+       }
+
+       return set_netnsid_from_name(name, nsid);
+}
 
 static int netns_monitor(int argc, char **argv)
 {
@@ -514,6 +773,8 @@ static int netns_monitor(int argc, char **argv)
 
 int do_netns(int argc, char **argv)
 {
+       netns_map_init();
+
        if (argc < 1)
                return netns_list(0, NULL);
 
@@ -521,12 +782,18 @@ int do_netns(int argc, char **argv)
            (matches(*argv, "lst") == 0))
                return netns_list(argc-1, argv+1);
 
+       if ((matches(*argv, "list-id") == 0))
+               return netns_list_id(argc-1, argv+1);
+
        if (matches(*argv, "help") == 0)
                return usage();
 
        if (matches(*argv, "add") == 0)
                return netns_add(argc-1, argv+1);
 
+       if (matches(*argv, "set") == 0)
+               return netns_set(argc-1, argv+1);
+
        if (matches(*argv, "delete") == 0)
                return netns_delete(argc-1, argv+1);