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 || req->method == UH_HTTP_MSG_POST ||
198 !conf.http_keepalive)
199 req->connection_close = true;
201 return CLIENT_STATE_HEADER;
204 static bool client_init_cb(struct client *cl, char *buf, int len)
208 newline = strstr(buf, "\r\n");
212 if (newline == buf) {
213 ustream_consume(cl->us, 2);
218 blob_buf_init(&cl->hdr, 0);
219 cl->state = client_parse_request(cl, buf);
220 ustream_consume(cl->us, newline + 2 - buf);
221 if (cl->state == CLIENT_STATE_DONE)
222 uh_header_error(cl, 400, "Bad Request");
227 static bool rfc1918_filter_check(struct client *cl)
229 if (!conf.rfc1918_filter)
232 if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
235 uh_client_error(cl, 403, "Forbidden",
236 "Rejected request from RFC1918 IP "
237 "to public server address");
241 static bool tls_redirect_check(struct client *cl)
244 struct blob_attr *cur;
245 char *ptr, *url = NULL, *host = NULL;
247 if (cl->tls || !conf.tls_redirect)
250 if ((port = uh_first_tls_port(cl->srv_addr.family)) == -1)
253 blob_for_each_attr(cur, cl->hdr.head, rem) {
254 if (!strcmp(blobmsg_name(cur), "host"))
255 host = blobmsg_get_string(cur);
257 if (!strcmp(blobmsg_name(cur), "URL"))
258 url = blobmsg_get_string(cur);
267 if ((ptr = strchr(host, ']')) != NULL)
269 else if ((ptr = strchr(host, ':')) != NULL)
272 cl->request.disable_chunked = true;
273 cl->request.connection_close = true;
275 uh_http_header(cl, 307, "Temporary Redirect");
278 ustream_printf(cl->us, "Location: https://%s:%d%s\r\n\r\n", host, port, url);
280 ustream_printf(cl->us, "Location: https://%s%s\r\n\r\n", host, url);
287 static void client_header_complete(struct client *cl)
289 struct http_request *r = &cl->request;
291 if (!rfc1918_filter_check(cl))
294 if (!tls_redirect_check(cl))
298 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
302 if (r->method != UH_HTTP_MSG_POST)
307 r->connection_close = true;
313 uh_handle_request(cl);
316 static void client_parse_header(struct client *cl, char *data)
318 struct http_request *r = &cl->request;
324 uloop_timeout_cancel(&cl->timeout);
325 cl->state = CLIENT_STATE_DATA;
326 client_header_complete(cl);
330 val = uh_split_header(data);
332 cl->state = CLIENT_STATE_DONE;
336 for (name = data; *name; name++)
338 *name = tolower(*name);
340 if (!strcmp(data, "expect")) {
341 if (!strcasecmp(val, "100-continue"))
342 r->expect_cont = true;
344 uh_header_error(cl, 412, "Precondition Failed");
347 } else if (!strcmp(data, "content-length")) {
348 r->content_length = strtoul(val, &err, 0);
349 if ((err && *err) || r->content_length < 0) {
350 uh_header_error(cl, 400, "Bad Request");
353 } else if (!strcmp(data, "transfer-encoding")) {
354 if (!strcmp(val, "chunked"))
355 r->transfer_chunked = true;
356 } else if (!strcmp(data, "connection")) {
357 if (!strcasecmp(val, "close"))
358 r->connection_close = true;
359 } else if (!strcmp(data, "user-agent")) {
362 if (strstr(val, "Opera"))
364 else if ((str = strstr(val, "MSIE ")) != NULL) {
365 r->ua = UH_UA_MSIE_NEW;
366 if (str[5] && str[6] == '.') {
369 if (strstr(str, "SV1"))
374 r->ua = UH_UA_MSIE_OLD;
379 else if (strstr(val, "Chrome/"))
380 r->ua = UH_UA_CHROME;
381 else if (strstr(val, "Safari/") && strstr(val, "Mac OS X"))
382 r->ua = UH_UA_SAFARI;
383 else if (strstr(val, "Gecko/"))
385 else if (strstr(val, "Konqueror"))
386 r->ua = UH_UA_KONQUEROR;
390 blobmsg_add_string(&cl->hdr, data, val);
392 cl->state = CLIENT_STATE_HEADER;
395 void client_poll_post_data(struct client *cl)
397 struct dispatch *d = &cl->dispatch;
398 struct http_request *r = &cl->request;
402 if (cl->state == CLIENT_STATE_DONE)
410 buf = ustream_get_read_buf(cl->us, &len);
417 cur_len = min(r->content_length, len);
423 cur_len = d->data_send(cl, buf, cur_len);
425 r->content_length -= cur_len;
426 ustream_consume(cl->us, cur_len);
430 if (!r->transfer_chunked)
433 if (r->transfer_chunked > 1)
436 sep = strstr(buf + offset, "\r\n");
442 r->content_length = strtoul(buf + offset, &sep, 16);
443 r->transfer_chunked++;
444 ustream_consume(cl->us, sep + 2 - buf);
446 /* invalid chunk length */
447 if ((sep && *sep) || r->content_length < 0) {
448 r->content_length = 0;
449 r->transfer_chunked = 0;
453 /* empty chunk == eof */
454 if (!r->content_length) {
455 r->transfer_chunked = false;
460 buf = ustream_get_read_buf(cl->us, &len);
461 if (!r->content_length && !r->transfer_chunked &&
462 cl->state != CLIENT_STATE_DONE) {
463 if (cl->dispatch.data_done)
464 cl->dispatch.data_done(cl);
466 cl->state = CLIENT_STATE_DONE;
470 static bool client_data_cb(struct client *cl, char *buf, int len)
472 client_poll_post_data(cl);
476 static bool client_header_cb(struct client *cl, char *buf, int len)
481 newline = strstr(buf, "\r\n");
486 client_parse_header(cl, buf);
487 line_len = newline + 2 - buf;
488 ustream_consume(cl->us, line_len);
489 if (cl->state == CLIENT_STATE_DATA)
490 return client_data_cb(cl, newline + 2, len - line_len);
495 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
496 static read_cb_t read_cbs[] = {
497 [CLIENT_STATE_INIT] = client_init_cb,
498 [CLIENT_STATE_HEADER] = client_header_cb,
499 [CLIENT_STATE_DATA] = client_data_cb,
502 void uh_client_read_cb(struct client *cl)
504 struct ustream *us = cl->us;
510 str = ustream_get_read_buf(us, &len);
514 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
517 if (!read_cbs[cl->state](cl, str, len)) {
518 if (len == us->r.buffer_len &&
519 cl->state != CLIENT_STATE_DATA)
520 uh_header_error(cl, 413, "Request Entity Too Large");
523 } while (!client_done);
526 static void client_close(struct client *cl)
529 cl->state = CLIENT_STATE_CLEANUP;
535 uh_dispatch_done(cl);
536 uloop_timeout_cancel(&cl->timeout);
538 uh_tls_client_detach(cl);
539 ustream_free(&cl->sfd.stream);
540 close(cl->sfd.fd.fd);
542 blob_buf_free(&cl->hdr);
543 blob_buf_free(&cl->hdr_response);
546 uh_unblock_listeners();
549 void uh_client_notify_state(struct client *cl)
551 struct ustream *s = cl->us;
553 if (!s->write_error && cl->state != CLIENT_STATE_CLEANUP) {
554 if (cl->state == CLIENT_STATE_DATA)
557 if (!s->eof || s->w.data_bytes)
561 if (cl->tls && cl->ssl.conn && cl->ssl.conn->w.data_bytes) {
562 cl->ssl.conn->eof = s->eof;
563 if (!ustream_write_pending(cl->ssl.conn))
569 return client_close(cl);
572 static void client_ustream_read_cb(struct ustream *s, int bytes)
574 struct client *cl = container_of(s, struct client, sfd.stream);
576 uh_client_read_cb(cl);
579 static void client_ustream_write_cb(struct ustream *s, int bytes)
581 struct client *cl = container_of(s, struct client, sfd.stream);
583 if (cl->dispatch.write_cb)
584 cl->dispatch.write_cb(cl);
587 static void client_notify_state(struct ustream *s)
589 struct client *cl = container_of(s, struct client, sfd.stream);
591 uh_client_notify_state(cl);
594 static void set_addr(struct uh_addr *addr, void *src)
596 struct sockaddr_in *sin = src;
597 struct sockaddr_in6 *sin6 = src;
599 addr->family = sin->sin_family;
600 if (addr->family == AF_INET) {
601 addr->port = ntohs(sin->sin_port);
602 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
604 addr->port = ntohs(sin6->sin6_port);
605 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
609 bool uh_accept_client(int fd, bool tls)
611 static struct client *next_client;
615 static int client_id = 0;
616 struct sockaddr_in6 addr;
619 next_client = calloc(1, sizeof(*next_client));
624 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
628 set_addr(&cl->peer_addr, &addr);
630 getsockname(sfd, (struct sockaddr *) &addr, &sl);
631 set_addr(&cl->srv_addr, &addr);
633 cl->us = &cl->sfd.stream;
635 uh_tls_client_attach(cl);
637 cl->us->notify_read = client_ustream_read_cb;
638 cl->us->notify_write = client_ustream_write_cb;
639 cl->us->notify_state = client_notify_state;
642 cl->us->string_data = true;
643 ustream_fd_init(&cl->sfd, sfd);
645 uh_poll_connection(cl);
646 list_add_tail(&cl->list, &clients);
650 cl->id = client_id++;
656 void uh_close_fds(void)
661 uh_close_listen_fds();
662 list_for_each_entry(cl, &clients, list) {
663 close(cl->sfd.fd.fd);
664 if (cl->dispatch.close_fds)
665 cl->dispatch.close_fds(cl);