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