#Need a bit of help parsing HTTP message

1 messages · Page 1 of 1 (latest)

candid island
#

For learning purpose, I am trying to make an HTTP Server in C. What did I do wrong here that I get r->body is null

request_t *parse_request(char *buf) {
  request_t *req = malloc(sizeof(request_t));
  char *save_prt;

  char *line = strtok_r(buf, "\r\n", &save_prt);
  char **parts = malloc(sizeof(char *) * 3);
  request_line_t *req_line = malloc(sizeof(request_line_t));
  str_split(line, " ", parts);
  req_line->method = parts[0];
  req_line->path = parts[1];
  req_line->version = parts[2];

  req->line = req_line;
  free(parts);

  header_map_t *headers = new_header_map();
  char *header_line;
  while ((header_line = strtok_r(NULL, "\r\n", &save_prt)) != NULL) {
    char **header_parts = malloc(sizeof(char *) * 2);
    str_split(header_line, ":", header_parts);
    char *val = trim(header_parts[1]);
    add_header(headers, header_parts[0], val);
    free(header_parts);
  }

  req->headers = headers;

  char *content_length_header = get_header(headers, "Content-Length");
  if (content_length_header != NULL) {
    int content_length = atoi(content_length_header);
    if (content_length > 1) {
      req->body = malloc(sizeof(char) * 1024);
      char *body = strtok_r(NULL, "\r\n", &save_prt);
      printf("body: %s \n", body);
      req->body = body;
    }
  }

  return req;
}

int main() {
  char buf[1024] = "POST /files/number HTTP/1.1\r\n"
                   "Host: localhost:4221\r\n"
                   "User-Agent: curl/7.64.1\r\n"
                   "Accept: */*\r\n"
                   "Content-Type: application/octet-stream\r\n"
                   "Content-Length: 5\r\n"
                   "\r\n"
                   "12345";

  request_t *r = parse_request(buf);
  if (r->body != NULL) {
    printf("%s\n", r->body);
  }
  return 0;
}

Expected r->body to be 12345, but getting null

spark rapidsBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

inner oak
#

if its still relevant:

      req->body = malloc(sizeof(char) * 1024);
      char *body = strtok_r(NULL, "\r\n", &save_prt);
      ...
      req->body = body;```
isn't what you want. `req->body = body` won't copy the content of `body` into `req::body`, rather it'll assign the _pointer_ to `req::body`. this will cause `req::body` to point somewhere in `buf`, leaking the memory you've allocated for it

as for the question:
- `strtok_r` may return `NULL`. did you check this isn't the case here?
- i suggest using a debugger