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",
44 void uh_http_header(struct client *cl, int code, const char *summary)
46 struct http_request *r = &cl->request;
47 const char *enc = "Transfer-Encoding: chunked\r\n";
50 if (!uh_use_chunked(cl))
53 if (r->connection_close)
54 conn = "Connection: close";
56 conn = "Connection: Keep-Alive";
58 ustream_printf(cl->us, "%s %03i %s\r\n%s\r\n%s",
59 http_versions[cl->request.version],
60 code, summary, conn, enc);
62 if (!r->connection_close)
63 ustream_printf(cl->us, "Keep-Alive: timeout=%d\r\n", conf.http_keepalive);
66 static void uh_connection_close(struct client *cl)
68 cl->state = CLIENT_STATE_CLOSE;
70 ustream_state_change(cl->us);
73 static void uh_dispatch_done(struct client *cl)
75 if (cl->dispatch.free)
76 cl->dispatch.free(cl);
77 if (cl->dispatch.req_free)
78 cl->dispatch.req_free(cl);
81 static void client_timeout(struct uloop_timeout *timeout)
83 struct client *cl = container_of(timeout, struct client, timeout);
85 cl->state = CLIENT_STATE_CLOSE;
86 uh_connection_close(cl);
89 static void uh_set_client_timeout(struct client *cl, int timeout)
91 cl->timeout.cb = client_timeout;
92 uloop_timeout_set(&cl->timeout, timeout * 1000);
95 static void uh_keepalive_poll_cb(struct uloop_timeout *timeout)
97 struct client *cl = container_of(timeout, struct client, timeout);
98 int sec = cl->requests > 0 ? conf.http_keepalive : conf.network_timeout;
100 uh_set_client_timeout(cl, sec);
101 cl->us->notify_read(cl->us, 0);
104 static void uh_poll_connection(struct client *cl)
106 cl->timeout.cb = uh_keepalive_poll_cb;
107 uloop_timeout_set(&cl->timeout, 1);
110 void uh_request_done(struct client *cl)
113 uh_dispatch_done(cl);
114 memset(&cl->dispatch, 0, sizeof(cl->dispatch));
116 if (!conf.http_keepalive || cl->request.connection_close)
117 return uh_connection_close(cl);
119 cl->state = CLIENT_STATE_INIT;
121 uh_poll_connection(cl);
125 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
129 uh_http_header(cl, code, summary);
130 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
132 uh_chunk_printf(cl, "<h1>%s</h1>", summary);
136 uh_chunk_vprintf(cl, fmt, arg);
143 static void uh_header_error(struct client *cl, int code, const char *summary)
145 uh_client_error(cl, code, summary, NULL);
146 uh_connection_close(cl);
149 static int find_idx(const char * const *list, int max, const char *str)
153 for (i = 0; i < max; i++)
154 if (!strcmp(list[i], str))
160 static int client_parse_request(struct client *cl, char *data)
162 struct http_request *req = &cl->request;
163 char *type, *path, *version;
164 int h_method, h_version;
166 type = strtok(data, " ");
167 path = strtok(NULL, " ");
168 version = strtok(NULL, " ");
169 if (!type || !path || !version)
170 return CLIENT_STATE_DONE;
172 blobmsg_add_string(&cl->hdr, "URL", path);
174 memset(&cl->request, 0, sizeof(cl->request));
175 h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
176 h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
177 if (h_method < 0 || h_version < 0) {
178 req->version = UH_HTTP_VER_1_0;
179 return CLIENT_STATE_DONE;
182 req->method = h_method;
183 req->version = h_version;
184 if (req->version < UH_HTTP_VER_1_1 || req->method == UH_HTTP_MSG_POST ||
185 !conf.http_keepalive)
186 req->connection_close = true;
188 return CLIENT_STATE_HEADER;
191 static bool client_init_cb(struct client *cl, char *buf, int len)
195 newline = strstr(buf, "\r\n");
199 if (newline == buf) {
200 ustream_consume(cl->us, 2);
205 blob_buf_init(&cl->hdr, 0);
206 cl->state = client_parse_request(cl, buf);
207 ustream_consume(cl->us, newline + 2 - buf);
208 if (cl->state == CLIENT_STATE_DONE)
209 uh_header_error(cl, 400, "Bad Request");
214 static bool rfc1918_filter_check(struct client *cl)
216 if (!conf.rfc1918_filter)
219 if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
222 uh_client_error(cl, 403, "Forbidden",
223 "Rejected request from RFC1918 IP "
224 "to public server address");
228 static void client_header_complete(struct client *cl)
230 struct http_request *r = &cl->request;
232 if (!rfc1918_filter_check(cl))
236 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
240 if (r->method != UH_HTTP_MSG_POST)
245 r->connection_close = true;
251 uh_handle_request(cl);
254 static void client_parse_header(struct client *cl, char *data)
256 struct http_request *r = &cl->request;
262 uloop_timeout_cancel(&cl->timeout);
263 cl->state = CLIENT_STATE_DATA;
264 client_header_complete(cl);
268 val = uh_split_header(data);
270 cl->state = CLIENT_STATE_DONE;
274 for (name = data; *name; name++)
276 *name = tolower(*name);
278 if (!strcmp(data, "expect")) {
279 if (!strcasecmp(val, "100-continue"))
280 r->expect_cont = true;
282 uh_header_error(cl, 412, "Precondition Failed");
285 } else if (!strcmp(data, "content-length")) {
286 r->content_length = strtoul(val, &err, 0);
288 uh_header_error(cl, 400, "Bad Request");
291 } else if (!strcmp(data, "transfer-encoding")) {
292 if (!strcmp(val, "chunked"))
293 r->transfer_chunked = true;
294 } else if (!strcmp(data, "connection")) {
295 if (!strcasecmp(val, "close"))
296 r->connection_close = true;
297 } else if (!strcmp(data, "user-agent")) {
300 if (strstr(val, "Opera"))
302 else if ((str = strstr(val, "MSIE ")) != NULL) {
303 r->ua = UH_UA_MSIE_NEW;
304 if (str[5] && str[6] == '.') {
307 if (strstr(str, "SV1"))
312 r->ua = UH_UA_MSIE_OLD;
317 else if (strstr(val, "Chrome/"))
318 r->ua = UH_UA_CHROME;
319 else if (strstr(val, "Safari/") && strstr(val, "Mac OS X"))
320 r->ua = UH_UA_SAFARI;
321 else if (strstr(val, "Gecko/"))
323 else if (strstr(val, "Konqueror"))
324 r->ua = UH_UA_KONQUEROR;
328 blobmsg_add_string(&cl->hdr, data, val);
330 cl->state = CLIENT_STATE_HEADER;
333 void client_poll_post_data(struct client *cl)
335 struct dispatch *d = &cl->dispatch;
336 struct http_request *r = &cl->request;
340 if (cl->state == CLIENT_STATE_DONE)
348 buf = ustream_get_read_buf(cl->us, &len);
355 cur_len = min(r->content_length, len);
361 cur_len = d->data_send(cl, buf, cur_len);
363 r->content_length -= cur_len;
364 ustream_consume(cl->us, cur_len);
368 if (!r->transfer_chunked)
371 if (r->transfer_chunked > 1)
374 sep = strstr(buf + offset, "\r\n");
380 r->content_length = strtoul(buf + offset, &sep, 16);
381 r->transfer_chunked++;
382 ustream_consume(cl->us, sep + 2 - buf);
384 /* invalid chunk length */
386 r->content_length = 0;
387 r->transfer_chunked = 0;
391 /* empty chunk == eof */
392 if (!r->content_length) {
393 r->transfer_chunked = false;
398 buf = ustream_get_read_buf(cl->us, &len);
399 if (!r->content_length && !r->transfer_chunked &&
400 cl->state != CLIENT_STATE_DONE) {
401 if (cl->dispatch.data_done)
402 cl->dispatch.data_done(cl);
404 cl->state = CLIENT_STATE_DONE;
408 static bool client_data_cb(struct client *cl, char *buf, int len)
410 client_poll_post_data(cl);
414 static bool client_header_cb(struct client *cl, char *buf, int len)
419 newline = strstr(buf, "\r\n");
424 client_parse_header(cl, buf);
425 line_len = newline + 2 - buf;
426 ustream_consume(cl->us, line_len);
427 if (cl->state == CLIENT_STATE_DATA)
428 return client_data_cb(cl, newline + 2, len - line_len);
433 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
434 static read_cb_t read_cbs[] = {
435 [CLIENT_STATE_INIT] = client_init_cb,
436 [CLIENT_STATE_HEADER] = client_header_cb,
437 [CLIENT_STATE_DATA] = client_data_cb,
440 void uh_client_read_cb(struct client *cl)
442 struct ustream *us = cl->us;
448 str = ustream_get_read_buf(us, &len);
452 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
455 if (!read_cbs[cl->state](cl, str, len)) {
456 if (len == us->r.buffer_len &&
457 cl->state != CLIENT_STATE_DATA)
458 uh_header_error(cl, 413, "Request Entity Too Large");
461 } while (!client_done);
464 static void client_close(struct client *cl)
468 uh_dispatch_done(cl);
469 uloop_timeout_cancel(&cl->timeout);
471 uh_tls_client_detach(cl);
472 ustream_free(&cl->sfd.stream);
473 close(cl->sfd.fd.fd);
475 blob_buf_free(&cl->hdr);
478 uh_unblock_listeners();
481 void uh_client_notify_state(struct client *cl)
483 struct ustream *s = cl->us;
485 if (!s->write_error) {
486 if (cl->state == CLIENT_STATE_DATA)
489 if (!s->eof || s->w.data_bytes)
493 return client_close(cl);
496 static void client_ustream_read_cb(struct ustream *s, int bytes)
498 struct client *cl = container_of(s, struct client, sfd.stream);
500 uh_client_read_cb(cl);
503 static void client_ustream_write_cb(struct ustream *s, int bytes)
505 struct client *cl = container_of(s, struct client, sfd.stream);
507 if (cl->dispatch.write_cb)
508 cl->dispatch.write_cb(cl);
511 static void client_notify_state(struct ustream *s)
513 struct client *cl = container_of(s, struct client, sfd.stream);
515 uh_client_notify_state(cl);
518 static void set_addr(struct uh_addr *addr, void *src)
520 struct sockaddr_in *sin = src;
521 struct sockaddr_in6 *sin6 = src;
523 addr->family = sin->sin_family;
524 if (addr->family == AF_INET) {
525 addr->port = ntohs(sin->sin_port);
526 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
528 addr->port = ntohs(sin6->sin6_port);
529 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
533 bool uh_accept_client(int fd, bool tls)
535 static struct client *next_client;
539 static int client_id = 0;
540 struct sockaddr_in6 addr;
543 next_client = calloc(1, sizeof(*next_client));
548 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
552 set_addr(&cl->peer_addr, &addr);
554 getsockname(sfd, (struct sockaddr *) &addr, &sl);
555 set_addr(&cl->srv_addr, &addr);
557 cl->us = &cl->sfd.stream;
559 uh_tls_client_attach(cl);
561 cl->us->notify_read = client_ustream_read_cb;
562 cl->us->notify_write = client_ustream_write_cb;
563 cl->us->notify_state = client_notify_state;
566 cl->us->string_data = true;
567 ustream_fd_init(&cl->sfd, sfd);
569 uh_poll_connection(cl);
570 list_add_tail(&cl->list, &clients);
574 cl->id = client_id++;
580 void uh_close_fds(void)
585 uh_close_listen_fds();
586 list_for_each_entry(cl, &clients, list) {
587 close(cl->sfd.fd.fd);
588 if (cl->dispatch.close_fds)
589 cl->dispatch.close_fds(cl);