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