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