15f3d8c1922da6e0223fc85d2e2c5356149a467d
[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         memset(&cl->dispatch, 0, sizeof(cl->dispatch));
114
115         if (!conf.http_keepalive || cl->request.connection_close)
116                 return uh_connection_close(cl);
117
118         cl->state = CLIENT_STATE_INIT;
119         cl->requests++;
120         uh_poll_connection(cl);
121 }
122
123 void __printf(4, 5)
124 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
125 {
126         va_list arg;
127
128         uh_http_header(cl, code, summary);
129         ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
130
131         uh_chunk_printf(cl, "<h1>%s</h1>", summary);
132
133         if (fmt) {
134                 va_start(arg, fmt);
135                 uh_chunk_vprintf(cl, fmt, arg);
136                 va_end(arg);
137         }
138
139         uh_request_done(cl);
140 }
141
142 static void uh_header_error(struct client *cl, int code, const char *summary)
143 {
144         uh_client_error(cl, code, summary, NULL);
145         uh_connection_close(cl);
146 }
147
148 static int find_idx(const char * const *list, int max, const char *str)
149 {
150         int i;
151
152         for (i = 0; i < max; i++)
153                 if (!strcmp(list[i], str))
154                         return i;
155
156         return -1;
157 }
158
159 static int client_parse_request(struct client *cl, char *data)
160 {
161         struct http_request *req = &cl->request;
162         char *type, *path, *version;
163         int h_method, h_version;
164
165         type = strtok(data, " ");
166         path = strtok(NULL, " ");
167         version = strtok(NULL, " ");
168         if (!type || !path || !version)
169                 return CLIENT_STATE_DONE;
170
171         blobmsg_add_string(&cl->hdr, "URL", path);
172
173         memset(&cl->request, 0, sizeof(cl->request));
174         h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
175         h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
176         if (h_method < 0 || h_version < 0) {
177                 req->version = UH_HTTP_VER_1_0;
178                 return CLIENT_STATE_DONE;
179         }
180
181         req->method = h_method;
182         req->version = h_version;
183         if (req->version < UH_HTTP_VER_1_1 || req->method == UH_HTTP_MSG_POST ||
184             !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                 ustream_consume(cl->us, 2);
200                 return true;
201         }
202
203         *newline = 0;
204         blob_buf_init(&cl->hdr, 0);
205         cl->state = client_parse_request(cl, buf);
206         ustream_consume(cl->us, newline + 2 - buf);
207         if (cl->state == CLIENT_STATE_DONE)
208                 uh_header_error(cl, 400, "Bad Request");
209
210         return true;
211 }
212
213 static bool rfc1918_filter_check(struct client *cl)
214 {
215         if (!conf.rfc1918_filter)
216                 return true;
217
218         if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
219                 return true;
220
221         uh_client_error(cl, 403, "Forbidden",
222                         "Rejected request from RFC1918 IP "
223                         "to public server address");
224         return false;
225 }
226
227 static void client_header_complete(struct client *cl)
228 {
229         struct http_request *r = &cl->request;
230
231         if (!rfc1918_filter_check(cl))
232                 return;
233
234         if (r->expect_cont)
235                 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
236
237         switch(r->ua) {
238         case UH_UA_MSIE_OLD:
239                 if (r->method != UH_HTTP_MSG_POST)
240                         break;
241
242                 /* fall through */
243         case UH_UA_SAFARI:
244                 r->connection_close = true;
245                 break;
246         default:
247                 break;
248         }
249
250         uh_handle_request(cl);
251 }
252
253 static void client_parse_header(struct client *cl, char *data)
254 {
255         struct http_request *r = &cl->request;
256         char *err;
257         char *name;
258         char *val;
259
260         if (!*data) {
261                 uloop_timeout_cancel(&cl->timeout);
262                 cl->state = CLIENT_STATE_DATA;
263                 client_header_complete(cl);
264                 return;
265         }
266
267         val = uh_split_header(data);
268         if (!val) {
269                 cl->state = CLIENT_STATE_DONE;
270                 return;
271         }
272
273         for (name = data; *name; name++)
274                 if (isupper(*name))
275                         *name = tolower(*name);
276
277         if (!strcmp(data, "expect")) {
278                 if (!strcasecmp(val, "100-continue"))
279                         r->expect_cont = true;
280                 else {
281                         uh_header_error(cl, 412, "Precondition Failed");
282                         return;
283                 }
284         } else if (!strcmp(data, "content-length")) {
285                 r->content_length = strtoul(val, &err, 0);
286                 if (err && *err) {
287                         uh_header_error(cl, 400, "Bad Request");
288                         return;
289                 }
290         } else if (!strcmp(data, "transfer-encoding")) {
291                 if (!strcmp(val, "chunked"))
292                         r->transfer_chunked = true;
293         } else if (!strcmp(data, "connection")) {
294                 if (!strcasecmp(val, "close"))
295                         r->connection_close = true;
296                 else if (!strcasecmp(val, "keep-alive"))
297                         r->connection_close = false;
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                 } else if (strstr(val, "Safari/") && strstr(val, "Mac OS X"))
318                         r->ua = UH_UA_SAFARI;
319                 else if (strstr(val, "Chrome/"))
320                         r->ua = UH_UA_CHROME;
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         do {
447                 str = ustream_get_read_buf(us, &len);
448                 if (!str || !len)
449                         break;
450
451                 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
452                         break;
453
454                 if (!read_cbs[cl->state](cl, str, len)) {
455                         if (len == us->r.buffer_len &&
456                             cl->state != CLIENT_STATE_DATA)
457                                 uh_header_error(cl, 413, "Request Entity Too Large");
458                         break;
459                 }
460         } while(1);
461 }
462
463 static void client_close(struct client *cl)
464 {
465         n_clients--;
466         uh_dispatch_done(cl);
467         uloop_timeout_cancel(&cl->timeout);
468         if (cl->tls)
469                 uh_tls_client_detach(cl);
470         ustream_free(&cl->sfd.stream);
471         close(cl->sfd.fd.fd);
472         list_del(&cl->list);
473         blob_buf_free(&cl->hdr);
474         free(cl);
475
476         uh_unblock_listeners();
477 }
478
479 void uh_client_notify_state(struct client *cl)
480 {
481         struct ustream *s = cl->us;
482
483         if (!s->write_error) {
484                 if (cl->state == CLIENT_STATE_DATA)
485                         return;
486
487                 if (!s->eof || s->w.data_bytes)
488                         return;
489         }
490
491         return client_close(cl);
492 }
493
494 static void client_ustream_read_cb(struct ustream *s, int bytes)
495 {
496         struct client *cl = container_of(s, struct client, sfd.stream);
497
498         uh_client_read_cb(cl);
499 }
500
501 static void client_ustream_write_cb(struct ustream *s, int bytes)
502 {
503         struct client *cl = container_of(s, struct client, sfd.stream);
504
505         if (cl->dispatch.write_cb)
506                 cl->dispatch.write_cb(cl);
507 }
508
509 static void client_notify_state(struct ustream *s)
510 {
511         struct client *cl = container_of(s, struct client, sfd.stream);
512
513         uh_client_notify_state(cl);
514 }
515
516 static void set_addr(struct uh_addr *addr, void *src)
517 {
518         struct sockaddr_in *sin = src;
519         struct sockaddr_in6 *sin6 = src;
520
521         addr->family = sin->sin_family;
522         if (addr->family == AF_INET) {
523                 addr->port = ntohs(sin->sin_port);
524                 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
525         } else {
526                 addr->port = ntohs(sin6->sin6_port);
527                 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
528         }
529 }
530
531 bool uh_accept_client(int fd, bool tls)
532 {
533         static struct client *next_client;
534         struct client *cl;
535         unsigned int sl;
536         int sfd;
537         static int client_id = 0;
538         struct sockaddr_in6 addr;
539
540         if (!next_client)
541                 next_client = calloc(1, sizeof(*next_client));
542
543         cl = next_client;
544
545         sl = sizeof(addr);
546         sfd = accept(fd, (struct sockaddr *) &addr, &sl);
547         if (sfd < 0)
548                 return false;
549
550         set_addr(&cl->peer_addr, &addr);
551         sl = sizeof(addr);
552         getsockname(sfd, (struct sockaddr *) &addr, &sl);
553         set_addr(&cl->srv_addr, &addr);
554
555         cl->us = &cl->sfd.stream;
556         if (tls) {
557                 uh_tls_client_attach(cl);
558         } else {
559                 cl->us->notify_read = client_ustream_read_cb;
560                 cl->us->notify_write = client_ustream_write_cb;
561                 cl->us->notify_state = client_notify_state;
562         }
563
564         cl->us->string_data = true;
565         ustream_fd_init(&cl->sfd, sfd);
566
567         uh_poll_connection(cl);
568         list_add_tail(&cl->list, &clients);
569
570         next_client = NULL;
571         n_clients++;
572         cl->id = client_id++;
573         cl->tls = tls;
574
575         return true;
576 }
577
578 void uh_close_fds(void)
579 {
580         struct client *cl;
581
582         uloop_done();
583         uh_close_listen_fds();
584         list_for_each_entry(cl, &clients, list) {
585                 close(cl->sfd.fd.fd);
586                 if (cl->dispatch.close_fds)
587                         cl->dispatch.close_fds(cl);
588         }
589 }