eliminate stat/fopen race in example

This commit is contained in:
Christian Grothoff committed 2016-01-18 20:43:27 +00:00
1 parent 9be469e2ee
commit 1421e4394f
1 file changed
+19 -7
+19 -7
View File
@@ -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)
{