/** * Read all the data pending in the socket. * The buffer with the data is allocated by proxenet_read_all() and *MUST* be free-ed * by the caller. * * @return the number of bytes read, or -1 if an error occured */ int proxenet_read_all(sock_t sock, char** ptr, proxenet_ssl_context_t* ssl) { int ret = 0; unsigned int total_bytes_read = 0; size_t malloced_size = sizeof(char) * MAX_READ_SIZE; char *data, *current_offset; current_offset = NULL; *ptr = NULL; data = (char*)proxenet_xmalloc(malloced_size+1); while (true) { current_offset = data + total_bytes_read; if (ssl) { /* ssl */ ret = proxenet_ssl_read(ssl, current_offset, MAX_READ_SIZE); } else { /* plaintext */ ret = proxenet_read(sock, current_offset, MAX_READ_SIZE); } if (ret < 0) { proxenet_xfree(data); xlog(LOG_ERROR, "read(%d) = %d\n", sock, ret); return ret; } total_bytes_read += ret; if (ret == MAX_READ_SIZE) { /* may be more data to come */ malloced_size += sizeof(char) * MAX_READ_SIZE; data = (char*)proxenet_xrealloc(data, malloced_size+1); #ifdef DEBUG xlog(LOG_DEBUG, "Increasing recv buf size to %d\n", malloced_size+1); #endif continue; } break; } if (total_bytes_read == 0) { proxenet_xfree(data); return -ENODATA; } *ptr = data; return total_bytes_read; }
int proxenet_handle_control_event(sock_t* sock) { char read_buf[BUFSIZE] = {0, }; char *ptr = NULL; int retcode = -1; struct command_t *cmd = NULL; retcode = proxenet_read(*sock, read_buf, BUFSIZE-1); if (retcode < 0) { xlog(LOG_ERROR, "Failed to read control command: %s\n", strerror(errno)); return -1; } if (retcode == 0) { return -1; } if (read_buf[0] == '\n') { goto cmd_end; } if ( (cmd=get_command(read_buf)) == NULL ) { proxenet_write(*sock, CONTROL_INVALID, strlen(CONTROL_INVALID)); goto cmd_end; } #ifdef DEBUG xlog(LOG_DEBUG, "Receiving control command: \"%s\" \n", cmd->name); #endif ptr = &read_buf[strlen(cmd->name)]; cmd->func(*sock, ptr, cmd->nb_opt_max); cmd_end: proxenet_write(*sock, CONTROL_PROMPT, strlen(CONTROL_PROMPT)); return 0; }