Skip to contentSkip to conversation

nbd: Avoid off-by-one in long export name truncation

PATCH In review Eric Blake 2 participants 2 messages Jun 22, 2020 – Jun 23, 2020 Block layer

lore
Share & tools
lore

Eric Blake

author
#0 lore raw

PATCH 1/1 nbd: Avoid off-by-one in long export name truncation

When snprintf returns the same value as the buffer size, the final byte was truncated to ensure a NUL terminator. Fortunately, such long export names are unusual enough, with no real impact other than what is displayed to the user.

Fixes 5c86bdf12089
---
 block/nbd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
block/nbd.c +1 -1
index eed160c5cda1..8301fcac0589 100644
@@ -2009,7 +2009,7 @@ static void nbd_refresh_filename(BlockDriverState *bs)
         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
                        "nbd://%s:%s", host, port);
     }
-    if (len > sizeof(bs->exact_filename)) {
+    if (len >= sizeof(bs->exact_filename)) {
         /* Name is too long to represent exactly, so leave it empty. */
         bs->exact_filename[0] = '\0';
     }
Signature · 1 line
2.27.0
Reviewed-by on v1 1/1
#1 lore raw
Quoted 6 lines · Eric Blake

When snprintf returns the same value as the buffer size, the final byte was truncated to ensure a NUL terminator. Fortunately, such long export names are unusual enough, with no real impact other than what is displayed to the user.

Fixes 5c86bdf12089

Oh, I remember myself checking snprintf spec when reviewing this, but still I missed this thing :(

Quoted 2 lines
Quoted 10 lines
---
  block/nbd.c | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)
block/nbd.c +0 -0
index eed160c5cda1..8301fcac0589 100644

block/nbd.c static void nbd_refresh_filename(BlockDriverState *bs) · line 2015

Quoted 8 lines
block/nbd.c +1 -1
@@ -2009,7 +2009,7 @@ static void nbd_refresh_filename(BlockDriverState *bs)
          len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
                         "nbd://%s:%s", host, port);
      }
-    if (len > sizeof(bs->exact_filename)) {
+    if (len >= sizeof(bs->exact_filename)) {
          /* Name is too long to represent exactly, so leave it empty. */
          bs->exact_filename[0] = '\0';
      }

Hmm, interesting, that in case of len=0 (no one branch was executed from previous if-else-if, which seems possible) we do nothing. Shouldn't this if actually be if (!len || len >= sizeof(bs->exact_filename)) {
/* Name is too long or we have nothing to report */ bs->exact_filename[0] = '\0';
}

Probably not, as bdrv_refresh_filename() does it anyway prior to calling drv->bdrv_refresh_filename().

Signature · 2 lines
Best regards,
Vladimir