proc: do not cancel script killing after writing headers
[oweals/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         char *buf;
399         int len;
400
401         if (cl->state == CLIENT_STATE_DONE)
402                 return;
403
404         while (1) {
405                 char *sep;
406                 int offset = 0;
407                 int cur_len;
408
409                 buf = ustream_get_read_buf(cl->us, &len);
410                 if (!buf || !len)
411                         break;
412
413                 if (!d->data_send)
414                         return;
415
416                 cur_len = min(r->content_length, len);
417                 if (cur_len) {
418                         if (d->data_blocked)
419                                 break;
420
421                         if (d->data_send)
422                                 cur_len = d->data_send(cl, buf, cur_len);
423
424                         r->content_length -= cur_len;
425                         ustream_consume(cl->us, cur_len);
426                         continue;
427                 }
428
429                 if (!r->transfer_chunked)
430                         break;
431
432                 if (r->transfer_chunked > 1)
433                         offset = 2;
434
435                 sep = strstr(buf + offset, "\r\n");
436                 if (!sep)
437                         break;
438
439                 *sep = 0;
440
441                 r->content_length = strtoul(buf + offset, &sep, 16);
442                 r->transfer_chunked++;
443                 ustream_consume(cl->us, sep + 2 - buf);
444
445                 /* invalid chunk length */
446                 if ((sep && *sep) || r->content_length < 0) {
447                         r->content_length = 0;
448                         r->transfer_chunked = 0;
449                         break;
450                 }
451
452                 /* empty chunk == eof */
453                 if (!r->content_length) {
454                         r->transfer_chunked = false;
455                         break;
456                 }
457         }
458
459         buf = ustream_get_read_buf(cl->us, &len);
460         if (!r->content_length && !r->transfer_chunked &&
461                 cl->state != CLIENT_STATE_DONE) {
462                 if (cl->dispatch.data_done)
463                         cl->dispatch.data_done(cl);
464
465                 cl->state = CLIENT_STATE_DONE;
466         }
467 }
468
469 static bool client_data_cb(struct client *cl, char *buf, int len)
470 {
471         client_poll_post_data(cl);
472         return false;
473 }
474
475 static bool client_header_cb(struct client *cl, char *buf, int len)
476 {
477         char *newline;
478         int line_len;
479
480         newline = strstr(buf, "\r\n");
481         if (!newline)
482                 return false;
483
484         *newline = 0;
485         client_parse_header(cl, buf);
486         line_len = newline + 2 - buf;
487         ustream_consume(cl->us, line_len);
488         if (cl->state == CLIENT_STATE_DATA)
489                 return client_data_cb(cl, newline + 2, len - line_len);
490
491         return true;
492 }
493
494 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
495 static read_cb_t read_cbs[] = {
496         [CLIENT_STATE_INIT] = client_init_cb,
497         [CLIENT_STATE_HEADER] = client_header_cb,
498         [CLIENT_STATE_DATA] = client_data_cb,
499 };
500
501 void uh_client_read_cb(struct client *cl)
502 {
503         struct ustream *us = cl->us;
504         char *str;
505         int len;
506
507         client_done = false;
508         do {
509                 str = ustream_get_read_buf(us, &len);
510                 if (!str || !len)
511                         break;
512
513                 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
514                         break;
515
516                 if (!read_cbs[cl->state](cl, str, len)) {
517                         if (len == us->r.buffer_len &&
518                             cl->state != CLIENT_STATE_DATA)
519                                 uh_header_error(cl, 413, "Request Entity Too Large");
520                         break;
521                 }
522         } while (!client_done);
523 }
524
525 static void client_close(struct client *cl)
526 {
527         if (cl->refcount) {
528                 cl->state = CLIENT_STATE_CLEANUP;
529                 return;
530         }
531
532         client_done = true;
533         n_clients--;
534         uh_dispatch_done(cl);
535         uloop_timeout_cancel(&cl->timeout);
536         if (cl->tls)
537                 uh_tls_client_detach(cl);
538         ustream_free(&cl->sfd.stream);
539         close(cl->sfd.fd.fd);
540         list_del(&cl->list);
541         blob_buf_free(&cl->hdr);
542         blob_buf_free(&cl->hdr_response);
543         free(cl);
544
545         uh_unblock_listeners();
546 }
547
548 void uh_client_notify_state(struct client *cl)
549 {
550         struct ustream *s = cl->us;
551
552         if (!s->write_error && cl->state != CLIENT_STATE_CLEANUP) {
553                 if (cl->state == CLIENT_STATE_DATA)
554                         return;
555
556                 if (!s->eof || s->w.data_bytes)
557                         return;
558
559 #ifdef HAVE_TLS
560                 if (cl->tls && cl->ssl.conn && cl->ssl.conn->w.data_bytes) {
561                         cl->ssl.conn->eof = s->eof;
562                         if (!ustream_write_pending(cl->ssl.conn))
563                                 return;
564                 }
565 #endif
566         }
567
568         return client_close(cl);
569 }
570
571 static void client_ustream_read_cb(struct ustream *s, int bytes)
572 {
573         struct client *cl = container_of(s, struct client, sfd.stream);
574
575         uh_client_read_cb(cl);
576 }
577
578 static void client_ustream_write_cb(struct ustream *s, int bytes)
579 {
580         struct client *cl = container_of(s, struct client, sfd.stream);
581
582         if (cl->dispatch.write_cb)
583                 cl->dispatch.write_cb(cl);
584 }
585
586 static void client_notify_state(struct ustream *s)
587 {
588         struct client *cl = container_of(s, struct client, sfd.stream);
589
590         uh_client_notify_state(cl);
591 }
592
593 static void set_addr(struct uh_addr *addr, void *src)
594 {
595         struct sockaddr_in *sin = src;
596         struct sockaddr_in6 *sin6 = src;
597
598         addr->family = sin->sin_family;
599         if (addr->family == AF_INET) {
600                 addr->port = ntohs(sin->sin_port);
601                 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
602         } else {
603                 addr->port = ntohs(sin6->sin6_port);
604                 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
605         }
606 }
607
608 bool uh_accept_client(int fd, bool tls)
609 {
610         static struct client *next_client;
611         struct client *cl;
612         unsigned int sl;
613         int sfd;
614         static int client_id = 0;
615         struct sockaddr_in6 addr;
616
617         if (!next_client)
618                 next_client = calloc(1, sizeof(*next_client));
619
620         cl = next_client;
621
622         sl = sizeof(addr);
623         sfd = accept(fd, (struct sockaddr *) &addr, &sl);
624         if (sfd < 0)
625                 return false;
626
627         set_addr(&cl->peer_addr, &addr);
628         sl = sizeof(addr);
629         getsockname(sfd, (struct sockaddr *) &addr, &sl);
630         set_addr(&cl->srv_addr, &addr);
631
632         cl->us = &cl->sfd.stream;
633         if (tls) {
634                 uh_tls_client_attach(cl);
635         } else {
636                 cl->us->notify_read = client_ustream_read_cb;
637                 cl->us->notify_write = client_ustream_write_cb;
638                 cl->us->notify_state = client_notify_state;
639         }
640
641         cl->us->string_data = true;
642         ustream_fd_init(&cl->sfd, sfd);
643
644         uh_poll_connection(cl);
645         list_add_tail(&cl->list, &clients);
646
647         next_client = NULL;
648         n_clients++;
649         cl->id = client_id++;
650         cl->tls = tls;
651
652         return true;
653 }
654
655 void uh_close_fds(void)
656 {
657         struct client *cl;
658
659         uloop_done();
660         uh_close_listen_fds();
661         list_for_each_entry(cl, &clients, list) {
662                 close(cl->sfd.fd.fd);
663                 if (cl->dispatch.close_fds)
664                         cl->dispatch.close_fds(cl);
665         }
666 }