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 void uh_request_done(struct client *cl)
82 cl->us->notify_write = NULL;
83 memset(&cl->dispatch, 0, sizeof(cl->dispatch));
85 if (!conf.http_keepalive || cl->request.connection_close)
86 return uh_connection_close(cl);
88 cl->state = CLIENT_STATE_INIT;
89 uloop_timeout_set(&cl->timeout, conf.http_keepalive * 1000);
93 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
97 uh_http_header(cl, code, summary);
98 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
100 uh_chunk_printf(cl, "<h1>%s</h1>", summary);
104 uh_chunk_vprintf(cl, fmt, arg);
111 static void uh_header_error(struct client *cl, int code, const char *summary)
113 uh_client_error(cl, code, summary, NULL);
114 uh_connection_close(cl);
117 static void client_timeout(struct uloop_timeout *timeout)
119 struct client *cl = container_of(timeout, struct client, timeout);
121 cl->state = CLIENT_STATE_CLOSE;
122 uh_connection_close(cl);
125 static int find_idx(const char * const *list, int max, const char *str)
129 for (i = 0; i < max; i++)
130 if (!strcmp(list[i], str))
136 static int client_parse_request(struct client *cl, char *data)
138 struct http_request *req = &cl->request;
139 char *type, *path, *version;
140 int h_method, h_version;
142 type = strtok(data, " ");
143 path = strtok(NULL, " ");
144 version = strtok(NULL, " ");
145 if (!type || !path || !version)
146 return CLIENT_STATE_DONE;
148 blobmsg_add_string(&cl->hdr, "URL", path);
150 memset(&cl->request, 0, sizeof(cl->request));
151 h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
152 h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
153 if (h_method < 0 || h_version < 0) {
154 req->version = UH_HTTP_VER_1_0;
155 return CLIENT_STATE_DONE;
158 req->method = h_method;
159 req->version = h_version;
160 if (req->version < UH_HTTP_VER_1_1 || !conf.http_keepalive)
161 req->connection_close = true;
163 return CLIENT_STATE_HEADER;
166 static bool client_init_cb(struct client *cl, char *buf, int len)
170 newline = strstr(buf, "\r\n");
175 blob_buf_init(&cl->hdr, 0);
176 cl->state = client_parse_request(cl, buf);
177 ustream_consume(cl->us, newline + 2 - buf);
178 if (cl->state == CLIENT_STATE_DONE)
179 uh_header_error(cl, 400, "Bad Request");
184 static bool rfc1918_filter_check(struct client *cl)
186 if (!conf.rfc1918_filter)
189 if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
192 uh_client_error(cl, 403, "Forbidden",
193 "Rejected request from RFC1918 IP "
194 "to public server address");
198 static void client_header_complete(struct client *cl)
200 struct http_request *r = &cl->request;
202 if (!rfc1918_filter_check(cl))
206 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
210 if (r->method != UH_HTTP_MSG_POST)
215 r->connection_close = true;
221 uh_handle_request(cl);
224 static void client_parse_header(struct client *cl, char *data)
226 struct http_request *r = &cl->request;
232 uloop_timeout_cancel(&cl->timeout);
233 cl->state = CLIENT_STATE_DATA;
234 client_header_complete(cl);
238 val = uh_split_header(data);
240 cl->state = CLIENT_STATE_DONE;
244 for (name = data; *name; name++)
246 *name = tolower(*name);
248 if (!strcmp(data, "expect")) {
249 if (!strcasecmp(val, "100-continue"))
250 r->expect_cont = true;
252 uh_header_error(cl, 412, "Precondition Failed");
255 } else if (!strcmp(data, "content-length")) {
256 r->content_length = strtoul(val, &err, 0);
258 uh_header_error(cl, 400, "Bad Request");
261 } else if (!strcmp(data, "transfer-encoding")) {
262 if (!strcmp(val, "chunked"))
263 r->transfer_chunked = true;
264 } else if (!strcmp(data, "connection")) {
265 if (!strcasecmp(val, "close"))
266 r->connection_close = true;
267 else if (!strcasecmp(val, "keep-alive"))
268 r->connection_close = false;
269 } else if (!strcmp(data, "user-agent")) {
272 if (strstr(val, "Opera"))
274 else if ((str = strstr(val, "MSIE ")) != NULL) {
275 r->ua = UH_UA_MSIE_NEW;
276 if (str[5] && str[6] == '.') {
279 if (strstr(str, "SV1"))
284 r->ua = UH_UA_MSIE_OLD;
288 } else if (strstr(val, "Safari/") && strstr(val, "Mac OS X"))
289 r->ua = UH_UA_SAFARI;
290 else if (strstr(val, "Chrome/"))
291 r->ua = UH_UA_CHROME;
292 else if (strstr(val, "Gecko/"))
294 else if (strstr(val, "Konqueror"))
295 r->ua = UH_UA_KONQUEROR;
299 blobmsg_add_string(&cl->hdr, data, val);
301 cl->state = CLIENT_STATE_HEADER;
304 void client_poll_post_data(struct client *cl)
306 struct dispatch *d = &cl->dispatch;
307 struct http_request *r = &cl->request;
311 if (cl->state == CLIENT_STATE_DONE)
319 buf = ustream_get_read_buf(cl->us, &len);
326 cur_len = min(r->content_length, len);
332 cur_len = d->data_send(cl, buf, cur_len);
334 r->content_length -= cur_len;
335 ustream_consume(cl->us, cur_len);
339 if (!r->transfer_chunked)
342 if (r->transfer_chunked > 1)
345 sep = strstr(buf + offset, "\r\n");
351 r->content_length = strtoul(buf + offset, &sep, 16);
352 r->transfer_chunked++;
353 ustream_consume(cl->us, sep + 2 - buf);
355 /* invalid chunk length */
357 r->content_length = 0;
358 r->transfer_chunked = 0;
362 /* empty chunk == eof */
363 if (!r->content_length) {
364 r->transfer_chunked = false;
369 buf = ustream_get_read_buf(cl->us, &len);
370 if (!r->content_length && !r->transfer_chunked &&
371 cl->state != CLIENT_STATE_DONE) {
372 if (cl->dispatch.data_done)
373 cl->dispatch.data_done(cl);
375 cl->state = CLIENT_STATE_DONE;
379 static bool client_data_cb(struct client *cl, char *buf, int len)
381 client_poll_post_data(cl);
385 static bool client_header_cb(struct client *cl, char *buf, int len)
390 newline = strstr(buf, "\r\n");
395 client_parse_header(cl, buf);
396 line_len = newline + 2 - buf;
397 ustream_consume(cl->us, line_len);
398 if (cl->state == CLIENT_STATE_DATA)
399 return client_data_cb(cl, newline + 2, len - line_len);
404 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
405 static read_cb_t read_cbs[] = {
406 [CLIENT_STATE_INIT] = client_init_cb,
407 [CLIENT_STATE_HEADER] = client_header_cb,
408 [CLIENT_STATE_DATA] = client_data_cb,
411 void uh_client_read_cb(struct client *cl)
413 struct ustream *us = cl->us;
418 str = ustream_get_read_buf(us, &len);
422 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
425 if (!read_cbs[cl->state](cl, str, len)) {
426 if (len == us->r.buffer_len &&
427 cl->state != CLIENT_STATE_DATA)
428 uh_header_error(cl, 413, "Request Entity Too Large");
434 static void client_close(struct client *cl)
437 uh_dispatch_done(cl);
438 uloop_timeout_cancel(&cl->timeout);
440 uh_tls_client_detach(cl);
441 ustream_free(&cl->sfd.stream);
442 close(cl->sfd.fd.fd);
444 blob_buf_free(&cl->hdr);
447 uh_unblock_listeners();
450 void uh_client_notify_state(struct client *cl)
452 struct ustream *s = cl->us;
454 if (!s->write_error) {
455 if (cl->state == CLIENT_STATE_DATA)
458 if (!s->eof || s->w.data_bytes)
462 return client_close(cl);
465 static void client_ustream_read_cb(struct ustream *s, int bytes)
467 struct client *cl = container_of(s, struct client, sfd);
469 uh_client_read_cb(cl);
472 static void client_ustream_write_cb(struct ustream *s, int bytes)
474 struct client *cl = container_of(s, struct client, sfd);
476 if (cl->dispatch.write_cb)
477 cl->dispatch.write_cb(cl);
480 static void client_notify_state(struct ustream *s)
482 struct client *cl = container_of(s, struct client, sfd);
484 uh_client_notify_state(cl);
487 static void set_addr(struct uh_addr *addr, void *src)
489 struct sockaddr_in *sin = src;
490 struct sockaddr_in6 *sin6 = src;
492 addr->family = sin->sin_family;
493 if (addr->family == AF_INET) {
494 addr->port = ntohs(sin->sin_port);
495 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
497 addr->port = ntohs(sin6->sin6_port);
498 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
502 bool uh_accept_client(int fd, bool tls)
504 static struct client *next_client;
508 static int client_id = 0;
509 struct sockaddr_in6 addr;
512 next_client = calloc(1, sizeof(*next_client));
517 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
521 set_addr(&cl->peer_addr, &addr);
523 getsockname(sfd, (struct sockaddr *) &addr, &sl);
524 set_addr(&cl->srv_addr, &addr);
526 cl->us = &cl->sfd.stream;
528 uh_tls_client_attach(cl);
530 cl->us->notify_read = client_ustream_read_cb;
531 cl->us->notify_write = client_ustream_write_cb;
532 cl->us->notify_state = client_notify_state;
535 cl->us->string_data = true;
536 ustream_fd_init(&cl->sfd, sfd);
538 cl->timeout.cb = client_timeout;
539 uloop_timeout_set(&cl->timeout, conf.network_timeout * 1000);
541 list_add_tail(&cl->list, &clients);
545 cl->id = client_id++;
550 void uh_close_fds(void)
555 uh_close_listen_fds();
556 list_for_each_entry(cl, &clients, list) {
557 close(cl->sfd.fd.fd);
558 if (cl->dispatch.close_fds)
559 cl->dispatch.close_fds(cl);