0

This question already has an answer here:

I don't understand how is request-line extracted from request in the distribution code. I can't visualize it.

// extract request's request-line
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
const char* haystack = request;
char* needle = strstr(haystack, "\r\n");
if (needle == NULL)
{
    error(400);
    continue;
}
else if (needle - haystack + 2 > LimitRequestLine)
{
    error(414);
    continue;
}   
char line[needle - haystack + 2 + 1];
strncpy(line, haystack, needle - haystack + 2);
line[needle - haystack + 2] = '\0';

marked as duplicate by Kareem Oct 16 '15 at 17:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

I'll comment it up for you. It is quite confusing at first, but you'll get your head around it :)

// place the request in a char pointer called haystack
const char* haystack = request;

// in a pointer called needle place the memory address of CRLF (the end of the request-line) only if it exists in haystack
char* needle = strstr(haystack, "\r\n");

// if there was no CRLF in the request line send bad request error
if (needle == NULL)
{
    error(400);
    continue;
}

// subtract the pointer for haystack (plus one CRLF (remember it comes with 2 CRLFs)) from the pointer for needle. What this does is find the length in bytes of the request. eg: If needle is at memory position 25 and haystack is at memory position 5 then needle - haystack is 20, the length of the request. If it's greater than the length limit, throw an error.
else if (needle - haystack + 2 > LimitRequestLine)
{
    error(414);
    continue;
}

// create a normal char array called line, the size of which is the length of the valid request plus one CRLF plus a null terminator
char line[needle - haystack + 2 + 1];

// use strncpy to copy the request(haystack) to line but only to it's proper length plus one CRLF
strncpy(line, haystack, needle - haystack + 2);

// place a null terminator at the end of the request line
line[needle - haystack + 2] = '\0';
  • i don't really get the subtraction part.can you please explain this with an example to make it more clear to me ? – kawegan Oct 16 '15 at 16:44

Not the answer you're looking for? Browse other questions tagged .