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