#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mime.h"
#include "http_common.h"
static const char* methods[]=
{
"GET",
"POST"
};
static int get_version(const char* versionPos, char* version)
{
char* versionEnd = NULL;
int versionlen = 0;
if(versionPos == NULL || version == NULL)
return -1;
versionEnd = strstr(versionPos, "\n");
versionlen = versionEnd - versionPos;
#if 0
printf("versionlen = [%d]\n", versionlen);
#endif
if(versionlen >10 || versionlen <0)
return -1;
strncpy(version, versionPos, versionlen);
return 0;
}
static int get_method(const char* request, EN_REQ_METHOD* method)
{
if(strncmp(request, methods[HTTP_GET], 3) == 0)
{
*method = HTTP_GET;
}else if(strncmp(request, methods[HTTP_POST], 4) == 0)
{
*method = HTTP_POST;
}else
{
*method = HTTP_ELSE;
}
return (int)(*method);
}
/*--------------------------------------------------------------
functionname: parse_request
param: NA
return: NA
author: xxxx
--------------------------------------------------------------*/
int parse_request(const char* request, STR_REQUEST* result)
{
int method=0;
int urilen =0;
char* version_pos = NULL;
if(request == NULL || result == NULL)
return -1;
method =get_method(request, &(result->method));
//only apply GET POST
if(method == HTTP_ELSE)
return -1;
//-----------------get URI---------------------------------
version_pos = strstr(request, "HTTP");
//malloc uri
result->URI = (char*)malloc(urilen + WEBAPP_DIR_LEN);
//
if(result->URI == NULL)
{
perror("malloc failed");
return -1;
}
bzero(result->URI, urilen);
strncpy(result->URI, WEBAPP_DIR, WEBAPP_DIR_LEN);
//
if(result->method == HTTP_GET)
{
urilen = version_pos - (request+4) -1;
strncpy((result->URI)+WEBAPP_DIR_LEN, request + 4, urilen);
}
if(result->method == HTTP_POST)
{
urilen = version_pos - (request + 5) -1;
strncpy(result->URI+WEBAPP_DIR_LEN, request + 5, urilen);
}
//---------------------------------------------------------
if(get_version(version_pos, result->http_version) == -1)
return -1;
return 0;
}