@@ -428,9 +428,59 @@ apr_status_t modsecurity_request_body_store(modsec_rec *msr,
428428}
429429
430430apr_status_t modsecurity_request_body_to_stream (modsec_rec * msr , const char * buffer , int buflen , char * * error_msg ) {
431+ #ifndef MSC_LARGE_STREAM_INPUT
432+ char * stream_input_body = NULL ;
433+ char * data = NULL ;
434+ int first_pkt = 0 ;
435+ #else
431436 apr_size_t allocate_length = 0 ;
432437 char * allocated = NULL ;
438+ #endif
439+
440+ #ifndef MSC_LARGE_STREAM_INPUT
441+ if (msr -> stream_input_data == NULL ) {
442+ msr -> stream_input_data = (char * )calloc (sizeof (char ), msr -> stream_input_length + 1 );
443+ first_pkt = 1 ;
444+ }
445+ else {
446+
447+ data = (char * )malloc (msr -> stream_input_length + 1 - buflen );
448+
449+ if (data == NULL )
450+ return -1 ;
451+
452+ memset (data , 0 , msr -> stream_input_length + 1 - buflen );
453+ memcpy (data , msr -> stream_input_data , msr -> stream_input_length - buflen );
454+
455+ stream_input_body = (char * )realloc (msr -> stream_input_data , msr -> stream_input_length + 1 );
456+
457+ msr -> stream_input_data = (char * )stream_input_body ;
458+ }
459+
460+ if (msr -> stream_input_data == NULL ) {
461+ if (data ) {
462+ free (data );
463+ data = NULL ;
464+ }
465+ * error_msg = apr_psprintf (msr -> mp , "Unable to allocate memory to hold request body on stream. Asked for %" APR_SIZE_T_FMT " bytes." ,
466+ msr -> stream_input_length + 1 );
467+ return -1 ;
468+ }
469+
470+ memset (msr -> stream_input_data , 0 , msr -> stream_input_length + 1 );
471+
472+ if (first_pkt ) {
473+ memcpy (msr -> stream_input_data , buffer , msr -> stream_input_length );
474+ } else {
475+ memcpy (msr -> stream_input_data , data , msr -> stream_input_length - buflen );
476+ memcpy (msr -> stream_input_data + (msr -> stream_input_length - buflen ), buffer , buflen );
477+ }
433478
479+ if (data ) {
480+ free (data );
481+ data = NULL ;
482+ }
483+ #else
434484 if (msr -> stream_input_data == NULL ) {
435485 // Is the request body length known beforehand? (requests that are not Transfer-Encoding: chunked)
436486 if (msr -> request_content_length > 0 ) {
@@ -458,7 +508,6 @@ apr_status_t modsecurity_request_body_to_stream(modsec_rec *msr, const char *buf
458508 else {
459509 // Do we need to expand the space we have previously allocated?
460510 if ((msr -> stream_input_length + buflen ) > msr -> stream_input_allocated_length ) {
461-
462511 // If this becomes a hotspot again, consider increasing by some percent extra each time, for fewer reallocs
463512 allocate_length = msr -> stream_input_length + buflen ;
464513
@@ -480,10 +529,10 @@ apr_status_t modsecurity_request_body_to_stream(modsec_rec *msr, const char *buf
480529 }
481530 }
482531 }
483-
484532 // Append buffer to msr->stream_input_data
485533 memcpy (msr -> stream_input_data + msr -> stream_input_length , buffer , buflen );
486534 msr -> stream_input_length += buflen ;
535+ #endif
487536
488537 return 1 ;
489538}
0 commit comments