From 885b99b7a8c395bbea72e0c0156451c7d9aa73f4 Mon Sep 17 00:00:00 2001 From: ENGO150 Date: Sat, 25 Mar 2023 16:35:44 +0100 Subject: [PATCH] added raw socket functions --- src/chat/misc.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/src/chat/misc.c b/src/chat/misc.c index 4ba1f33..75e05d4 100644 --- a/src/chat/misc.c +++ b/src/chat/misc.c @@ -159,7 +159,60 @@ char *get_string_from_json(struct json_object *json, char *string) json_object_object_get_ex(json, string, &object); //GET STRINGS - return (char*) json_object_get_string(object); + return returning; +} + +char *read_socket_raw(int socket) +{ + if (socket == -1) + { + fprintf(stderr, "Reading socket failed.\n"); + return NULL; + } + + unsigned short content_size = 0; + char *content_buffer = why2_calloc(3, sizeof(char)); + //GET LENGTH + if (recv(socket, content_buffer, 2, 0) != 2) + { + fprintf(stderr, "Getting message length failed!\n"); + return NULL; + } + + content_size = (unsigned short) (((unsigned) content_buffer[1] << 8) | content_buffer[0]); + + why2_deallocate(content_buffer); + + //ALLOCATE + content_buffer = why2_calloc(content_size + 1, sizeof(char)); + + //READ JSON MESSAGE + if (recv(socket, content_buffer, content_size, 0) != content_size - 2) fprintf(stderr, "Socket probably read wrongly!\n"); + + content_buffer[content_size - 2] = '\0'; //TODO: Possible problems + + return content_buffer; +} + +char *read_socket_from_raw(char *raw) +{ + char *final_message; + struct json_object *json_obj = json_tokener_parse(raw); + + //GET STRINGS + char *message = get_string_from_json(json_obj, "message"); //TODO: Check deallocation problems + char *username = get_string_from_json(json_obj, "username"); + + //ALLOCATE final_message + final_message = why2_calloc(strlen(message) + strlen(username) + 3, sizeof(char)); + + //BUILD final_message + sprintf(final_message, "%s: %s", username, message); + + //DEALLOCATION + json_object_put(json_obj); + + return final_message; } //GLOBAL