journal-upload: add asserts that snprintf does not return an error
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Tue, 2 Oct 2018 10:46:31 +0000 (12:46 +0200)
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Tue, 2 Oct 2018 13:36:24 +0000 (15:36 +0200)
LGMT complains:
> The size argument of this snprintf call is derived from its return value,
> which may exceed the size of the buffer and overflow.

Let's make sure that r is non-negative. (This shouldn't occur unless the format
string is borked, so let's just add an assert.)
Then, let's reorder the comparison to avoid the potential overflow.

src/journal-remote/journal-upload-journal.c

index 3991dcb..205ce18 100644 (file)
@@ -34,7 +34,8 @@ static ssize_t write_entry(char *buf, size_t size, Uploader *u) {
 
                         r = snprintf(buf + pos, size - pos,
                                      "__CURSOR=%s\n", u->current_cursor);
-                        if (pos + r > size)
+                        assert(r >= 0);
+                        if ((size_t) r > size - pos)
                                 /* not enough space */
                                 return pos;
 
@@ -58,7 +59,8 @@ static ssize_t write_entry(char *buf, size_t size, Uploader *u) {
 
                         r = snprintf(buf + pos, size - pos,
                                      "__REALTIME_TIMESTAMP="USEC_FMT"\n", realtime);
-                        if (r + pos > size)
+                        assert(r >= 0);
+                        if ((size_t) r > size - pos)
                                 /* not enough space */
                                 return pos;
 
@@ -83,7 +85,8 @@ static ssize_t write_entry(char *buf, size_t size, Uploader *u) {
 
                         r = snprintf(buf + pos, size - pos,
                                      "__MONOTONIC_TIMESTAMP="USEC_FMT"\n", monotonic);
-                        if (r + pos > size)
+                        assert(r >= 0);
+                        if ((size_t) r > size - pos)
                                 /* not enough space */
                                 return pos;
 
@@ -108,7 +111,8 @@ static ssize_t write_entry(char *buf, size_t size, Uploader *u) {
 
                         r = snprintf(buf + pos, size - pos,
                                      "_BOOT_ID=%s\n", sd_id128_to_string(boot_id, sid));
-                        if (r + pos > size)
+                        assert(r >= 0);
+                        if ((size_t) r > size - pos)
                                 /* not enough space */
                                 return pos;