add support for deferring script requests, limit maximum number of script calls to...
[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         cl->us->notify_write = NULL;
114         memset(&cl->dispatch, 0, sizeof(cl->dispatch));
115
116         if (!conf.http_keepalive || cl->request.connection_close)
117                 return uh_connection_close(cl);
118
119         cl->state = CLIENT_STATE_INIT;
120         cl->requests++;
121         uh_poll_connection(cl);
122 }
123
124 void __printf(4, 5)
125 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
126 {
127         va_list arg;
128
129         uh_http_header(cl, code, summary);
130         ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
131
132         uh_chunk_printf(cl, "<h1>%s</h1>", summary);
133
134         if (fmt) {
135                 va_start(arg, fmt);
136                 uh_chunk_vprintf(cl, fmt, arg);
137                 va_end(arg);
138         }
139
140         uh_request_done(cl);
141 }
142
143 static void uh_header_error(struct client *cl, int code, const char *summary)
144 {
145         uh_client_error(cl, code, summary, NULL);
146         uh_connection_close(cl);
147 }
148
149 static int find_idx(const char * const *list, int max, const char *str)
150 {
151         int i;
152
153         for (i = 0; i < max; i++)
154                 if (!strcmp(list[i], str))
155                         return i;
156
157         return -1;
158 }
159
160 static int client_parse_request(struct client *cl, char *data)
161 {
162         struct http_request *req = &cl->request;
163         char *type, *path, *version;
164         int h_method, h_version;
165
166         type = strtok(data, " ");
167         path = strtok(NULL, " ");
168         version = strtok(NULL, " ");
169         if (!type || !path || !version)
170                 return CLIENT_STATE_DONE;
171
172         blobmsg_add_string(&cl->hdr, "URL", path);
173
174         memset(&cl->request, 0, sizeof(cl->request));
175         h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
176         h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
177         if (h_method < 0 || h_version < 0) {
178                 req->version = UH_HTTP_VER_1_0;
179                 return CLIENT_STATE_DONE;
180         }
181
182         req->method = h_method;
183         req->version = h_version;
184         if (req->version < UH_HTTP_VER_1_1 || !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                 return true;
200
201         *newline = 0;
202         blob_buf_init(&cl->hdr, 0);
203         cl->state = client_parse_request(cl, buf);
204         ustream_consume(cl->us, newline + 2 - buf);
205         if (cl->state == CLIENT_STATE_DONE)
206                 uh_header_error(cl, 400, "Bad Request");
207
208         return true;
209 }
210
211 static bool rfc1918_filter_check(struct client *cl)
212 {
213         if (!conf.rfc1918_filter)
214                 return true;
215
216         if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
217                 return true;
218
219         uh_client_error(cl, 403, "Forbidden",
220                         "Rejected request from RFC1918 IP "
221                         "to public server address");
222         return false;
223 }
224
225 static void client_header_complete(struct client *cl)
226 {
227         struct http_request *r = &cl->request;
228
229         if (!rfc1918_filter_check(cl))
230                 return;
231
232         if (r->expect_cont)
233                 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
234
235         switch(r->ua) {
236         case UH_UA_MSIE_OLD:
237                 if (r->method != UH_HTTP_MSG_POST)
238                         break;
239
240                 /* fall through */
241         case UH_UA_SAFARI:
242                 r->connection_close = true;
243                 break;
244         default:
245                 break;
246         }
247
248         uh_handle_request(cl);
249 }
250
251 static void client_parse_header(struct client *cl, char *data)
252 {
253         struct http_request *r = &cl->request;
254         char *err;
255         char *name;
256         char *val;
257
258         if (!*data) {
259                 uloop_timeout_cancel(&cl->timeout);
260                 cl->state = CLIENT_STATE_DATA;
261                 client_header_complete(cl);
262                 return;
263         }
264
265         val = uh_split_header(data);
266         if (!val) {
267                 cl->state = CLIENT_STATE_DONE;
268                 return;
269         }
270
271         for (name = data; *name; name++)
272                 if (isupper(*name))
273                         *name = tolower(*name);
274
275         if (!strcmp(data, "expect")) {
276                 if (!strcasecmp(val, "100-continue"))
277                         r->expect_cont = true;
278                 else {
279                         uh_header_error(cl, 412, "Precondition Failed");
280                         return;
281                 }
282         } else if (!strcmp(data, "content-length")) {
283                 r->content_length = strtoul(val, &err, 0);
284                 if (err && *err) {
285                         uh_header_error(cl, 400, "Bad Request");
286                         return;
287                 }
288         } else if (!strcmp(data, "transfer-encoding")) {
289                 if (!strcmp(val, "chunked"))
290                         r->transfer_chunked = true;
291         } else if (!strcmp(data, "connection")) {
292                 if (!strcasecmp(val, "close"))
293                         r->connection_close = true;
294                 else if (!strcasecmp(val, "keep-alive"))
295                         r->connection_close = false;
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
572         return true;
573 }
574
575 void uh_close_fds(void)
576 {
577         struct client *cl;
578
579         uloop_done();
580         uh_close_listen_fds();
581         list_for_each_entry(cl, &clients, list) {
582                 close(cl->sfd.fd.fd);
583                 if (cl->dispatch.close_fds)
584                         cl->dispatch.close_fds(cl);
585         }
586 }