get_request_line.c 1.71 KB
#include <stdlib.h>
#include <string.h>

#include "http/message.h"
#include "http/request.h"
#include "http/request/parser.h"
#include "ringbuffer.h"

#define MAX(x,y)    	((x) > (y) ? (x) : (y))
#define MIN(x,y)    	((x) < (y) ? (x) : (y))
#define MIN_SIZE(x,y)	(MAX(strlen((x)), (y)))

enum e_method {
	OPTIONS=0,
	GET,
	HEAD,
	POST,
	PUT,
	DELETE,
	TRACE,
	CONNECT
};

#define N_METHODS	8

static
const
char * method[N_METHODS] = {
	"OPTIONS",
	"GET",
	"HEAD",
	"POST",
	"PUT",
	"DELETE",
	"TRACE",
	"CONNECT"
};

ssize_t
httpRequestParserGetRequestLine(HttpRequestParser this, char * cr)
{
	HttpRequest request = this->cur_request;
	HttpMessage message = (HttpMessage)request;
	char * space1, * space2;
	size_t len = cr - this->buffer->buffer - this->buffer->bstart;
	int    i;

	space1 = memchr(
			this->buffer->buffer + this->buffer->bstart,
			' ', len);

	if (NULL == space1) {
		return -1;
	}

	len = cr - space1;
	space2 = memchr(space1 + 1, ' ', len);

	if (NULL == space2) {
		return -1;
	}

	len = space1 - this->buffer->buffer - this->buffer->bstart;
	request->method = calloc(1, len + 1);
	memcpy(request->method,
			this->buffer->buffer + this->buffer->bstart,
			len);

	for (i= 0; i< N_METHODS; i++) {
		if (0 == memcmp(method[i], request->method, MIN_SIZE(method[i], len))) {
			break;
		}
	}

	if (i == N_METHODS) {
		return -1;
	}

	len = space2 - space1 - 1;
	request->uri = calloc(1, len + 1);
	memcpy(request->uri, space1 + 1, len);

	len = cr - space2 - 1;
	message->version = calloc(1, len + 1);
	memcpy(message->version, space2 + 1, len);

	if (len+1 != sizeof("HTTP/1.1") ||
			0 != memcmp("HTTP/1.", message->version, len-1)) {
		return -1;
	}

	return 1; //* @TODO: return something useful here
}

// vim: set ts=4 sw=4: