From f611496625b0b240a8b849afabcfef9d373fa868 Mon Sep 17 00:00:00 2001 From: Nakidai Date: Sun, 15 Dec 2024 00:29:28 +0300 Subject: Make LibHTTPC_dumpResponse accept NULL in buf When LibHTTPC_dumpResponse accepts NULL it will allocate buffer itself using LibHTTPC_malloc --- TODO.7 | 10 ---------- src/response.c | 30 +++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/TODO.7 b/TODO.7 index 12a0adb..80eb496 100644 --- a/TODO.7 +++ b/TODO.7 @@ -18,16 +18,6 @@ parse requests from .Xr socket 2 directly. -.It -Make -.Fn LibHTTPC_dumpResponse -accept -.Dv NULL -in -.Fa buf . -In this way -function should -allocate buffer itself. .El . .Sh AUTHORS diff --git a/src/response.c b/src/response.c index b930fc6..d2442ff 100644 --- a/src/response.c +++ b/src/response.c @@ -43,11 +43,39 @@ char *LibHTTPC_dumpResponse(struct LibHTTPC_Response *response, char *buf, size_ snprintf(status, sizeof(status), "%d", response->status); + if (!buf) + { + if (!LibHTTPC_malloc) + return NULL; + + size_t buf_len = ( + 1 + + strlen(response->version) + 1 + + strlen(status) + 1 + + strlen(response->phrase) + 2 + + 2 + ); + for (size_t i = 0; i < response->header_count; ++i) + buf_len += ( + strlen(response->headers[i].name) + + 2 + + strlen(response->headers[i].value) + + 2 + ); + if (response->body) + buf_len += strlen(response->body); + buf = malloc(buf_len); + if (!buf) + return NULL; + + *buf = '\0'; + } + #define append(X) strncat(buf, (X), buf_len - strlen(buf)) WRITE(); #undef append - return NULL; + return buf; } #ifdef LibHTTPC_SOCK -- cgit 1.4.1