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",
43 [UH_HTTP_MSG_PUT] = "PUT",
44 [UH_HTTP_MSG_PATCH] = "PATCH",
45 [UH_HTTP_MSG_DELETE] = "DELETE",
48 void uh_http_header(struct client *cl, int code, const char *summary)
50 struct http_request *r = &cl->request;
51 struct blob_attr *cur;
52 const char *enc = "Transfer-Encoding: chunked\r\n";
58 if (!uh_use_chunked(cl))
61 if (r->connection_close)
62 conn = "Connection: close";
64 conn = "Connection: Keep-Alive";
66 ustream_printf(cl->us, "%s %03i %s\r\n%s\r\n%s",
67 http_versions[cl->request.version],
68 code, summary, conn, enc);
70 if (!r->connection_close)
71 ustream_printf(cl->us, "Keep-Alive: timeout=%d\r\n", conf.http_keepalive);
73 blobmsg_for_each_attr(cur, cl->hdr_response.head, rem)
74 ustream_printf(cl->us, "%s: %s\r\n", blobmsg_name(cur),
75 blobmsg_get_string(cur));
78 static void uh_connection_close(struct client *cl)
80 cl->state = CLIENT_STATE_CLOSE;
82 ustream_state_change(cl->us);
85 static void uh_dispatch_done(struct client *cl)
87 if (cl->dispatch.free)
88 cl->dispatch.free(cl);
89 if (cl->dispatch.req_free)
90 cl->dispatch.req_free(cl);
93 static void client_timeout(struct uloop_timeout *timeout)
95 struct client *cl = container_of(timeout, struct client, timeout);
97 cl->state = CLIENT_STATE_CLOSE;
98 uh_connection_close(cl);
101 static void uh_set_client_timeout(struct client *cl, int timeout)
103 cl->timeout.cb = client_timeout;
104 uloop_timeout_set(&cl->timeout, timeout * 1000);
107 static void uh_keepalive_poll_cb(struct uloop_timeout *timeout)
109 struct client *cl = container_of(timeout, struct client, timeout);
110 int sec = cl->requests > 0 ? conf.http_keepalive : conf.network_timeout;
112 uh_set_client_timeout(cl, sec);
113 cl->us->notify_read(cl->us, 0);
116 static void uh_poll_connection(struct client *cl)
118 cl->timeout.cb = uh_keepalive_poll_cb;
119 uloop_timeout_set(&cl->timeout, 1);
122 void uh_request_done(struct client *cl)
125 uh_dispatch_done(cl);
126 blob_buf_init(&cl->hdr_response, 0);
127 memset(&cl->dispatch, 0, sizeof(cl->dispatch));
129 if (!conf.http_keepalive || cl->request.connection_close)
130 return uh_connection_close(cl);
132 cl->state = CLIENT_STATE_INIT;
134 uh_poll_connection(cl);
138 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
142 uh_http_header(cl, code, summary);
143 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
145 uh_chunk_printf(cl, "<h1>%s</h1>", summary);
149 uh_chunk_vprintf(cl, fmt, arg);
156 static void uh_header_error(struct client *cl, int code, const char *summary)
158 uh_client_error(cl, code, summary, NULL);
159 uh_connection_close(cl);
162 static int find_idx(const char * const *list, int max, const char *str)
166 for (i = 0; i < max; i++)
167 if (!strcmp(list[i], str))
173 static int client_parse_request(struct client *cl, char *data)
175 struct http_request *req = &cl->request;
176 char *type, *path, *version;
177 int h_method, h_version;
179 type = strtok(data, " ");
180 path = strtok(NULL, " ");
181 version = strtok(NULL, " ");
182 if (!type || !path || !version)
183 return CLIENT_STATE_DONE;
185 blobmsg_add_string(&cl->hdr, "URL", path);
187 memset(&cl->request, 0, sizeof(cl->request));
188 h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
189 h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
190 if (h_method < 0 || h_version < 0) {
191 req->version = UH_HTTP_VER_1_0;
192 return CLIENT_STATE_DONE;
195 req->method = h_method;
196 req->version = h_version;
197 if (req->version < UH_HTTP_VER_1_1 || !conf.http_keepalive)
198 req->connection_close = true;
200 return CLIENT_STATE_HEADER;
203 static bool client_init_cb(struct client *cl, char *buf, int len)
207 newline = strstr(buf, "\r\n");
211 if (newline == buf) {
212 ustream_consume(cl->us, 2);
217 blob_buf_init(&cl->hdr, 0);
218 cl->state = client_parse_request(cl, buf);
219 ustream_consume(cl->us, newline + 2 - buf);
220 if (cl->state == CLIENT_STATE_DONE)
221 uh_header_error(cl, 400, "Bad Request");
226 static bool rfc1918_filter_check(struct client *cl)
228 if (!conf.rfc1918_filter)
231 if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
234 uh_client_error(cl, 403, "Forbidden",
235 "Rejected request from RFC1918 IP "
236 "to public server address");
240 static bool tls_redirect_check(struct client *cl)
243 struct blob_attr *cur;
244 char *ptr, *url = NULL, *host = NULL;
246 if (cl->tls || !conf.tls_redirect)
249 if ((port = uh_first_tls_port(cl->srv_addr.family)) == -1)
252 blob_for_each_attr(cur, cl->hdr.head, rem) {
253 if (!strcmp(blobmsg_name(cur), "host"))
254 host = blobmsg_get_string(cur);
256 if (!strcmp(blobmsg_name(cur), "URL"))
257 url = blobmsg_get_string(cur);
266 if ((ptr = strchr(host, ']')) != NULL)
268 else if ((ptr = strchr(host, ':')) != NULL)
271 cl->request.disable_chunked = true;
272 cl->request.connection_close = true;
274 uh_http_header(cl, 307, "Temporary Redirect");
277 ustream_printf(cl->us, "Location: https://%s:%d%s\r\n\r\n", host, port, url);
279 ustream_printf(cl->us, "Location: https://%s%s\r\n\r\n", host, url);
286 static void client_header_complete(struct client *cl)
288 struct http_request *r = &cl->request;
290 if (!rfc1918_filter_check(cl))
293 if (!tls_redirect_check(cl))
297 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
301 if (r->method != UH_HTTP_MSG_POST)
306 r->connection_close = true;
312 uh_handle_request(cl);
315 static void client_parse_header(struct client *cl, char *data)
317 struct http_request *r = &cl->request;
323 uloop_timeout_cancel(&cl->timeout);
324 cl->state = CLIENT_STATE_DATA;
325 client_header_complete(cl);
329 val = uh_split_header(data);
331 cl->state = CLIENT_STATE_DONE;
335 for (name = data; *name; name++)
337 *name = tolower(*name);
339 if (!strcmp(data, "expect")) {
340 if (!strcasecmp(val, "100-continue"))
341 r->expect_cont = true;
343 uh_header_error(cl, 412, "Precondition Failed");
346 } else if (!strcmp(data, "content-length")) {
347 r->content_length = strtoul(val, &err, 0);
348 if ((err && *err) || r->content_length < 0) {
349 uh_header_error(cl, 400, "Bad Request");
352 } else if (!strcmp(data, "transfer-encoding")) {
353 if (!strcmp(val, "chunked"))
354 r->transfer_chunked = true;
355 } else if (!strcmp(data, "connection")) {
356 if (!strcasecmp(val, "close"))
357 r->connection_close = true;
358 } else if (!strcmp(data, "user-agent")) {
361 if (strstr(val, "Opera"))
363 else if ((str = strstr(val, "MSIE ")) != NULL) {
364 r->ua = UH_UA_MSIE_NEW;
365 if (str[5] && str[6] == '.') {
368 if (strstr(str, "SV1"))
373 r->ua = UH_UA_MSIE_OLD;
378 else if (strstr(val, "Chrome/"))
379 r->ua = UH_UA_CHROME;
380 else if (strstr(val, "Safari/") && strstr(val, "Mac OS X"))
381 r->ua = UH_UA_SAFARI;
382 else if (strstr(val, "Gecko/"))
384 else if (strstr(val, "Konqueror"))
385 r->ua = UH_UA_KONQUEROR;
389 blobmsg_add_string(&cl->hdr, data, val);
391 cl->state = CLIENT_STATE_HEADER;
394 void client_poll_post_data(struct client *cl)
396 struct dispatch *d = &cl->dispatch;
397 struct http_request *r = &cl->request;
401 if (cl->state == CLIENT_STATE_DONE)
409 buf = ustream_get_read_buf(cl->us, &len);
416 cur_len = min(r->content_length, len);
422 cur_len = d->data_send(cl, buf, cur_len);
424 r->content_length -= cur_len;
425 ustream_consume(cl->us, cur_len);
429 if (!r->transfer_chunked)
432 if (r->transfer_chunked > 1)
435 sep = strstr(buf + offset, "\r\n");
441 r->content_length = strtoul(buf + offset, &sep, 16);
442 r->transfer_chunked++;
443 ustream_consume(cl->us, sep + 2 - buf);
445 /* invalid chunk length */
446 if ((sep && *sep) || r->content_length < 0) {
447 r->content_length = 0;
448 r->transfer_chunked = 0;
452 /* empty chunk == eof */
453 if (!r->content_length) {
454 r->transfer_chunked = false;
459 buf = ustream_get_read_buf(cl->us, &len);
460 if (!r->content_length && !r->transfer_chunked &&
461 cl->state != CLIENT_STATE_DONE) {
462 if (cl->dispatch.data_done)
463 cl->dispatch.data_done(cl);
465 cl->state = CLIENT_STATE_DONE;
469 static bool client_data_cb(struct client *cl, char *buf, int len)
471 client_poll_post_data(cl);
475 static bool client_header_cb(struct client *cl, char *buf, int len)
480 newline = strstr(buf, "\r\n");
485 client_parse_header(cl, buf);
486 line_len = newline + 2 - buf;
487 ustream_consume(cl->us, line_len);
488 if (cl->state == CLIENT_STATE_DATA)
489 return client_data_cb(cl, newline + 2, len - line_len);
494 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
495 static read_cb_t read_cbs[] = {
496 [CLIENT_STATE_INIT] = client_init_cb,
497 [CLIENT_STATE_HEADER] = client_header_cb,
498 [CLIENT_STATE_DATA] = client_data_cb,
501 void uh_client_read_cb(struct client *cl)
503 struct ustream *us = cl->us;
509 str = ustream_get_read_buf(us, &len);
513 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
516 if (!read_cbs[cl->state](cl, str, len)) {
517 if (len == us->r.buffer_len &&
518 cl->state != CLIENT_STATE_DATA)
519 uh_header_error(cl, 413, "Request Entity Too Large");
522 } while (!client_done);
525 static void client_close(struct client *cl)
528 cl->state = CLIENT_STATE_CLEANUP;
534 uh_dispatch_done(cl);
535 uloop_timeout_cancel(&cl->timeout);
537 uh_tls_client_detach(cl);
538 ustream_free(&cl->sfd.stream);
539 close(cl->sfd.fd.fd);
541 blob_buf_free(&cl->hdr);
542 blob_buf_free(&cl->hdr_response);
545 uh_unblock_listeners();
548 void uh_client_notify_state(struct client *cl)
550 struct ustream *s = cl->us;
552 if (!s->write_error && cl->state != CLIENT_STATE_CLEANUP) {
553 if (cl->state == CLIENT_STATE_DATA)
556 if (!s->eof || s->w.data_bytes)
560 if (cl->tls && cl->ssl.conn && cl->ssl.conn->w.data_bytes) {
561 cl->ssl.conn->eof = s->eof;
562 if (!ustream_write_pending(cl->ssl.conn))
568 return client_close(cl);
571 static void client_ustream_read_cb(struct ustream *s, int bytes)
573 struct client *cl = container_of(s, struct client, sfd.stream);
575 uh_client_read_cb(cl);
578 static void client_ustream_write_cb(struct ustream *s, int bytes)
580 struct client *cl = container_of(s, struct client, sfd.stream);
582 if (cl->dispatch.write_cb)
583 cl->dispatch.write_cb(cl);
586 static void client_notify_state(struct ustream *s)
588 struct client *cl = container_of(s, struct client, sfd.stream);
590 uh_client_notify_state(cl);
593 static void set_addr(struct uh_addr *addr, void *src)
595 struct sockaddr_in *sin = src;
596 struct sockaddr_in6 *sin6 = src;
598 addr->family = sin->sin_family;
599 if (addr->family == AF_INET) {
600 addr->port = ntohs(sin->sin_port);
601 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
603 addr->port = ntohs(sin6->sin6_port);
604 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
608 bool uh_accept_client(int fd, bool tls)
610 static struct client *next_client;
614 static int client_id = 0;
615 struct sockaddr_in6 addr;
618 next_client = calloc(1, sizeof(*next_client));
623 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
627 set_addr(&cl->peer_addr, &addr);
629 getsockname(sfd, (struct sockaddr *) &addr, &sl);
630 set_addr(&cl->srv_addr, &addr);
632 cl->us = &cl->sfd.stream;
634 uh_tls_client_attach(cl);
636 cl->us->notify_read = client_ustream_read_cb;
637 cl->us->notify_write = client_ustream_write_cb;
638 cl->us->notify_state = client_notify_state;
641 cl->us->string_data = true;
642 ustream_fd_init(&cl->sfd, sfd);
644 uh_poll_connection(cl);
645 list_add_tail(&cl->list, &clients);
649 cl->id = client_id++;
655 void uh_close_fds(void)
660 uh_close_listen_fds();
661 list_for_each_entry(cl, &clients, list) {
662 close(cl->sfd.fd.fd);
663 if (cl->dispatch.close_fds)
664 cl->dispatch.close_fds(cl);