2 * uhttpd - Tiny single-threaded httpd
4 * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include <libubox/blobmsg.h>
26 static LIST_HEAD(clients);
27 static bool client_done = false;
30 struct config conf = {};
32 const char * const http_versions[] = {
33 [UH_HTTP_VER_0_9] = "HTTP/0.9",
34 [UH_HTTP_VER_1_0] = "HTTP/1.0",
35 [UH_HTTP_VER_1_1] = "HTTP/1.1",
38 const char * const http_methods[] = {
39 [UH_HTTP_MSG_GET] = "GET",
40 [UH_HTTP_MSG_POST] = "POST",
41 [UH_HTTP_MSG_HEAD] = "HEAD",
42 [UH_HTTP_MSG_OPTIONS] = "OPTIONS",
45 void uh_http_header(struct client *cl, int code, const char *summary)
47 struct http_request *r = &cl->request;
48 const char *enc = "Transfer-Encoding: chunked\r\n";
53 if (!uh_use_chunked(cl))
56 if (r->connection_close)
57 conn = "Connection: close";
59 conn = "Connection: Keep-Alive";
61 ustream_printf(cl->us, "%s %03i %s\r\n%s\r\n%s",
62 http_versions[cl->request.version],
63 code, summary, conn, enc);
65 if (!r->connection_close)
66 ustream_printf(cl->us, "Keep-Alive: timeout=%d\r\n", conf.http_keepalive);
69 static void uh_connection_close(struct client *cl)
71 cl->state = CLIENT_STATE_CLOSE;
73 ustream_state_change(cl->us);
76 static void uh_dispatch_done(struct client *cl)
78 if (cl->dispatch.free)
79 cl->dispatch.free(cl);
80 if (cl->dispatch.req_free)
81 cl->dispatch.req_free(cl);
84 static void client_timeout(struct uloop_timeout *timeout)
86 struct client *cl = container_of(timeout, struct client, timeout);
88 cl->state = CLIENT_STATE_CLOSE;
89 uh_connection_close(cl);
92 static void uh_set_client_timeout(struct client *cl, int timeout)
94 cl->timeout.cb = client_timeout;
95 uloop_timeout_set(&cl->timeout, timeout * 1000);
98 static void uh_keepalive_poll_cb(struct uloop_timeout *timeout)
100 struct client *cl = container_of(timeout, struct client, timeout);
101 int sec = cl->requests > 0 ? conf.http_keepalive : conf.network_timeout;
103 uh_set_client_timeout(cl, sec);
104 cl->us->notify_read(cl->us, 0);
107 static void uh_poll_connection(struct client *cl)
109 cl->timeout.cb = uh_keepalive_poll_cb;
110 uloop_timeout_set(&cl->timeout, 1);
113 void uh_request_done(struct client *cl)
116 uh_dispatch_done(cl);
117 memset(&cl->dispatch, 0, sizeof(cl->dispatch));
119 if (!conf.http_keepalive || cl->request.connection_close)
120 return uh_connection_close(cl);
122 cl->state = CLIENT_STATE_INIT;
124 uh_poll_connection(cl);
128 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
132 uh_http_header(cl, code, summary);
133 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
135 uh_chunk_printf(cl, "<h1>%s</h1>", summary);
139 uh_chunk_vprintf(cl, fmt, arg);
146 static void uh_header_error(struct client *cl, int code, const char *summary)
148 uh_client_error(cl, code, summary, NULL);
149 uh_connection_close(cl);
152 static int find_idx(const char * const *list, int max, const char *str)
156 for (i = 0; i < max; i++)
157 if (!strcmp(list[i], str))
163 static int client_parse_request(struct client *cl, char *data)
165 struct http_request *req = &cl->request;
166 char *type, *path, *version;
167 int h_method, h_version;
169 type = strtok(data, " ");
170 path = strtok(NULL, " ");
171 version = strtok(NULL, " ");
172 if (!type || !path || !version)
173 return CLIENT_STATE_DONE;
175 blobmsg_add_string(&cl->hdr, "URL", path);
177 memset(&cl->request, 0, sizeof(cl->request));
178 h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
179 h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
180 if (h_method < 0 || h_version < 0) {
181 req->version = UH_HTTP_VER_1_0;
182 return CLIENT_STATE_DONE;
185 req->method = h_method;
186 req->version = h_version;
187 if (req->version < UH_HTTP_VER_1_1 || req->method == UH_HTTP_MSG_POST ||
188 !conf.http_keepalive)
189 req->connection_close = true;
191 return CLIENT_STATE_HEADER;
194 static bool client_init_cb(struct client *cl, char *buf, int len)
198 newline = strstr(buf, "\r\n");
202 if (newline == buf) {
203 ustream_consume(cl->us, 2);
208 blob_buf_init(&cl->hdr, 0);
209 cl->state = client_parse_request(cl, buf);
210 ustream_consume(cl->us, newline + 2 - buf);
211 if (cl->state == CLIENT_STATE_DONE)
212 uh_header_error(cl, 400, "Bad Request");
217 static bool rfc1918_filter_check(struct client *cl)
219 if (!conf.rfc1918_filter)
222 if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
225 uh_client_error(cl, 403, "Forbidden",
226 "Rejected request from RFC1918 IP "
227 "to public server address");
231 static void client_header_complete(struct client *cl)
233 struct http_request *r = &cl->request;
235 if (!rfc1918_filter_check(cl))
239 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
243 if (r->method != UH_HTTP_MSG_POST)
248 r->connection_close = true;
254 uh_handle_request(cl);
257 static void client_parse_header(struct client *cl, char *data)
259 struct http_request *r = &cl->request;
265 uloop_timeout_cancel(&cl->timeout);
266 cl->state = CLIENT_STATE_DATA;
267 client_header_complete(cl);
271 val = uh_split_header(data);
273 cl->state = CLIENT_STATE_DONE;
277 for (name = data; *name; name++)
279 *name = tolower(*name);
281 if (!strcmp(data, "expect")) {
282 if (!strcasecmp(val, "100-continue"))
283 r->expect_cont = true;
285 uh_header_error(cl, 412, "Precondition Failed");
288 } else if (!strcmp(data, "content-length")) {
289 r->content_length = strtoul(val, &err, 0);
291 uh_header_error(cl, 400, "Bad Request");
294 } else if (!strcmp(data, "transfer-encoding")) {
295 if (!strcmp(val, "chunked"))
296 r->transfer_chunked = true;
297 } else if (!strcmp(data, "connection")) {
298 if (!strcasecmp(val, "close"))
299 r->connection_close = true;
300 } else if (!strcmp(data, "user-agent")) {
303 if (strstr(val, "Opera"))
305 else if ((str = strstr(val, "MSIE ")) != NULL) {
306 r->ua = UH_UA_MSIE_NEW;
307 if (str[5] && str[6] == '.') {
310 if (strstr(str, "SV1"))
315 r->ua = UH_UA_MSIE_OLD;
320 else if (strstr(val, "Chrome/"))
321 r->ua = UH_UA_CHROME;
322 else if (strstr(val, "Safari/") && strstr(val, "Mac OS X"))
323 r->ua = UH_UA_SAFARI;
324 else if (strstr(val, "Gecko/"))
326 else if (strstr(val, "Konqueror"))
327 r->ua = UH_UA_KONQUEROR;
331 blobmsg_add_string(&cl->hdr, data, val);
333 cl->state = CLIENT_STATE_HEADER;
336 void client_poll_post_data(struct client *cl)
338 struct dispatch *d = &cl->dispatch;
339 struct http_request *r = &cl->request;
343 if (cl->state == CLIENT_STATE_DONE)
351 buf = ustream_get_read_buf(cl->us, &len);
358 cur_len = min(r->content_length, len);
364 cur_len = d->data_send(cl, buf, cur_len);
366 r->content_length -= cur_len;
367 ustream_consume(cl->us, cur_len);
371 if (!r->transfer_chunked)
374 if (r->transfer_chunked > 1)
377 sep = strstr(buf + offset, "\r\n");
383 r->content_length = strtoul(buf + offset, &sep, 16);
384 r->transfer_chunked++;
385 ustream_consume(cl->us, sep + 2 - buf);
387 /* invalid chunk length */
389 r->content_length = 0;
390 r->transfer_chunked = 0;
394 /* empty chunk == eof */
395 if (!r->content_length) {
396 r->transfer_chunked = false;
401 buf = ustream_get_read_buf(cl->us, &len);
402 if (!r->content_length && !r->transfer_chunked &&
403 cl->state != CLIENT_STATE_DONE) {
404 if (cl->dispatch.data_done)
405 cl->dispatch.data_done(cl);
407 cl->state = CLIENT_STATE_DONE;
411 static bool client_data_cb(struct client *cl, char *buf, int len)
413 client_poll_post_data(cl);
417 static bool client_header_cb(struct client *cl, char *buf, int len)
422 newline = strstr(buf, "\r\n");
427 client_parse_header(cl, buf);
428 line_len = newline + 2 - buf;
429 ustream_consume(cl->us, line_len);
430 if (cl->state == CLIENT_STATE_DATA)
431 return client_data_cb(cl, newline + 2, len - line_len);
436 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
437 static read_cb_t read_cbs[] = {
438 [CLIENT_STATE_INIT] = client_init_cb,
439 [CLIENT_STATE_HEADER] = client_header_cb,
440 [CLIENT_STATE_DATA] = client_data_cb,
443 void uh_client_read_cb(struct client *cl)
445 struct ustream *us = cl->us;
451 str = ustream_get_read_buf(us, &len);
455 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
458 if (!read_cbs[cl->state](cl, str, len)) {
459 if (len == us->r.buffer_len &&
460 cl->state != CLIENT_STATE_DATA)
461 uh_header_error(cl, 413, "Request Entity Too Large");
464 } while (!client_done);
467 static void client_close(struct client *cl)
470 cl->state = CLIENT_STATE_CLEANUP;
476 uh_dispatch_done(cl);
477 uloop_timeout_cancel(&cl->timeout);
479 uh_tls_client_detach(cl);
480 ustream_free(&cl->sfd.stream);
481 close(cl->sfd.fd.fd);
483 blob_buf_free(&cl->hdr);
486 uh_unblock_listeners();
489 void uh_client_notify_state(struct client *cl)
491 struct ustream *s = cl->us;
493 if (!s->write_error && cl->state != CLIENT_STATE_CLEANUP) {
494 if (cl->state == CLIENT_STATE_DATA)
497 if (!s->eof || s->w.data_bytes)
501 return client_close(cl);
504 static void client_ustream_read_cb(struct ustream *s, int bytes)
506 struct client *cl = container_of(s, struct client, sfd.stream);
508 uh_client_read_cb(cl);
511 static void client_ustream_write_cb(struct ustream *s, int bytes)
513 struct client *cl = container_of(s, struct client, sfd.stream);
515 if (cl->dispatch.write_cb)
516 cl->dispatch.write_cb(cl);
519 static void client_notify_state(struct ustream *s)
521 struct client *cl = container_of(s, struct client, sfd.stream);
523 uh_client_notify_state(cl);
526 static void set_addr(struct uh_addr *addr, void *src)
528 struct sockaddr_in *sin = src;
529 struct sockaddr_in6 *sin6 = src;
531 addr->family = sin->sin_family;
532 if (addr->family == AF_INET) {
533 addr->port = ntohs(sin->sin_port);
534 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
536 addr->port = ntohs(sin6->sin6_port);
537 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
541 bool uh_accept_client(int fd, bool tls)
543 static struct client *next_client;
547 static int client_id = 0;
548 struct sockaddr_in6 addr;
551 next_client = calloc(1, sizeof(*next_client));
556 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
560 set_addr(&cl->peer_addr, &addr);
562 getsockname(sfd, (struct sockaddr *) &addr, &sl);
563 set_addr(&cl->srv_addr, &addr);
565 cl->us = &cl->sfd.stream;
567 uh_tls_client_attach(cl);
569 cl->us->notify_read = client_ustream_read_cb;
570 cl->us->notify_write = client_ustream_write_cb;
571 cl->us->notify_state = client_notify_state;
574 cl->us->string_data = true;
575 ustream_fd_init(&cl->sfd, sfd);
577 uh_poll_connection(cl);
578 list_add_tail(&cl->list, &clients);
582 cl->id = client_id++;
588 void uh_close_fds(void)
593 uh_close_listen_fds();
594 list_for_each_entry(cl, &clients, list) {
595 close(cl->sfd.fd.fd);
596 if (cl->dispatch.close_fds)
597 cl->dispatch.close_fds(cl);