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