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