2.53
xs_httpd.h
1/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
2
3#ifndef _XS_HTTPD_H
4
5#define _XS_HTTPD_H
6
7xs_dict *xs_httpd_request(FILE *f, xs_str **payload, int *p_size);
8void xs_httpd_response(FILE *f, int status, xs_dict *headers, xs_str *body, int b_size);
9
10
11#ifdef XS_IMPLEMENTATION
12
13xs_dict *xs_httpd_request(FILE *f, xs_str **payload, int *p_size)
14/* processes an httpd connection */
15{
16 xs *q_vars = NULL;
17 xs *p_vars = NULL;
18 xs *l1, *l2;
19 char *v;
20
21 xs_socket_timeout(fileno(f), 2.0, 0.0);
22
23 /* read the first line and split it */
24 l1 = xs_strip_i(xs_readline(f));
25 l2 = xs_split(l1, " ");
26
27 if (xs_list_len(l2) != 3) {
28 /* error or timeout */
29 return NULL;
30 }
31
32 xs_dict *req = xs_dict_new();
33
34 req = xs_dict_append(req, "method", xs_list_get(l2, 0));
35 req = xs_dict_append(req, "proto", xs_list_get(l2, 2));
36
37 {
38 /* split the path with its optional variables */
39 xs *udp = xs_url_dec(xs_list_get(l2, 1));
40 xs *pnv = xs_split_n(udp, "?", 1);
41
42 /* store the path */
43 req = xs_dict_append(req, "path", xs_list_get(pnv, 0));
44
45 /* get the variables */
46 q_vars = xs_url_vars(xs_list_get(pnv, 1));
47 }
48
49 /* read the headers */
50 for (;;) {
51 xs *l, *p = NULL;
52
53 l = xs_strip_i(xs_readline(f));
54
55 /* done with the header? */
56 if (strcmp(l, "") == 0)
57 break;
58
59 /* split header and content */
60 p = xs_split_n(l, ": ", 1);
61
62 if (xs_list_len(p) == 2)
63 req = xs_dict_append(req, xs_tolower_i(xs_list_get(p, 0)), xs_list_get(p, 1));
64 }
65
66 xs_socket_timeout(fileno(f), 5.0, 0.0);
67
68 if ((v = xs_dict_get(req, "content-length")) != NULL) {
69 /* if it has a payload, load it */
70 *p_size = atoi(v);
71 *payload = xs_read(f, p_size);
72 }
73
74 v = xs_dict_get(req, "content-type");
75
76 if (*payload && v && strcmp(v, "application/x-www-form-urlencoded") == 0) {
77 xs *upl = xs_url_dec(*payload);
78 p_vars = xs_url_vars(upl);
79 }
80 else
81 if (*payload && v && xs_startswith(v, "multipart/form-data")) {
82 p_vars = xs_multipart_form_data(*payload, *p_size, v);
83 }
84 else
85 p_vars = xs_dict_new();
86
87 req = xs_dict_append(req, "q_vars", q_vars);
88 req = xs_dict_append(req, "p_vars", p_vars);
89
90 if (errno)
91 req = xs_free(req);
92
93 return req;
94}
95
96
97void xs_httpd_response(FILE *f, int status, xs_dict *headers, xs_str *body, int b_size)
98/* sends an httpd response */
99{
100 xs *proto;
101 xs_str *k;
102 xs_val *v;
103
104 proto = xs_fmt("HTTP/1.1 %d %s", status, status / 100 == 2 ? "OK" : "ERROR");
105 fprintf(f, "%s\r\n", proto);
106
107 int c = 0;
108 while (xs_dict_next(headers, &k, &v, &c)) {
109 fprintf(f, "%s: %s\r\n", k, v);
110 }
111
112 if (b_size != 0)
113 fprintf(f, "content-length: %d\r\n", b_size);
114
115 fprintf(f, "\r\n");
116
117 if (body != NULL && b_size != 0)
118 fwrite(body, b_size, 1, f);
119}
120
121
122#endif /* XS_IMPLEMENTATION */
123
124#endif /* XS_HTTPD_H */