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