111 lines
2.7 KiB
C
111 lines
2.7 KiB
C
#include "wire.h"
|
|
|
|
#include <ctype.h>
|
|
#include <errno.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
int wire_hex_digit(int value)
|
|
{
|
|
if (value >= '0' && value <= '9') {
|
|
return value - '0';
|
|
}
|
|
if (value >= 'a' && value <= 'f') {
|
|
return value - 'a' + 10;
|
|
}
|
|
if (value >= 'A' && value <= 'F') {
|
|
return value - 'A' + 10;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
static const char *skip_space(const char *text)
|
|
{
|
|
while (*text && isspace((unsigned char)*text)) {
|
|
text++;
|
|
}
|
|
return text;
|
|
}
|
|
|
|
static int decimal(const char **text, unsigned limit, unsigned *value)
|
|
{
|
|
char *end;
|
|
unsigned long number;
|
|
const char *start = skip_space(*text);
|
|
if (!isdigit((unsigned char)*start)) {
|
|
return 0;
|
|
}
|
|
errno = 0;
|
|
number = strtoul(start, &end, 10);
|
|
if (errno || end == start || number > limit) {
|
|
return 0;
|
|
}
|
|
if (*end && !isspace((unsigned char)*end)) {
|
|
return 0;
|
|
}
|
|
*text = end;
|
|
*value = (unsigned)number;
|
|
return 1;
|
|
}
|
|
|
|
int wire_parse_request(const char *text, wire_request *request)
|
|
{
|
|
size_t length = 0u;
|
|
memset(request, 0, sizeof(*request));
|
|
if (!decimal(&text, 7u, &request->pad)) {
|
|
return 0;
|
|
}
|
|
if (!decimal(&text, WIRE_LIMIT, &request->chunk) || !request->chunk) {
|
|
return 0;
|
|
}
|
|
text = skip_space(text);
|
|
while (*text && !isspace((unsigned char)*text)) {
|
|
int high;
|
|
int low;
|
|
if (length == WIRE_LIMIT || !text[1]) {
|
|
return 0;
|
|
}
|
|
high = wire_hex_digit((unsigned char)text[0]);
|
|
low = wire_hex_digit((unsigned char)text[1]);
|
|
if (high < 0 || low < 0) {
|
|
return 0;
|
|
}
|
|
request->bytes[length++] = (unsigned char)(high * 16 + low);
|
|
text += 2;
|
|
}
|
|
text = skip_space(text);
|
|
if (*text || !length) {
|
|
return 0;
|
|
}
|
|
request->length = length;
|
|
return 1;
|
|
}
|
|
|
|
int wire_process_line(const char *text, unsigned sequence, FILE *output)
|
|
{
|
|
wire_request request;
|
|
wire_decoder decoder;
|
|
size_t position;
|
|
size_t count = 0u;
|
|
wire_fragment fragments[WIRE_LIMIT];
|
|
if (!wire_parse_request(text, &request)) {
|
|
fprintf(output, "I %u\n", sequence);
|
|
return 0;
|
|
}
|
|
wire_decoder_init(&decoder, request.pad);
|
|
for (position = 0u; position < request.length;) {
|
|
size_t length = request.length - position;
|
|
if (length > request.chunk) {
|
|
length = request.chunk;
|
|
}
|
|
fragments[count].data = request.bytes + position;
|
|
fragments[count].length = length;
|
|
count++;
|
|
position += length;
|
|
}
|
|
wire_decoder_feedv(&decoder, fragments, count);
|
|
wire_decoder_finish(&decoder);
|
|
wire_print_observation(output, sequence, &decoder);
|
|
return 1;
|
|
}
|