forked from michaelforney/oscmix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.c
73 lines (68 loc) · 1.51 KB
/
http.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* SPDX-License-Identifier: ISC */
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "http.h"
int
http_request(char *buf, size_t len, struct http_request *req)
{
char *method;
if (len < 2 || buf[len - 2] != '\r' || buf[len - 1] != '\n')
return -1;
method = buf;
buf = strchr(buf, ' ');
if (!buf)
return -1;
*buf++ = '\0';
if (strcmp(method, "GET") == 0) {
req->method = HTTP_GET;
} else if (strcmp(method, "POST") == 0) {
req->method = HTTP_POST;
} else if (strcmp(method, "M-SEARCH") == 0) {
req->method = HTTP_MSEARCH;
} else {
return -1;
}
req->uri = buf;
buf = strchr(buf, ' ');
if (!buf)
return -1;
*buf++ = '\0';
return 0;
}
int
http_header(char *buf, size_t len, struct http_header *hdr)
{
char *end;
if (len < 2 || buf[len - 2] != '\r' || buf[len - 1] != '\n')
return -1;
if (len == 2) {
hdr->name = NULL;
hdr->value = NULL;
return 0;
}
end = buf + (len - 2);
buf[len - 2] = '\0';
hdr->name = buf;
buf = strchr(buf, ':');
if (!buf)
return -1;
hdr->name_len = buf - hdr->name;
*buf = '\0';
do ++buf;
while (*buf == ' ' || *buf == '\t');
hdr->value = buf;
hdr->value_len = end - hdr->value;
return 0;
}
void
http_error(FILE *fp, int code, const char *text, const char *hdr[], size_t hdr_len)
{
assert(code >= 100 && code < 1000);
fprintf(fp, "HTTP/1.1 %d %s\r\nContent-Type:text/plain\r\nContent-Length:%zu\r\n", code, text, 5 + strlen(text));
while (hdr_len > 0) {
--hdr_len;
fprintf(fp, "%s\r\n", *hdr);
}
fprintf(fp, "\r\n%d %s\n", code, text);
}