[ovs-dev] [strings 2/3] util: Don't read over 'size - 1' bytes of source string in ovs_strlcpy().

Ben Pfaff blp at nicira.com
Tue Feb 22 19:01:42 UTC 2011


The blind replacement of strncpy() by ovs_strlcpy() is risky because
strncpy() never reads more bytes from its source string than necessary to
write its destination string, but ovs_strlcpy() and the OpenBSD function
that inspired it both read the entire source string.  This avoids that
problem.

Given that change, we can use ovs_strlcpy() in a few more places, and
this commit does that too.
---
 lib/ofp-print.c   |    3 +--
 lib/route-table.c |    5 ++---
 lib/util.c        |    9 +++++----
 3 files changed, 8 insertions(+), 9 deletions(-)

diff --git a/lib/ofp-print.c b/lib/ofp-print.c
index 0e2cb0f..bf9bf82 100644
--- a/lib/ofp-print.c
+++ b/lib/ofp-print.c
@@ -1315,8 +1315,7 @@ ofp_print_ofpst_table_reply(struct ds *string, const struct ofp_header *oh,
 
     for (; n--; ts++) {
         char name[OFP_MAX_TABLE_NAME_LEN + 1];
-        strncpy(name, ts->name, sizeof name);
-        name[OFP_MAX_TABLE_NAME_LEN] = '\0';
+        ovs_strlcpy(name, ts->name, sizeof name);
 
         ds_put_format(string, "  %d: %-8s: ", ts->table_id, name);
         ds_put_format(string, "wild=0x%05"PRIx32", ", ntohl(ts->wildcards));
diff --git a/lib/route-table.c b/lib/route-table.c
index 64a5c1e..8212c54 100644
--- a/lib/route-table.c
+++ b/lib/route-table.c
@@ -111,7 +111,7 @@ route_table_get_name(ovs_be32 ip, char name[IFNAMSIZ])
 
         nn = name_node_lookup(ifindex);
         if (nn) {
-            strncpy(name, nn->ifname, IFNAMSIZ);
+            ovs_strlcpy(name, nn->ifname, IFNAMSIZ);
             return true;
         }
     }
@@ -445,8 +445,7 @@ name_table_reset(void)
 
             nn = xzalloc(sizeof *nn);
             nn->ifi_index = change.ifi_index;
-            strncpy(nn->ifname, change.ifname, IFNAMSIZ);
-            nn->ifname[IFNAMSIZ - 1] = '\0';
+            ovs_strlcpy(nn->ifname, change.ifname, IFNAMSIZ);
             hmap_insert(&name_map, &nn->node, hash_int(nn->ifi_index, 0));
         }
     }
diff --git a/lib/util.c b/lib/util.c
index 193efb9..1aa8271 100644
--- a/lib/util.c
+++ b/lib/util.c
@@ -137,14 +137,15 @@ xasprintf(const char *format, ...)
     return s;
 }
 
+/* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
+ * bytes from 'src' and doesn't return anything. */
 void
 ovs_strlcpy(char *dst, const char *src, size_t size)
 {
     if (size > 0) {
-        size_t n = strlen(src);
-        size_t n_copy = MIN(n, size - 1);
-        memcpy(dst, src, n_copy);
-        dst[n_copy] = '\0';
+        size_t len = strnlen(src, size - 1);
+        memcpy(dst, src, len);
+        dst[len] = '\0';
     }
 }
 
-- 
1.7.1





More information about the dev mailing list