client: fix spurious keepalive connection timeouts
[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 || !conf.http_keepalive)
198 req->connection_close = true;
199
200 return CLIENT_STATE_HEADER;
201 }
202
203 static bool client_init_cb(struct client *cl, char *buf, int len)
204 {
205 char *newline;
206
207 newline = strstr(buf, "\r\n");
208 if (!newline)
209 return false;
210
211 if (newline == buf) {
212 ustream_consume(cl->us, 2);
213 return true;
214 }
215
216 *newline = 0;
217 blob_buf_init(&cl->hdr, 0);
218 cl->state = client_parse_request(cl, buf);
219 ustream_consume(cl->us, newline + 2 - buf);
220 if (cl->state == CLIENT_STATE_DONE)
221 uh_header_error(cl, 400, "Bad Request");
222
223 return true;
224 }
225
226 static bool rfc1918_filter_check(struct client *cl)
227 {
228 if (!conf.rfc1918_filter)
229 return true;
230
231 if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
232 return true;
233
234 uh_client_error(cl, 403, "Forbidden",
235 "Rejected request from RFC1918 IP "
236 "to public server address");
237 return false;
238 }
239
240 static bool tls_redirect_check(struct client *cl)
241 {
242 int rem, port;
243 struct blob_attr *cur;
244 char *ptr, *url = NULL, *host = NULL;
245
246 if (cl->tls || !conf.tls_redirect)
247 return true;
248
249 if ((port = uh_first_tls_port(cl->srv_addr.family)) == -1)
250 return true;
251
252 blob_for_each_attr(cur, cl->hdr.head, rem) {
253 if (!strcmp(blobmsg_name(cur), "host"))
254 host = blobmsg_get_string(cur);
255
256 if (!strcmp(blobmsg_name(cur), "URL"))
257 url = blobmsg_get_string(cur);
258
259 if (url && host)
260 break;
261 }
262
263 if (!url || !host)
264 return true;
265
266 if ((ptr = strchr(host, ']')) != NULL)
267 *(ptr+1) = 0;
268 else if ((ptr = strchr(host, ':')) != NULL)
269 *ptr = 0;
270
271 cl->request.disable_chunked = true;
272 cl->request.connection_close = true;
273
274 uh_http_header(cl, 307, "Temporary Redirect");
275
276 if (port != 443)
277 ustream_printf(cl->us, "Location: https://%s:%d%s\r\n\r\n", host, port, url);
278 else
279 ustream_printf(cl->us, "Location: https://%s%s\r\n\r\n", host, url);
280
281 uh_request_done(cl);
282
283 return false;
284 }
285
286 static void client_header_complete(struct client *cl)
287 {
288 struct http_request *r = &cl->request;
289
290 if (!rfc1918_filter_check(cl))
291 return;
292
293 if (!tls_redirect_check(cl))
294 return;
295
296 if (r->expect_cont)
297 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
298
299 switch(r->ua) {
300 case UH_UA_MSIE_OLD:
301 if (r->method != UH_HTTP_MSG_POST)
302 break;
303
304 /* fall through */
305 case UH_UA_SAFARI:
306 r->connection_close = true;
307 break;
308 default:
309 break;
310 }
311
312 uh_handle_request(cl);
313 }
314
315 static void client_parse_header(struct client *cl, char *data)
316 {
317 struct http_request *r = &cl->request;
318 char *err;
319 char *name;
320 char *val;
321
322 if (!*data) {
323 uloop_timeout_cancel(&cl->timeout);
324 cl->state = CLIENT_STATE_DATA;
325 client_header_complete(cl);
326 return;
327 }
328
329 val = uh_split_header(data);
330 if (!val) {
331 cl->state = CLIENT_STATE_DONE;
332 return;
333 }
334
335 for (name = data; *name; name++)
336 if (isupper(*name))
337 *name = tolower(*name);
338
339 if (!strcmp(data, "expect")) {
340 if (!strcasecmp(val, "100-continue"))
341 r->expect_cont = true;
342 else {
343 uh_header_error(cl, 412, "Precondition Failed");
344 return;
345 }
346 } else if (!strcmp(data, "content-length")) {
347 r->content_length = strtoul(val, &err, 0);
348 if ((err && *err) || r->content_length < 0) {
349 uh_header_error(cl, 400, "Bad Request");
350 return;
351 }
352 } else if (!strcmp(data, "transfer-encoding")) {
353 if (!strcmp(val, "chunked"))
354 r->transfer_chunked = true;
355 } else if (!strcmp(data, "connection")) {
356 if (!strcasecmp(val, "close"))
357 r->connection_close = true;
358 } else if (!strcmp(data, "user-agent")) {
359 char *str;
360
361 if (strstr(val, "Opera"))
362 r->ua = UH_UA_OPERA;
363 else if ((str = strstr(val, "MSIE ")) != NULL) {
364 r->ua = UH_UA_MSIE_NEW;
365 if (str[5] && str[6] == '.') {
366 switch (str[5]) {
367 case '6':
368 if (strstr(str, "SV1"))
369 break;
370 /* fall through */
371 case '5':
372 case '4':
373 r->ua = UH_UA_MSIE_OLD;
374 break;
375 }
376 }
377 }
378 else if (strstr(val, "Chrome/"))
379 r->ua = UH_UA_CHROME;
380 else if (strstr(val, "Safari/") && strstr(val, "Mac OS X"))
381 r->ua = UH_UA_SAFARI;
382 else if (strstr(val, "Gecko/"))
383 r->ua = UH_UA_GECKO;
384 else if (strstr(val, "Konqueror"))
385 r->ua = UH_UA_KONQUEROR;
386 }
387
388
389 blobmsg_add_string(&cl->hdr, data, val);
390
391 cl->state = CLIENT_STATE_HEADER;
392 }
393
394 void client_poll_post_data(struct client *cl)
395 {
396 struct dispatch *d = &cl->dispatch;
397 struct http_request *r = &cl->request;
398 enum client_state st;
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 st = cl->state;
464
465 if (cl->dispatch.data_done)
466 cl->dispatch.data_done(cl);
467
468 if (cl->state == st)
469 cl->state = CLIENT_STATE_DONE;
470 }
471 }
472
473 static bool client_data_cb(struct client *cl, char *buf, int len)
474 {
475 client_poll_post_data(cl);
476 return false;
477 }
478
479 static bool client_header_cb(struct client *cl, char *buf, int len)
480 {
481 char *newline;
482 int line_len;
483
484 newline = strstr(buf, "\r\n");
485 if (!newline)
486 return false;
487
488 *newline = 0;
489 client_parse_header(cl, buf);
490 line_len = newline + 2 - buf;
491 ustream_consume(cl->us, line_len);
492 if (cl->state == CLIENT_STATE_DATA)
493 return client_data_cb(cl, newline + 2, len - line_len);
494
495 return true;
496 }
497
498 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
499 static read_cb_t read_cbs[] = {
500 [CLIENT_STATE_INIT] = client_init_cb,
501 [CLIENT_STATE_HEADER] = client_header_cb,
502 [CLIENT_STATE_DATA] = client_data_cb,
503 };
504
505 void uh_client_read_cb(struct client *cl)
506 {
507 struct ustream *us = cl->us;
508 char *str;
509 int len;
510
511 client_done = false;
512 do {
513 str = ustream_get_read_buf(us, &len);
514 if (!str || !len)
515 break;
516
517 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
518 break;
519
520 if (!read_cbs[cl->state](cl, str, len)) {
521 if (len == us->r.buffer_len &&
522 cl->state != CLIENT_STATE_DATA)
523 uh_header_error(cl, 413, "Request Entity Too Large");
524 break;
525 }
526 } while (!client_done);
527 }
528
529 static void client_close(struct client *cl)
530 {
531 if (cl->refcount) {
532 cl->state = CLIENT_STATE_CLEANUP;
533 return;
534 }
535
536 client_done = true;
537 n_clients--;
538 uh_dispatch_done(cl);
539 uloop_timeout_cancel(&cl->timeout);
540 if (cl->tls)
541 uh_tls_client_detach(cl);
542 ustream_free(&cl->sfd.stream);
543 close(cl->sfd.fd.fd);
544 list_del(&cl->list);
545 blob_buf_free(&cl->hdr);
546 blob_buf_free(&cl->hdr_response);
547 free(cl);
548
549 uh_unblock_listeners();
550 }
551
552 void uh_client_notify_state(struct client *cl)
553 {
554 struct ustream *s = cl->us;
555
556 if (!s->write_error && cl->state != CLIENT_STATE_CLEANUP) {
557 if (cl->state == CLIENT_STATE_DATA)
558 return;
559
560 if (!s->eof || s->w.data_bytes)
561 return;
562
563 #ifdef HAVE_TLS
564 if (cl->tls && cl->ssl.conn && cl->ssl.conn->w.data_bytes) {
565 cl->ssl.conn->eof = s->eof;
566 if (!ustream_write_pending(cl->ssl.conn))
567 return;
568 }
569 #endif
570 }
571
572 return client_close(cl);
573 }
574
575 static void client_ustream_read_cb(struct ustream *s, int bytes)
576 {
577 struct client *cl = container_of(s, struct client, sfd.stream);
578
579 uh_client_read_cb(cl);
580 }
581
582 static void client_ustream_write_cb(struct ustream *s, int bytes)
583 {
584 struct client *cl = container_of(s, struct client, sfd.stream);
585
586 if (cl->dispatch.write_cb)
587 cl->dispatch.write_cb(cl);
588 }
589
590 static void client_notify_state(struct ustream *s)
591 {
592 struct client *cl = container_of(s, struct client, sfd.stream);
593
594 uh_client_notify_state(cl);
595 }
596
597 static void set_addr(struct uh_addr *addr, void *src)
598 {
599 struct sockaddr_in *sin = src;
600 struct sockaddr_in6 *sin6 = src;
601
602 addr->family = sin->sin_family;
603 if (addr->family == AF_INET) {
604 addr->port = ntohs(sin->sin_port);
605 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
606 } else {
607 addr->port = ntohs(sin6->sin6_port);
608 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
609 }
610 }
611
612 bool uh_accept_client(int fd, bool tls)
613 {
614 static struct client *next_client;
615 struct client *cl;
616 unsigned int sl;
617 int sfd;
618 static int client_id = 0;
619 struct sockaddr_in6 addr;
620
621 if (!next_client)
622 next_client = calloc(1, sizeof(*next_client));
623
624 cl = next_client;
625
626 sl = sizeof(addr);
627 sfd = accept(fd, (struct sockaddr *) &addr, &sl);
628 if (sfd < 0)
629 return false;
630
631 set_addr(&cl->peer_addr, &addr);
632 sl = sizeof(addr);
633 getsockname(sfd, (struct sockaddr *) &addr, &sl);
634 set_addr(&cl->srv_addr, &addr);
635
636 cl->us = &cl->sfd.stream;
637 if (tls) {
638 uh_tls_client_attach(cl);
639 } else {
640 cl->us->notify_read = client_ustream_read_cb;
641 cl->us->notify_write = client_ustream_write_cb;
642 cl->us->notify_state = client_notify_state;
643 }
644
645 cl->us->string_data = true;
646 ustream_fd_init(&cl->sfd, sfd);
647
648 uh_poll_connection(cl);
649 list_add_tail(&cl->list, &clients);
650
651 next_client = NULL;
652 n_clients++;
653 cl->id = client_id++;
654 cl->tls = tls;
655
656 return true;
657 }
658
659 void uh_close_fds(void)
660 {
661 struct client *cl;
662
663 uloop_done();
664 uh_close_listen_fds();
665 list_for_each_entry(cl, &clients, list) {
666 close(cl->sfd.fd.fd);
667 if (cl->dispatch.close_fds)
668 cl->dispatch.close_fds(cl);
669 }
670 }