From 1421e4394f01e8167b5b7be67b6f98159895ae4b Mon Sep 17 00:00:00 2001 From: Christian Grothoff Date: Mon, 18 Jan 2016 20:43:27 +0000 Subject: eliminate stat/fopen race in example --- src/examples/https_fileserver_example.c | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/examples/https_fileserver_example.c b/src/examples/https_fileserver_example.c index fe0c2de7..99ec50b3 100644 --- a/src/examples/https_fileserver_example.c +++ b/src/examples/https_fileserver_example.c @@ -125,6 +125,7 @@ http_ahc (void *cls, struct MHD_Response *response; int ret; FILE *file; + int fd; struct stat buf; if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) @@ -137,12 +138,22 @@ http_ahc (void *cls, } *ptr = NULL; /* reset when done */ - if ( (0 == stat (&url[1], &buf)) && - (S_ISREG (buf.st_mode)) ) - file = fopen (&url[1], "rb"); - else - file = NULL; - if (file == NULL) + file = fopen (&url[1], "rb"); + if (NULL != file) + { + fd = fileno (file); + if (-1 == fd) + return MHD_NO; /* internal error */ + if ( (0 != fstat (fd, &buf)) || + (! S_ISREG (buf.st_mode)) ) + { + /* not a regular file, refuse to serve */ + fclose (file); + file = NULL; + } + } + + if (NULL == file) { response = MHD_create_response_from_buffer (strlen (EMPTY_PAGE), (void *) EMPTY_PAGE, @@ -155,7 +166,7 @@ http_ahc (void *cls, response = MHD_create_response_from_callback (buf.st_size, 32 * 1024, /* 32k PAGE_NOT_FOUND size */ &file_reader, file, &file_free_callback); - if (response == NULL) + if (NULL == response) { fclose (file); return MHD_NO; @@ -166,6 +177,7 @@ http_ahc (void *cls, return ret; } + int main (int argc, char *const *argv) { -- cgit v1.2.3