commit 1421e4394f01e8167b5b7be67b6f98159895ae4b
parent 9be469e2eeade6ccdbbd24f99cd37aa424e9afb9
Author: Christian Grothoff <christian@grothoff.org>
Date: Mon, 18 Jan 2016 20:43:27 +0000
eliminate stat/fopen race in example
Diffstat:
1 file changed, 19 insertions(+), 7 deletions(-)
diff --git 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)
{