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);
29 struct config conf = {};
31 const char * const http_versions[] = {
32 [UH_HTTP_VER_0_9] = "HTTP/0.9",
33 [UH_HTTP_VER_1_0] = "HTTP/1.0",
34 [UH_HTTP_VER_1_1] = "HTTP/1.1",
37 const char * const http_methods[] = {
38 [UH_HTTP_MSG_GET] = "GET",
39 [UH_HTTP_MSG_POST] = "POST",
40 [UH_HTTP_MSG_HEAD] = "HEAD",
43 void uh_http_header(struct client *cl, int code, const char *summary)
45 struct http_request *r = &cl->request;
46 const char *enc = "Transfer-Encoding: chunked\r\n";
49 if (!uh_use_chunked(cl))
52 if (r->connection_close)
53 conn = "Connection: close";
55 conn = "Connection: Keep-Alive";
57 ustream_printf(cl->us, "%s %03i %s\r\n%s\r\n%s",
58 http_versions[cl->request.version],
59 code, summary, conn, enc);
61 if (!r->connection_close)
62 ustream_printf(cl->us, "Keep-Alive: timeout=%d\r\n", conf.http_keepalive);
65 static void uh_connection_close(struct client *cl)
67 cl->state = CLIENT_STATE_CLOSE;
69 ustream_state_change(cl->us);
72 static void uh_dispatch_done(struct client *cl)
74 if (cl->dispatch.free)
75 cl->dispatch.free(cl);
78 static void client_timeout(struct uloop_timeout *timeout)
80 struct client *cl = container_of(timeout, struct client, timeout);
82 cl->state = CLIENT_STATE_CLOSE;
83 uh_connection_close(cl);
86 static void uh_set_client_timeout(struct client *cl, int timeout)
88 cl->timeout.cb = client_timeout;
89 uloop_timeout_set(&cl->timeout, timeout * 1000);
92 static void uh_keepalive_poll_cb(struct uloop_timeout *timeout)
94 struct client *cl = container_of(timeout, struct client, timeout);
96 uh_set_client_timeout(cl, conf.http_keepalive);
97 cl->us->notify_read(cl->us, 0);
100 void uh_request_done(struct client *cl)
103 uh_dispatch_done(cl);
104 cl->us->notify_write = NULL;
105 memset(&cl->dispatch, 0, sizeof(cl->dispatch));
107 if (!conf.http_keepalive || cl->request.connection_close)
108 return uh_connection_close(cl);
110 cl->state = CLIENT_STATE_INIT;
111 cl->timeout.cb = uh_keepalive_poll_cb;
112 uloop_timeout_set(&cl->timeout, 1);
116 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
120 uh_http_header(cl, code, summary);
121 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
123 uh_chunk_printf(cl, "<h1>%s</h1>", summary);
127 uh_chunk_vprintf(cl, fmt, arg);
134 static void uh_header_error(struct client *cl, int code, const char *summary)
136 uh_client_error(cl, code, summary, NULL);
137 uh_connection_close(cl);
140 static int find_idx(const char * const *list, int max, const char *str)
144 for (i = 0; i < max; i++)
145 if (!strcmp(list[i], str))
151 static int client_parse_request(struct client *cl, char *data)
153 struct http_request *req = &cl->request;
154 char *type, *path, *version;
155 int h_method, h_version;
157 type = strtok(data, " ");
158 path = strtok(NULL, " ");
159 version = strtok(NULL, " ");
160 if (!type || !path || !version)
161 return CLIENT_STATE_DONE;
163 blobmsg_add_string(&cl->hdr, "URL", path);
165 memset(&cl->request, 0, sizeof(cl->request));
166 h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
167 h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
168 if (h_method < 0 || h_version < 0) {
169 req->version = UH_HTTP_VER_1_0;
170 return CLIENT_STATE_DONE;
173 req->method = h_method;
174 req->version = h_version;
175 if (req->version < UH_HTTP_VER_1_1 || !conf.http_keepalive)
176 req->connection_close = true;
178 return CLIENT_STATE_HEADER;
181 static bool client_init_cb(struct client *cl, char *buf, int len)
185 newline = strstr(buf, "\r\n");
190 blob_buf_init(&cl->hdr, 0);
191 cl->state = client_parse_request(cl, buf);
192 ustream_consume(cl->us, newline + 2 - buf);
193 if (cl->state == CLIENT_STATE_DONE)
194 uh_header_error(cl, 400, "Bad Request");
199 static bool rfc1918_filter_check(struct client *cl)
201 if (!conf.rfc1918_filter)
204 if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
207 uh_client_error(cl, 403, "Forbidden",
208 "Rejected request from RFC1918 IP "
209 "to public server address");
213 static void client_header_complete(struct client *cl)
215 struct http_request *r = &cl->request;
217 if (!rfc1918_filter_check(cl))
221 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
225 if (r->method != UH_HTTP_MSG_POST)
230 r->connection_close = true;
236 uh_handle_request(cl);
239 static void client_parse_header(struct client *cl, char *data)
241 struct http_request *r = &cl->request;
247 uloop_timeout_cancel(&cl->timeout);
248 cl->state = CLIENT_STATE_DATA;
249 client_header_complete(cl);
253 val = uh_split_header(data);
255 cl->state = CLIENT_STATE_DONE;
259 for (name = data; *name; name++)
261 *name = tolower(*name);
263 if (!strcmp(data, "expect")) {
264 if (!strcasecmp(val, "100-continue"))
265 r->expect_cont = true;
267 uh_header_error(cl, 412, "Precondition Failed");
270 } else if (!strcmp(data, "content-length")) {
271 r->content_length = strtoul(val, &err, 0);
273 uh_header_error(cl, 400, "Bad Request");
276 } else if (!strcmp(data, "transfer-encoding")) {
277 if (!strcmp(val, "chunked"))
278 r->transfer_chunked = true;
279 } else if (!strcmp(data, "connection")) {
280 if (!strcasecmp(val, "close"))
281 r->connection_close = true;
282 else if (!strcasecmp(val, "keep-alive"))
283 r->connection_close = false;
284 } else if (!strcmp(data, "user-agent")) {
287 if (strstr(val, "Opera"))
289 else if ((str = strstr(val, "MSIE ")) != NULL) {
290 r->ua = UH_UA_MSIE_NEW;
291 if (str[5] && str[6] == '.') {
294 if (strstr(str, "SV1"))
299 r->ua = UH_UA_MSIE_OLD;
303 } else if (strstr(val, "Safari/") && strstr(val, "Mac OS X"))
304 r->ua = UH_UA_SAFARI;
305 else if (strstr(val, "Chrome/"))
306 r->ua = UH_UA_CHROME;
307 else if (strstr(val, "Gecko/"))
309 else if (strstr(val, "Konqueror"))
310 r->ua = UH_UA_KONQUEROR;
314 blobmsg_add_string(&cl->hdr, data, val);
316 cl->state = CLIENT_STATE_HEADER;
319 void client_poll_post_data(struct client *cl)
321 struct dispatch *d = &cl->dispatch;
322 struct http_request *r = &cl->request;
326 if (cl->state == CLIENT_STATE_DONE)
334 buf = ustream_get_read_buf(cl->us, &len);
341 cur_len = min(r->content_length, len);
347 cur_len = d->data_send(cl, buf, cur_len);
349 r->content_length -= cur_len;
350 ustream_consume(cl->us, cur_len);
354 if (!r->transfer_chunked)
357 if (r->transfer_chunked > 1)
360 sep = strstr(buf + offset, "\r\n");
366 r->content_length = strtoul(buf + offset, &sep, 16);
367 r->transfer_chunked++;
368 ustream_consume(cl->us, sep + 2 - buf);
370 /* invalid chunk length */
372 r->content_length = 0;
373 r->transfer_chunked = 0;
377 /* empty chunk == eof */
378 if (!r->content_length) {
379 r->transfer_chunked = false;
384 buf = ustream_get_read_buf(cl->us, &len);
385 if (!r->content_length && !r->transfer_chunked &&
386 cl->state != CLIENT_STATE_DONE) {
387 if (cl->dispatch.data_done)
388 cl->dispatch.data_done(cl);
390 cl->state = CLIENT_STATE_DONE;
394 static bool client_data_cb(struct client *cl, char *buf, int len)
396 client_poll_post_data(cl);
400 static bool client_header_cb(struct client *cl, char *buf, int len)
405 newline = strstr(buf, "\r\n");
410 client_parse_header(cl, buf);
411 line_len = newline + 2 - buf;
412 ustream_consume(cl->us, line_len);
413 if (cl->state == CLIENT_STATE_DATA)
414 return client_data_cb(cl, newline + 2, len - line_len);
419 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
420 static read_cb_t read_cbs[] = {
421 [CLIENT_STATE_INIT] = client_init_cb,
422 [CLIENT_STATE_HEADER] = client_header_cb,
423 [CLIENT_STATE_DATA] = client_data_cb,
426 void uh_client_read_cb(struct client *cl)
428 struct ustream *us = cl->us;
433 str = ustream_get_read_buf(us, &len);
437 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
440 if (!read_cbs[cl->state](cl, str, len)) {
441 if (len == us->r.buffer_len &&
442 cl->state != CLIENT_STATE_DATA)
443 uh_header_error(cl, 413, "Request Entity Too Large");
449 static void client_close(struct client *cl)
452 uh_dispatch_done(cl);
453 uloop_timeout_cancel(&cl->timeout);
455 uh_tls_client_detach(cl);
456 ustream_free(&cl->sfd.stream);
457 close(cl->sfd.fd.fd);
459 blob_buf_free(&cl->hdr);
462 uh_unblock_listeners();
465 void uh_client_notify_state(struct client *cl)
467 struct ustream *s = cl->us;
469 if (!s->write_error) {
470 if (cl->state == CLIENT_STATE_DATA)
473 if (!s->eof || s->w.data_bytes)
477 return client_close(cl);
480 static void client_ustream_read_cb(struct ustream *s, int bytes)
482 struct client *cl = container_of(s, struct client, sfd);
484 uh_client_read_cb(cl);
487 static void client_ustream_write_cb(struct ustream *s, int bytes)
489 struct client *cl = container_of(s, struct client, sfd);
491 if (cl->dispatch.write_cb)
492 cl->dispatch.write_cb(cl);
495 static void client_notify_state(struct ustream *s)
497 struct client *cl = container_of(s, struct client, sfd);
499 uh_client_notify_state(cl);
502 static void set_addr(struct uh_addr *addr, void *src)
504 struct sockaddr_in *sin = src;
505 struct sockaddr_in6 *sin6 = src;
507 addr->family = sin->sin_family;
508 if (addr->family == AF_INET) {
509 addr->port = ntohs(sin->sin_port);
510 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
512 addr->port = ntohs(sin6->sin6_port);
513 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
517 bool uh_accept_client(int fd, bool tls)
519 static struct client *next_client;
523 static int client_id = 0;
524 struct sockaddr_in6 addr;
527 next_client = calloc(1, sizeof(*next_client));
532 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
536 set_addr(&cl->peer_addr, &addr);
538 getsockname(sfd, (struct sockaddr *) &addr, &sl);
539 set_addr(&cl->srv_addr, &addr);
541 cl->us = &cl->sfd.stream;
543 uh_tls_client_attach(cl);
545 cl->us->notify_read = client_ustream_read_cb;
546 cl->us->notify_write = client_ustream_write_cb;
547 cl->us->notify_state = client_notify_state;
550 cl->us->string_data = true;
551 ustream_fd_init(&cl->sfd, sfd);
553 uh_set_client_timeout(cl, conf.network_timeout);
554 list_add_tail(&cl->list, &clients);
558 cl->id = client_id++;
563 void uh_close_fds(void)
568 uh_close_listen_fds();
569 list_for_each_entry(cl, &clients, list) {
570 close(cl->sfd.fd.fd);
571 if (cl->dispatch.close_fds)
572 cl->dispatch.close_fds(cl);