Fix leaks and remove some non-standard functions

This commit is contained in:
Tobias Reisinger 2020-11-15 16:36:44 +01:00
parent c7cafa94c4
commit 97a19135ce
6 changed files with 63 additions and 27 deletions

View file

@ -1,3 +1,5 @@
#include <bsd/string.h>
#include <logger.h>
#include <cJSON.h>
#include <mongoose.h>
@ -33,6 +35,9 @@ endpoint_func_not_found(struct mg_connection *nc, struct http_message *hm, endpo
else
{
LOGGER_DEBUG("404 file not found\n");
endpoint_response_free_content(response);
response->status_code = 404;
response->content_type = global_config->not_found_content_type;
response->content_length = strlen(global_config->not_found_content);
@ -45,6 +50,8 @@ endpoint_func_not_found(struct mg_connection *nc, struct http_message *hm, endpo
void
endpoint_response_msg(endpoint_response_t *response, int status_code, const char *content, int content_length)
{
endpoint_response_free_content(response);
cJSON *json;
json = cJSON_CreateObject();
@ -66,11 +73,14 @@ endpoint_response_msg(endpoint_response_t *response, int status_code, const char
cJSON_AddItemToObject(json, "msg", json_msg);
endpoint_response_json(response, status_code, json);
cJSON_Delete(json);
}
void
endpoint_response_text(endpoint_response_t *response, int status_code, const char *content, int content_length)
{
endpoint_response_free_content(response);
if(content == NULL)
{
content = "";
@ -83,18 +93,24 @@ endpoint_response_text(endpoint_response_t *response, int status_code, const cha
{
response->content_length = content_length;
response->alloced_content = false;
response->content = (char*)content;
}
else
{
response->content_length = strlen(content);
response->alloced_content = true;
int content_size = response->content_length + 1;
response->content = malloc(sizeof(char) * content_size);
strlcpy(response->content, content, content_size);
}
response->content = content;
}
void
endpoint_response_json(endpoint_response_t *response, int status_code, const cJSON *json_root)
{
endpoint_response_free_content(response);
if(json_root != NULL)
{
char *json_str = cJSON_Print(json_root);
@ -112,3 +128,14 @@ endpoint_response_json(endpoint_response_t *response, int status_code, const cJS
M_RESPONSE_MSG(LOGGER_ERR, response, 500, "failed to print json");
}
void
endpoint_response_free_content(endpoint_response_t *response)
{
if(response->alloced_content)
{
free(response->content);
response->content = NULL;
response->alloced_content = false;
}
}