From bd28075ee0bf121ef4fe50e34146efe14acee07b Mon Sep 17 00:00:00 2001 From: Arturo Borrero Date: Tue, 29 Oct 2013 23:44:25 +0100 Subject: src: add fprintf API functions Now it's possible to print directly from libnftables to a file or other stream. The caller must explicitly print the trailing '\n' in this call. The error reporting of fprintf (< 0) is respected. However, we have already print some information in case that the default (plain text) output is used, that output is mostly intended for debugging so it should not be a problem. Signed-off-by: Arturo Borrero Gonzalez Signed-off-by: Pablo Neira Ayuso --- src/utils.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'src/utils.c') diff --git a/src/utils.c b/src/utils.c index 9a0bcfe..2415917 100644 --- a/src/utils.c +++ b/src/utils.c @@ -174,3 +174,30 @@ void xfree(const void *ptr) { free((void *)ptr); } + +int nft_fprintf(FILE *fp, void *obj, uint32_t type, uint32_t flags, + int (*snprintf_cb)(char *buf, size_t bufsiz, void *obj, + uint32_t type, uint32_t flags)) +{ + char _buf[NFT_SNPRINTF_BUFSIZ]; + char *buf = _buf; + size_t bufsiz = sizeof(_buf); + int ret; + + ret = snprintf_cb(buf, bufsiz, obj, type, flags); + if (ret > NFT_SNPRINTF_BUFSIZ) { + buf = calloc(1, ret); + if (buf == NULL) + return -1; + + bufsiz = ret; + ret = snprintf_cb(buf, bufsiz, obj, type, flags); + } + + ret = fprintf(fp, "%s", buf); + + if (buf != _buf) + xfree(buf); + + return ret; +} -- cgit v1.2.3