diff mbox

[libnftnl,1/2] utils: ensure \0 is in place in nft_fprintf()

Message ID 20140825130221.23329.86583.stgit@nfdev.cica.es
State Not Applicable
Delegated to: Pablo Neira
Headers show

Commit Message

Arturo Borrero Aug. 25, 2014, 1:02 p.m. UTC
We must make sure the buffer contains a \0 in the last position,
to avoid printing trash by the last fprintf() call.

This is needed because if the internal snprintf callback prints nothing,
no \0 exists in the buffer.

Signed-off-by: Arturo Borrero Gonzalez <arturo.borrero.glez@gmail.com>
---
 src/utils.c |    4 ++++
 1 file changed, 4 insertions(+)


--
To unsubscribe from this list: send the line "unsubscribe netfilter-devel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html

Comments

Pablo Neira Ayuso Aug. 25, 2014, 2:09 p.m. UTC | #1
On Mon, Aug 25, 2014 at 03:02:21PM +0200, Arturo Borrero Gonzalez wrote:
> We must make sure the buffer contains a \0 in the last position,
> to avoid printing trash by the last fprintf() call.

snprintf already guarantees that the string is nul-terminated if there
is enough room to add \0.

        ret = snprintf_cb(buf, bufsiz, obj, type, flags);
        if (ret < 0)
                goto out;

        if (ret >= NFT_SNPRINTF_BUFSIZ) {
                bufsiz = ret + 1;

                buf = malloc(bufsiz);
                if (buf == NULL)
                        return -1;

                ret = snprintf_cb(buf, bufsiz, obj, type, flags);
                if (ret < 0)
                        goto out;
        }

        ret = fprintf(fp, "%s", buf);

I think we have guarantees that buf is always nul-terminated after the
second try.

Patch 2/2 looks good to enough to me since it already resolves the
printed "garbage" at the end of the output issue.
--
To unsubscribe from this list: send the line "unsubscribe netfilter-devel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html
diff mbox

Patch

diff --git a/src/utils.c b/src/utils.c
index 96c8bf2..8a7c521 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -189,6 +189,8 @@  int nft_fprintf(FILE *fp, void *obj, uint32_t type, uint32_t flags,
 	size_t bufsiz = sizeof(_buf);
 	int ret;
 
+	buf[0] = '\0';
+
 	ret = snprintf_cb(buf, bufsiz, obj, type, flags);
 	if (ret < 0)
 		goto out;
@@ -200,6 +202,8 @@  int nft_fprintf(FILE *fp, void *obj, uint32_t type, uint32_t flags,
 		if (buf == NULL)
 			return -1;
 
+		buf[0] = '\0';
+
 		ret = snprintf_cb(buf, bufsiz, obj, type, flags);
 		if (ret < 0)
 			goto out;