]> git.ipfire.org Git - thirdparty/lxc.git/commitdiff
Improve efficiency of lxc_ifname_alnum_case_sensitive 3487/head
authorSam Boyles <sam.boyles42@gmail.com>
Fri, 17 Jul 2020 02:26:51 +0000 (14:26 +1200)
committerGitHub <noreply@github.com>
Fri, 17 Jul 2020 02:26:51 +0000 (14:26 +1200)
To detect if a newly generated interface name is a duplicate of an existing interface lxc_ifname_alnum_case_sensitive() currently gets a list of all interfaces using netns_getifaddrs(). When the system has a small number of interfaces this works fine, however when there are thousands or tens of thousands of interfaces this quickly becomes less than optimal.

As we only need to check if an interface name exists, and do not need the detailed information about the interfaces provided by netns_getifaddrs(), we can instead use the if_nametoindex() function, which is much more efficient.

Signed-off-by: Sam Boyles <sam.boyles@alliedtelesis.co.nz>
src/lxc/network.c

index aa8e1d157f6e20208fd909ab56d699f54a0265eb..5454560ab96b4ac4001d825a1b43049c49b5b00b 100644 (file)
@@ -2754,9 +2754,7 @@ static const char padchar[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM
 char *lxc_ifname_alnum_case_sensitive(char *template)
 {
        int ret;
-       struct netns_ifaddrs *ifa, *ifaddr;
        char name[IFNAMSIZ];
-       bool exists = false;
        size_t i = 0;
 #ifdef HAVE_RAND_R
        unsigned int seed;
@@ -2770,18 +2768,11 @@ char *lxc_ifname_alnum_case_sensitive(char *template)
        if (strlen(template) >= IFNAMSIZ)
                return NULL;
 
-       /* Get all the network interfaces. */
-       ret = netns_getifaddrs(&ifaddr, -1, &(bool){false});
-       if (ret < 0)
-               return log_error_errno(NULL, errno, "Failed to get network interfaces");
-
        /* Generate random names until we find one that doesn't exist. */
        for (;;) {
                name[0] = '\0';
                (void)strlcpy(name, template, IFNAMSIZ);
 
-               exists = false;
-
                for (i = 0; i < strlen(name); i++) {
                        if (name[i] == 'X') {
 #ifdef HAVE_RAND_R
@@ -2792,18 +2783,11 @@ char *lxc_ifname_alnum_case_sensitive(char *template)
                        }
                }
 
-               for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
-                       if (!strcmp(ifa->ifa_name, name)) {
-                               exists = true;
-                               break;
-                       }
-               }
-
-               if (!exists)
+               if (if_nametoindex(name) == 0) {
                        break;
+               }
        }
 
-       netns_freeifaddrs(ifaddr);
        (void)strlcpy(template, name, strlen(template) + 1);
 
        return template;