file: poke ustream after starting deferred program
[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 uh_connection_close(cl);
99 }
100
101 static void uh_set_client_timeout(struct client *cl, int timeout)
102 {
103 cl->timeout.cb = client_timeout;
104 uloop_timeout_set(&cl->timeout, timeout * 1000);
105 }
106
107 static void uh_keepalive_poll_cb(struct uloop_timeout *timeout)
108 {
109 struct client *cl = container_of(timeout, struct client, timeout);
110 int sec = cl->requests > 0 ? conf.http_keepalive : conf.network_timeout;
111
112 uh_set_client_timeout(cl, sec);
113 cl->us->notify_read(cl->us, 0);
114 }
115
116 static void uh_poll_connection(struct client *cl)
117 {
118 cl->timeout.cb = uh_keepalive_poll_cb;
119 uloop_timeout_set(&cl->timeout, 1);
120 }
121
122 void uh_request_done(struct client *cl)
123 {
124 uh_chunk_eof(cl);
125 uh_dispatch_done(cl);
126 blob_buf_init(&cl->hdr_response, 0);
127 memset(&cl->dispatch, 0, sizeof(cl->dispatch));
128
129 if (!conf.http_keepalive || cl->request.connection_close)
130 return uh_connection_close(cl);
131
132 cl->state = CLIENT_STATE_INIT;
133 cl->requests++;
134 uh_poll_connection(cl);
135 }
136
137 void __printf(4, 5)
138 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
139 {
140 va_list arg;
141
142 uh_http_header(cl, code, summary);
143 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
144
145 uh_chunk_printf(cl, "<h1>%s</h1>", summary);
146
147 if (fmt) {
148 va_start(arg, fmt);
149 uh_chunk_vprintf(cl, fmt, arg);
150 va_end(arg);
151 }
152
153 uh_request_done(cl);
154 }
155
156 static void uh_header_error(struct client *cl, int code, const char *summary)
157 {
158 uh_client_error(cl, code, summary, NULL);
159 uh_connection_close(cl);
160 }
161
162 static int find_idx(const char * const *list, int max, const char *str)
163 {
164 int i;
165
166 for (i = 0; i < max; i++)
167 if (!strcmp(list[i], str))
168 return i;
169
170 return -1;
171 }
172
173 static int client_parse_request(struct client *cl, char *data)
174 {
175 struct http_request *req = &cl->request;
176 char *type, *path, *version;
177 int h_method, h_version;
178
179 type = strtok(data, " ");
180 path = strtok(NULL, " ");
181 version = strtok(NULL, " ");
182 if (!type || !path || !version)
183 return CLIENT_STATE_DONE;
184
185 blobmsg_add_string(&cl->hdr, "URL", path);
186
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;
193 }
194
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;
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 char *buf;
400 int len;
401
402 if (cl->state == CLIENT_STATE_DONE)
403 return;
404
405 while (1) {
406 char *sep;
407 int offset = 0;
408 int cur_len;
409
410 buf = ustream_get_read_buf(cl->us, &len);
411 if (!buf || !len)
412 break;
413
414 if (!d->data_send)
415 return;
416
417 cur_len = min(r->content_length, len);
418 if (cur_len) {
419 if (d->data_blocked)
420 break;
421
422 if (d->data_send)
423 cur_len = d->data_send(cl, buf, cur_len);
424
425 r->content_length -= cur_len;
426 ustream_consume(cl->us, cur_len);
427 continue;
428 }
429
430 if (!r->transfer_chunked)
431 break;
432
433 if (r->transfer_chunked > 1)
434 offset = 2;
435
436 sep = strstr(buf + offset, "\r\n");
437 if (!sep)
438 break;
439
440 *sep = 0;
441
442 r->content_length = strtoul(buf + offset, &sep, 16);
443 r->transfer_chunked++;
444 ustream_consume(cl->us, sep + 2 - buf);
445
446 /* invalid chunk length */
447 if ((sep && *sep) || r->content_length < 0) {
448 r->content_length = 0;
449 r->transfer_chunked = 0;
450 break;
451 }
452
453 /* empty chunk == eof */
454 if (!r->content_length) {
455 r->transfer_chunked = false;
456 break;
457 }
458 }
459
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);
465
466 cl->state = CLIENT_STATE_DONE;
467 }
468 }
469
470 static bool client_data_cb(struct client *cl, char *buf, int len)
471 {
472 client_poll_post_data(cl);
473 return false;
474 }
475
476 static bool client_header_cb(struct client *cl, char *buf, int len)
477 {
478 char *newline;
479 int line_len;
480
481 newline = strstr(buf, "\r\n");
482 if (!newline)
483 return false;
484
485 *newline = 0;
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);
491
492 return true;
493 }
494
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,
500 };
501
502 void uh_client_read_cb(struct client *cl)
503 {
504 struct ustream *us = cl->us;
505 char *str;
506 int len;
507
508 client_done = false;
509 do {
510 str = ustream_get_read_buf(us, &len);
511 if (!str || !len)
512 break;
513
514 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
515 break;
516
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");
521 break;
522 }
523 } while (!client_done);
524 }
525
526 static void client_close(struct client *cl)
527 {
528 if (cl->refcount) {
529 cl->state = CLIENT_STATE_CLEANUP;
530 return;
531 }
532
533 client_done = true;
534 n_clients--;
535 uh_dispatch_done(cl);
536 uloop_timeout_cancel(&cl->timeout);
537 if (cl->tls)
538 uh_tls_client_detach(cl);
539 ustream_free(&cl->sfd.stream);
540 close(cl->sfd.fd.fd);
541 list_del(&cl->list);
542 blob_buf_free(&cl->hdr);
543 blob_buf_free(&cl->hdr_response);
544 free(cl);
545
546 uh_unblock_listeners();
547 }
548
549 void uh_client_notify_state(struct client *cl)
550 {
551 struct ustream *s = cl->us;
552
553 if (!s->write_error && cl->state != CLIENT_STATE_CLEANUP) {
554 if (cl->state == CLIENT_STATE_DATA)
555 return;
556
557 if (!s->eof || s->w.data_bytes)
558 return;
559
560 #ifdef HAVE_TLS
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))
564 return;
565 }
566 #endif
567 }
568
569 return client_close(cl);
570 }
571
572 static void client_ustream_read_cb(struct ustream *s, int bytes)
573 {
574 struct client *cl = container_of(s, struct client, sfd.stream);
575
576 uh_client_read_cb(cl);
577 }
578
579 static void client_ustream_write_cb(struct ustream *s, int bytes)
580 {
581 struct client *cl = container_of(s, struct client, sfd.stream);
582
583 if (cl->dispatch.write_cb)
584 cl->dispatch.write_cb(cl);
585 }
586
587 static void client_notify_state(struct ustream *s)
588 {
589 struct client *cl = container_of(s, struct client, sfd.stream);
590
591 uh_client_notify_state(cl);
592 }
593
594 static void set_addr(struct uh_addr *addr, void *src)
595 {
596 struct sockaddr_in *sin = src;
597 struct sockaddr_in6 *sin6 = src;
598
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));
603 } else {
604 addr->port = ntohs(sin6->sin6_port);
605 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
606 }
607 }
608
609 bool uh_accept_client(int fd, bool tls)
610 {
611 static struct client *next_client;
612 struct client *cl;
613 unsigned int sl;
614 int sfd;
615 static int client_id = 0;
616 struct sockaddr_in6 addr;
617
618 if (!next_client)
619 next_client = calloc(1, sizeof(*next_client));
620
621 cl = next_client;
622
623 sl = sizeof(addr);
624 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
625 if (sfd < 0)
626 return false;
627
628 set_addr(&cl->peer_addr, &addr);
629 sl = sizeof(addr);
630 getsockname(sfd, (struct sockaddr *) &addr, &sl);
631 set_addr(&cl->srv_addr, &addr);
632
633 cl->us = &cl->sfd.stream;
634 if (tls) {
635 uh_tls_client_attach(cl);
636 } else {
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;
640 }
641
642 cl->us->string_data = true;
643 ustream_fd_init(&cl->sfd, sfd);
644
645 uh_poll_connection(cl);
646 list_add_tail(&cl->list, &clients);
647
648 next_client = NULL;
649 n_clients++;
650 cl->id = client_id++;
651 cl->tls = tls;
652
653 return true;
654 }
655
656 void uh_close_fds(void)
657 {
658 struct client *cl;
659
660 uloop_done();
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);
666 }
667 }