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.
This commit is contained in:
Laslo Hunhold 2018-03-05 00:59:37 +01:00
parent 1879e14e79
commit c8401c591f
3 changed files with 20 additions and 6 deletions

12
http.c
View file

@ -346,8 +346,8 @@ http_send_response(int fd, struct request *r)
/* if we have a vhost prefix, prepend it to the target */ /* if we have a vhost prefix, prepend it to the target */
if (s.vhost[i].prefix) { if (s.vhost[i].prefix) {
if ((size_t)snprintf(realtarget, sizeof(realtarget), "%s%s", if (esnprintf(realtarget, sizeof(realtarget), "%s%s",
s.vhost[i].prefix, realtarget) >= sizeof(realtarget)) { s.vhost[i].prefix, realtarget)) {
return http_send_status(fd, S_REQUEST_TOO_LARGE); 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 */ /* swap out target prefix */
if ((size_t)snprintf(tmptarget, sizeof(tmptarget), "%s%s", if (esnprintf(tmptarget, sizeof(tmptarget), "%s%s",
s.map[i].to, realtarget + len) >= sizeof(tmptarget)) { s.map[i].to, realtarget + len)) {
return http_send_status(fd, S_REQUEST_TOO_LARGE); return http_send_status(fd, S_REQUEST_TOO_LARGE);
} }
memcpy(realtarget, tmptarget, sizeof(realtarget)); memcpy(realtarget, tmptarget, sizeof(realtarget));
@ -441,8 +441,8 @@ http_send_response(int fd, struct request *r)
if (S_ISDIR(st.st_mode)) { if (S_ISDIR(st.st_mode)) {
/* append docindex to target */ /* append docindex to target */
if ((size_t)snprintf(realtarget, sizeof(realtarget), "%s%s", if (esnprintf(realtarget, sizeof(realtarget), "%s%s",
r->target, s.docindex) >= sizeof(realtarget)) { r->target, s.docindex)) {
return http_send_status(fd, S_REQUEST_TOO_LARGE); return http_send_status(fd, S_REQUEST_TOO_LARGE);
} }

13
util.c
View file

@ -61,6 +61,19 @@ timestamp(time_t t, char buf[TIMESTAMP_LEN])
return buf; 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 INVALID 1
#define TOOSMALL 2 #define TOOSMALL 2
#define TOOLARGE 3 #define TOOLARGE 3

1
util.h
View file

@ -49,6 +49,7 @@ void die(const char *, ...);
#define TIMESTAMP_LEN 30 #define TIMESTAMP_LEN 30
char *timestamp(time_t, char buf[TIMESTAMP_LEN]); char *timestamp(time_t, char buf[TIMESTAMP_LEN]);
int esnprintf(char *, size_t, const char *, ...);
void *reallocarray(void *, size_t, size_t); void *reallocarray(void *, size_t, size_t);
long long strtonum(const char *, long long, long long, const char **); long long strtonum(const char *, long long, long long, const char **);