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