The headers buffer contains also potentially binary data the CGI program is sending, and it needs to be sent out later. Use add_data() to cache data so the cgi output does not get corrupted on first zero byte. add_data() still always terminates the buffer with zero, so strstr() can used safely. diff -ru mini_httpd-1.23.orig/mini_httpd.c mini_httpd-1.23/mini_httpd.c --- mini_httpd-1.23.orig/mini_httpd.c +++ mini_httpd-1.25/mini_httpd.c @@ -282,6 +282,7 @@ static int my_sendfile( int fd, int s, off_t offset, size_t nbytes ); #endif /* HAVE_SENDFILE */ static void add_str( char** bufP, size_t* bufsizeP, size_t* buflenP, char* str ); +static void add_data( char** bufP, size_t* bufsizeP, size_t* buflenP, char* str, size_t len ); static void make_log_entry( void ); static void check_referrer( void ); static int really_check_referrer( void ); @@ -1997,7 +1998,7 @@ add_str( &headers, &headers_size, &headers_len, (char*) 0 ); for (;;) { - r = read( rfd, buf, sizeof(buf) - 1 ); + r = read( rfd, buf, sizeof(buf) ); if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) ) { sleep( 1 ); @@ -2008,8 +2009,7 @@ br = &(headers[headers_len]); break; } - buf[r] = '\0'; - add_str( &headers, &headers_size, &headers_len, buf ); + add_data( &headers, &headers_size, &headers_len, buf, r ); if ( ( br = strstr( headers, "\015\012\015\012" ) ) != (char*) 0 || ( br = strstr( headers, "\012\012" ) ) != (char*) 0 ) break; @@ -2791,7 +2791,13 @@ len = 0; else len = strlen( str ); + add_data( bufP, bufsizeP, buflenP, str, len ); + } + +static void +add_data( char** bufP, size_t* bufsizeP, size_t* buflenP, char* str, size_t len ) + { if ( *bufsizeP == 0 ) { *bufsizeP = len + 500;