command_packet_t *command_packet_read(buffer_t *stream) { size_t remaining_bytes = buffer_get_remaining_bytes(stream); uint32_t needed_bytes = -1; uint8_t *data; command_packet_t *out = NULL; size_t length; /* If we don't have a length, we're done. */ if(remaining_bytes < 4) return NULL; /* Check for an overflow. */ needed_bytes = buffer_peek_next_int32(stream); if(needed_bytes + 4 < needed_bytes) { LOG_FATAL("Overflow in command_packet!"); exit(1); } /* Make sure there are enough bytes present for the length + data. */ if(remaining_bytes < needed_bytes + 4) return NULL; /* Consume the length. */ buffer_read_next_int32(stream); /* Read the data. */ data = buffer_read_remaining_bytes(stream, &length, needed_bytes, TRUE); /* Sanity check. */ if(length != needed_bytes) { LOG_FATAL("Something went very wrong with the buffer class; the wrong number of bytes were read!"); exit(1); } /* Parse the data and free the buffer. */ out = command_packet_parse(data, length); safe_free(data); return out; }
command_packet_t *command_packet_stream_read(command_packet_stream_t *stream) { uint32_t length; uint8_t *data; command_packet_t *command_packet; if(!command_packet_stream_ready(stream)) return NULL; length = buffer_read_next_int32(stream->buffer); data = safe_malloc(length); buffer_read_next_bytes(stream->buffer, data, length); command_packet = command_packet_parse(data, length, stream->is_request); safe_free(data); return command_packet; }