ubus: fix uhttpd crash
[project/uhttpd.git] / client.c
1 /*
2 * uhttpd - Tiny single-threaded httpd
3 *
4 * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
6 *
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.
10 *
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.
18 */
19
20 #include <libubox/blobmsg.h>
21 #include <ctype.h>
22
23 #include "uhttpd.h"
24 #include "tls.h"
25
26 static LIST_HEAD(clients);
27 static bool client_done = false;
28
29 int n_clients = 0;
30 struct config conf = {};
31
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",
36 };
37
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",
46 };
47
48 void uh_http_header(struct client *cl, int code, const char *summary)
49 {
50 struct http_request *r = &cl->request;
51 struct blob_attr *cur;
52 const char *enc = "Transfer-Encoding: chunked\r\n";
53 const char *conn;
54 int rem;
55
56 cl->http_code = code;
57
58 if (!uh_use_chunked(cl))
59 enc = "";
60
61 if (r->connection_close)
62 conn = "Connection: close";
63 else
64 conn = "Connection: Keep-Alive";
65
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);
69
70 if (!r->connection_close)
71 ustream_printf(cl->us, "Keep-Alive: timeout=%d\r\n", conf.http_keepalive);
72
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));
76 }
77
78 static void uh_connection_close(struct client *cl)
79 {
80 cl->state = CLIENT_STATE_CLOSE;
81 cl->us->eof = true;
82 ustream_state_change(cl->us);
83 }
84
85 static void uh_dispatch_done(struct client *cl)
86 {
87 if (cl->dispatch.free)
88 cl->dispatch.free(cl);
89 if (cl->dispatch.req_free)
90 cl->dispatch.req_free(cl);
91 }
92
93 static void client_timeout(struct uloop_timeout *timeout)
94 {
95 struct client *cl = container_of(timeout, struct client, timeout);
96
97 cl->state = CLIENT_STATE_CLOSE;
98 cl->request.connection_close = true;
99 uh_request_done(cl);
100 }
101
102 static void uh_set_client_timeout(struct client *cl, int timeout)
103 {
104 cl->timeout.cb = client_timeout;
105 uloop_timeout_set(&cl->timeout, timeout * 1000);
106 }
107
108 static void uh_keepalive_poll_cb(struct uloop_timeout *timeout)
109 {
110 struct client *cl = container_of(timeout, struct client, timeout);
111 int sec = cl->requests > 0 ? conf.http_keepalive : conf.network_timeout;
112
113 uh_set_client_timeout(cl, sec);
114 cl->us->notify_read(cl->us, 0);
115 }
116
117 static void uh_poll_connection(struct client *cl)
118 {
119 cl->timeout.cb = uh_keepalive_poll_cb;
120 uloop_timeout_set(&cl->timeout, 1);
121 }
122
123 void uh_request_done(struct client *cl)
124 {
125 uh_chunk_eof(cl);
126 uh_dispatch_done(cl);
127 blob_buf_init(&cl->hdr_response, 0);
128 memset(&cl->dispatch, 0, sizeof(cl->dispatch));
129
130 if (!conf.http_keepalive || cl->request.connection_close)
131 return uh_connection_close(cl);
132
133 cl->state = CLIENT_STATE_INIT;
134 cl->requests++;
135 uh_poll_connection(cl);
136 }
137
138 void __printf(4, 5)
139 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
140 {
141 va_list arg;
142
143 uh_http_header(cl, code, summary);
144 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
145
146 uh_chunk_printf(cl, "<h1>%s</h1>", summary);
147
148 if (fmt) {
149 va_start(arg, fmt);
150 uh_chunk_vprintf(cl, fmt, arg);
151 va_end(arg);
152 }
153
154 uh_request_done(cl);
155 }
156
157 static void uh_header_error(struct client *cl, int code, const char *summary)
158 {
159 uh_client_error(cl, code, summary, NULL);
160 uh_connection_close(cl);
161 }
162
163 static int find_idx(const char * const *list, int max, const char *str)
164 {
165 int i;
166
167 for (i = 0; i < max; i++)
168 if (!strcmp(list[i], str))
169 return i;
170
171 return -1;
172 }
173
174 static int client_parse_request(struct client *cl, char *data)
175 {
176 struct http_request *req = &cl->request;
177 char *type, *path, *version;
178 int h_method, h_version;
179
180 type = strtok(data, " ");
181 path = strtok(NULL, " ");
182 version = strtok(NULL, " ");
183 if (!type || !path || !version)
184 return CLIENT_STATE_DONE;
185
186 blobmsg_add_string(&cl->hdr, "URL", path);
187
188 memset(&cl->request, 0, sizeof(cl->request));
189 h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
190 h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
191 if (h_method < 0 || h_version < 0) {
192 req->version = UH_HTTP_VER_1_0;
193 return CLIENT_STATE_DONE;
194 }
195
196 req->method = h_method;
197 req->version = h_version;
198 if (req->version < UH_HTTP_VER_1_1 || !conf.http_keepalive)
199 req->connection_close = true;
200
201 return CLIENT_STATE_HEADER;
202 }
203
204 static bool client_init_cb(struct client *cl, char *buf, int len)
205 {
206 char *newline;
207
208 newline = strstr(buf, "\r\n");
209 if (!newline)
210 return false;
211
212 if (newline == buf) {
213 ustream_consume(cl->us, 2);
214 return true;
215 }
216
217 *newline = 0;
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");
223
224 return true;
225 }
226
227 static bool rfc1918_filter_check(struct client *cl)
228 {
229 if (!conf.rfc1918_filter)
230 return true;
231
232 if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
233 return true;
234
235 uh_client_error(cl, 403, "Forbidden",
236 "Rejected request from RFC1918 IP "
237 "to public server address");
238 return false;
239 }
240
241 static bool tls_redirect_check(struct client *cl)
242 {
243 int rem, port;
244 struct blob_attr *cur;
245 char *ptr, *url = NULL, *host = NULL;
246
247 if (cl->tls || !conf.tls_redirect)
248 return true;
249
250 if ((port = uh_first_tls_port(cl->srv_addr.family)) == -1)
251 return true;
252
253 blob_for_each_attr(cur, cl->hdr.head, rem) {
254 if (!strcmp(blobmsg_name(cur), "host"))
255 host = blobmsg_get_string(cur);
256
257 if (!strcmp(blobmsg_name(cur), "URL"))
258 url = blobmsg_get_string(cur);
259
260 if (url && host)
261 break;
262 }
263
264 if (!url || !host)
265 return true;
266
267 if ((ptr = strchr(host, ']')) != NULL)
268 *(ptr+1) = 0;
269 else if ((ptr = strchr(host, ':')) != NULL)
270 *ptr = 0;
271
272 cl->request.disable_chunked = true;
273 cl->request.connection_close = true;
274
275 uh_http_header(cl, 307, "Temporary Redirect");
276
277 if (port != 443)
278 ustream_printf(cl->us, "Location: https://%s:%d%s\r\n\r\n", host, port, url);
279 else
280 ustream_printf(cl->us, "Location: https://%s%s\r\n\r\n", host, url);
281
282 uh_request_done(cl);
283
284 return false;
285 }
286
287 static void client_header_complete(struct client *cl)
288 {
289 struct http_request *r = &cl->request;
290
291 if (!rfc1918_filter_check(cl))
292 return;
293
294 if (!tls_redirect_check(cl))
295 return;
296
297 if (r->expect_cont)
298 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
299
300 switch(r->ua) {
301 case UH_UA_MSIE_OLD:
302 if (r->method != UH_HTTP_MSG_POST)
303 break;
304
305 /* fall through */
306 case UH_UA_SAFARI:
307 r->connection_close = true;
308 break;
309 default:
310 break;
311 }
312
313 uh_handle_request(cl);
314 }
315
316 static void client_parse_header(struct client *cl, char *data)
317 {
318 struct http_request *r = &cl->request;
319 char *err;
320 char *name;
321 char *val;
322
323 if (!*data) {
324 uloop_timeout_cancel(&cl->timeout);
325 cl->state = CLIENT_STATE_DATA;
326 client_header_complete(cl);
327 return;
328 }
329
330 val = uh_split_header(data);
331 if (!val) {
332 cl->state = CLIENT_STATE_DONE;
333 return;
334 }
335
336 for (name = data; *name; name++)
337 if (isupper(*name))
338 *name = tolower(*name);
339
340 if (!strcmp(data, "expect")) {
341 if (!strcasecmp(val, "100-continue"))
342 r->expect_cont = true;
343 else {
344 uh_header_error(cl, 412, "Precondition Failed");
345 return;
346 }
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");
351 return;
352 }
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")) {
360 char *str;
361
362 if (strstr(val, "Opera"))
363 r->ua = UH_UA_OPERA;
364 else if ((str = strstr(val, "MSIE ")) != NULL) {
365 r->ua = UH_UA_MSIE_NEW;
366 if (str[5] && str[6] == '.') {
367 switch (str[5]) {
368 case '6':
369 if (strstr(str, "SV1"))
370 break;
371 /* fall through */
372 case '5':
373 case '4':
374 r->ua = UH_UA_MSIE_OLD;
375 break;
376 }
377 }
378 }
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/"))
384 r->ua = UH_UA_GECKO;
385 else if (strstr(val, "Konqueror"))
386 r->ua = UH_UA_KONQUEROR;
387 }
388
389
390 blobmsg_add_string(&cl->hdr, data, val);
391
392 cl->state = CLIENT_STATE_HEADER;
393 }
394
395 void client_poll_post_data(struct client *cl)
396 {
397 struct dispatch *d = &cl->dispatch;
398 struct http_request *r = &cl->request;
399 enum client_state st;
400 char *buf;
401 int len;
402
403 if (cl->state == CLIENT_STATE_DONE)
404 return;
405
406 while (1) {
407 char *sep;
408 int offset = 0;
409 int cur_len;
410
411 buf = ustream_get_read_buf(cl->us, &len);
412 if (!buf || !len)
413 break;
414
415 if (!d->data_send)
416 return;
417
418 cur_len = min(r->content_length, len);
419 if (cur_len) {
420 if (d->data_blocked)
421 break;
422
423 if (d->data_send)
424 cur_len = d->data_send(cl, buf, cur_len);
425
426 r->content_length -= cur_len;
427 ustream_consume(cl->us, cur_len);
428 continue;
429 }
430
431 if (!r->transfer_chunked)
432 break;
433
434 if (r->transfer_chunked > 1)
435 offset = 2;
436
437 sep = strstr(buf + offset, "\r\n");
438 if (!sep)
439 break;
440
441 *sep = 0;
442
443 r->content_length = strtoul(buf + offset, &sep, 16);
444 r->transfer_chunked++;
445 ustream_consume(cl->us, sep + 2 - buf);
446
447 /* invalid chunk length */
448 if ((sep && *sep) || r->content_length < 0) {
449 r->content_length = 0;
450 r->transfer_chunked = 0;
451 break;
452 }
453
454 /* empty chunk == eof */
455 if (!r->content_length) {
456 r->transfer_chunked = false;
457 break;
458 }
459 }
460
461 buf = ustream_get_read_buf(cl->us, &len);
462 if (!r->content_length && !r->transfer_chunked &&
463 cl->state != CLIENT_STATE_DONE) {
464 st = cl->state;
465
466 if (cl->dispatch.data_done)
467 cl->dispatch.data_done(cl);
468
469 if (cl->state == st)
470 cl->state = CLIENT_STATE_DONE;
471 }
472 }
473
474 static bool client_data_cb(struct client *cl, char *buf, int len)
475 {
476 client_poll_post_data(cl);
477 return false;
478 }
479
480 static bool client_header_cb(struct client *cl, char *buf, int len)
481 {
482 char *newline;
483 int line_len;
484
485 newline = strstr(buf, "\r\n");
486 if (!newline)
487 return false;
488
489 *newline = 0;
490 client_parse_header(cl, buf);
491 line_len = newline + 2 - buf;
492 ustream_consume(cl->us, line_len);
493 if (cl->state == CLIENT_STATE_DATA)
494 return client_data_cb(cl, newline + 2, len - line_len);
495
496 return true;
497 }
498
499 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
500 static read_cb_t read_cbs[] = {
501 [CLIENT_STATE_INIT] = client_init_cb,
502 [CLIENT_STATE_HEADER] = client_header_cb,
503 [CLIENT_STATE_DATA] = client_data_cb,
504 };
505
506 void uh_client_read_cb(struct client *cl)
507 {
508 struct ustream *us = cl->us;
509 char *str;
510 int len;
511
512 client_done = false;
513 do {
514 str = ustream_get_read_buf(us, &len);
515 if (!str || !len)
516 break;
517
518 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
519 break;
520
521 if (!read_cbs[cl->state](cl, str, len)) {
522 if (len == us->r.buffer_len &&
523 cl->state != CLIENT_STATE_DATA)
524 uh_header_error(cl, 413, "Request Entity Too Large");
525 break;
526 }
527 } while (!client_done);
528 }
529
530 static void client_close(struct client *cl)
531 {
532 if (cl->refcount) {
533 cl->state = CLIENT_STATE_CLEANUP;
534 return;
535 }
536
537 client_done = true;
538 n_clients--;
539 uh_dispatch_done(cl);
540 uloop_timeout_cancel(&cl->timeout);
541 if (cl->tls)
542 uh_tls_client_detach(cl);
543 ustream_free(&cl->sfd.stream);
544 close(cl->sfd.fd.fd);
545 list_del(&cl->list);
546 blob_buf_free(&cl->hdr);
547 blob_buf_free(&cl->hdr_response);
548 free(cl);
549
550 uh_unblock_listeners();
551 }
552
553 void uh_client_notify_state(struct client *cl)
554 {
555 struct ustream *s = cl->us;
556
557 if (!s->write_error && cl->state != CLIENT_STATE_CLEANUP) {
558 if (cl->state == CLIENT_STATE_DATA)
559 return;
560
561 if (!s->eof || s->w.data_bytes)
562 return;
563
564 #ifdef HAVE_TLS
565 if (cl->tls && cl->ssl.conn && cl->ssl.conn->w.data_bytes) {
566 cl->ssl.conn->eof = s->eof;
567 if (!ustream_write_pending(cl->ssl.conn))
568 return;
569 }
570 #endif
571 }
572
573 return client_close(cl);
574 }
575
576 static void client_ustream_read_cb(struct ustream *s, int bytes)
577 {
578 struct client *cl = container_of(s, struct client, sfd.stream);
579
580 uh_client_read_cb(cl);
581 }
582
583 static void client_ustream_write_cb(struct ustream *s, int bytes)
584 {
585 struct client *cl = container_of(s, struct client, sfd.stream);
586
587 if (cl->dispatch.write_cb)
588 cl->dispatch.write_cb(cl);
589 }
590
591 static void client_notify_state(struct ustream *s)
592 {
593 struct client *cl = container_of(s, struct client, sfd.stream);
594
595 uh_client_notify_state(cl);
596 }
597
598 static void set_addr(struct uh_addr *addr, void *src)
599 {
600 struct sockaddr_in *sin = src;
601 struct sockaddr_in6 *sin6 = src;
602
603 addr->family = sin->sin_family;
604 if (addr->family == AF_INET) {
605 addr->port = ntohs(sin->sin_port);
606 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
607 } else {
608 addr->port = ntohs(sin6->sin6_port);
609 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
610 }
611 }
612
613 bool uh_accept_client(int fd, bool tls)
614 {
615 static struct client *next_client;
616 struct client *cl;
617 unsigned int sl;
618 int sfd;
619 static int client_id = 0;
620 struct sockaddr_in6 addr;
621
622 if (!next_client)
623 next_client = calloc(1, sizeof(*next_client));
624
625 cl = next_client;
626
627 sl = sizeof(addr);
628 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
629 if (sfd < 0)
630 return false;
631
632 set_addr(&cl->peer_addr, &addr);
633 sl = sizeof(addr);
634 getsockname(sfd, (struct sockaddr *) &addr, &sl);
635 set_addr(&cl->srv_addr, &addr);
636
637 cl->us = &cl->sfd.stream;
638 if (tls) {
639 uh_tls_client_attach(cl);
640 } else {
641 cl->us->notify_read = client_ustream_read_cb;
642 cl->us->notify_write = client_ustream_write_cb;
643 cl->us->notify_state = client_notify_state;
644 }
645
646 cl->us->string_data = true;
647 ustream_fd_init(&cl->sfd, sfd);
648
649 uh_poll_connection(cl);
650 list_add_tail(&cl->list, &clients);
651
652 next_client = NULL;
653 n_clients++;
654 cl->id = client_id++;
655 cl->tls = tls;
656
657 return true;
658 }
659
660 void uh_close_fds(void)
661 {
662 struct client *cl;
663
664 uloop_done();
665 uh_close_listen_fds();
666 list_for_each_entry(cl, &clients, list) {
667 close(cl->sfd.fd.fd);
668 if (cl->dispatch.close_fds)
669 cl->dispatch.close_fds(cl);
670 }
671 }