diff --git a/src/chat/misc.c b/src/chat/misc.c index a19df09..1b3c1c0 100644 --- a/src/chat/misc.c +++ b/src/chat/misc.c @@ -173,6 +173,8 @@ char *read_socket_raw(int socket) recv(socket, wait_buffer, 1, MSG_PEEK); why2_deallocate(wait_buffer); + why2_bool empty_buffer = 0; //WHETHER MSG_PEEK SHOULD BE USER OR NOT + do { //FIND THE SENT SIZE @@ -180,34 +182,26 @@ char *read_socket_raw(int socket) if (ioctl(socket, FIONREAD, &content_size) < 0 || content_size <= 0) continue; //ALLOCATE - content_buffer = why2_malloc(content_size + 1); + content_buffer = why2_realloc(content_buffer, content_size + 1); + + read_section: //READ JSON MESSAGE - if (recv(socket, content_buffer, content_size, MSG_PEEK) != content_size) //READ THE MESSAGE BY CHARACTERS + if (recv(socket, content_buffer, content_size, !empty_buffer ? MSG_PEEK : 0) != content_size) //READ THE MESSAGE BY CHARACTERS { fprintf(stderr, "Socket probably read wrongly!\n"); } - why2_deallocate(content_buffer); //CLEANUP + if (empty_buffer) goto return_section; //STOP LOOPING } while (content_buffer == NULL || strncmp(content_buffer + (content_size - 2), "\"}", 2) != 0); - //ACTUALLY READ - content_buffer = why2_calloc(content_size + 1, sizeof(char)); //ALLOCATE + //REMOVE JUNK FROM BUFFER (CUZ THE MSG_PEEK FLAG) + empty_buffer = 1; + goto read_section; //TODO: remove the stupid goto - int i; - for (i = 0; i < content_size; i++) - { - //READ - if (recv(socket, content_buffer + i, 1, 0) != 1) //READ BY CHARS - { - fprintf(stderr, "Socket probably read wrongly!\n"); - } + return_section: - //REMOVE NON-ASCII - if (!is_ascii(content_buffer[i])) i--; //(REWRITE THE CURRENT CHAR) - } - - content_buffer[i] = '\0'; //NULL TERM + content_buffer[content_size] = '\0'; //NULL TERM //VALIDATE JSON FORMAT struct json_object *json = json_tokener_parse(content_buffer);