http-parser.c

Small C library to parse HTTP requests
Log | Files | Refs | README | LICENSE

commit 062c5f082003b3c7f81100e710eb071823c9da9b
parent 5bc5e46b65f79cb8b1aee55e3e80b8a727058ffa
Author: finwo <finwo@pm.me>
Date:   Tue, 11 Jul 2023 00:20:54 +0200

Added untested onChunk callback as alternative to waiting for whole request to finish

Diffstat:
Msrc/http-parser.c | 22+++++++++++++++++-----
Msrc/http-parser.h | 4++++
2 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/src/http-parser.c b/src/http-parser.c @@ -261,6 +261,7 @@ static int http_parser_message_read_header(struct http_parser_message *message) static int http_parser_message_read_chunked(struct http_parser_message *message) { char *aChunkSize; char *index; + struct http_parser_event *ev; // Attempt reading the chunk size if (message->chunksize == -1) { @@ -310,11 +311,22 @@ static int http_parser_message_read_chunked(struct http_parser_message *message) return 1; } - // Copy data into buffer - message->buf = realloc(message->buf, message->bufsize + message->chunksize + 1); - memcpy(message->buf + message->bufsize, message->body, message->chunksize ); - message->bufsize += message->chunksize; - *(message->buf + message->bufsize) = '\0'; + // Either call onChunk method OR copy into message buffer + if (message->onChunk) { + // Call onChunk if the message has that set + ev = calloc(1,sizeof(struct http_parser_event)); + ev->udata = message->udata; + ev->chunksize = message->chunksize; + ev->chunk = message->body; + message->onChunk(ev); + free(ev); + } else { + // Copy data into buffer if no onChunk set + message->buf = realloc(message->buf, message->bufsize + message->chunksize + 1); + memcpy(message->buf + message->bufsize, message->body, message->chunksize ); + message->bufsize += message->chunksize; + *(message->buf + message->bufsize) = '\0'; + } // Remove chunk from receiving data and reset chunking http_parser_message_remove_body_bytes(message, message->chunksize); diff --git a/src/http-parser.h b/src/http-parser.h @@ -22,6 +22,8 @@ struct http_parser_event { struct http_parser_message *request; struct http_parser_message *response; struct http_parser_pair *pair; + const char *chunk; + int chunksize; void *udata; }; @@ -41,6 +43,8 @@ struct http_parser_message { int bodysize; int chunktotal; int _state; + void (*onChunk)(struct http_parser_event*); + void *udata; }; struct http_parser_pair {