From c8401c591fac7fd98349e05e595cdbe861998a90 Mon Sep 17 00:00:00 2001 From: Laslo Hunhold Date: Mon, 5 Mar 2018 00:59:37 +0100 Subject: [PATCH] Add esnprintf() and refactor some code The (size_t) discards the case where the return value of snprintf is < 0. This is rather unlikely, but we'll keep it in mind anyway. --- http.c | 12 ++++++------ util.c | 13 +++++++++++++ util.h | 1 + 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/http.c b/http.c index cf08ada..98dfb00 100644 --- a/http.c +++ b/http.c @@ -346,8 +346,8 @@ http_send_response(int fd, struct request *r) /* if we have a vhost prefix, prepend it to the target */ if (s.vhost[i].prefix) { - if ((size_t)snprintf(realtarget, sizeof(realtarget), "%s%s", - s.vhost[i].prefix, realtarget) >= sizeof(realtarget)) { + if (esnprintf(realtarget, sizeof(realtarget), "%s%s", + s.vhost[i].prefix, realtarget)) { return http_send_status(fd, S_REQUEST_TOO_LARGE); } } @@ -363,8 +363,8 @@ http_send_response(int fd, struct request *r) } /* swap out target prefix */ - if ((size_t)snprintf(tmptarget, sizeof(tmptarget), "%s%s", - s.map[i].to, realtarget + len) >= sizeof(tmptarget)) { + if (esnprintf(tmptarget, sizeof(tmptarget), "%s%s", + s.map[i].to, realtarget + len)) { return http_send_status(fd, S_REQUEST_TOO_LARGE); } memcpy(realtarget, tmptarget, sizeof(realtarget)); @@ -441,8 +441,8 @@ http_send_response(int fd, struct request *r) if (S_ISDIR(st.st_mode)) { /* append docindex to target */ - if ((size_t)snprintf(realtarget, sizeof(realtarget), "%s%s", - r->target, s.docindex) >= sizeof(realtarget)) { + if (esnprintf(realtarget, sizeof(realtarget), "%s%s", + r->target, s.docindex)) { return http_send_status(fd, S_REQUEST_TOO_LARGE); } diff --git a/util.c b/util.c index 1fe9db8..d3db040 100644 --- a/util.c +++ b/util.c @@ -61,6 +61,19 @@ timestamp(time_t t, char buf[TIMESTAMP_LEN]) return buf; } +int +esnprintf(char *str, size_t size, const char *fmt, ...) +{ + va_list ap; + int ret; + + va_start(ap, fmt); + ret = vsnprintf(str, size, fmt, ap); + va_end(ap); + + return (ret < 0 || (size_t)ret >= size); +} + #define INVALID 1 #define TOOSMALL 2 #define TOOLARGE 3 diff --git a/util.h b/util.h index 1f9e107..8408ce3 100644 --- a/util.h +++ b/util.h @@ -49,6 +49,7 @@ void die(const char *, ...); #define TIMESTAMP_LEN 30 char *timestamp(time_t, char buf[TIMESTAMP_LEN]); +int esnprintf(char *, size_t, const char *, ...); void *reallocarray(void *, size_t, size_t); long long strtonum(const char *, long long, long long, const char **);