fix uninitialized variables
[project/uhttpd.git] / client.c
1 /*
2  * uhttpd - Tiny single-threaded httpd
3  *
4  *   Copyright (C) 2010-2012 Jo-Philipp Wich <xm@subsignal.org>
5  *   Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
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         const char *enc = "Transfer-Encoding: chunked\r\n";
46         const char *conn;
47
48         if (!uh_use_chunked(cl))
49                 enc = "";
50
51         if (cl->request.version != UH_HTTP_VER_1_1)
52                 conn = "Connection: close";
53         else
54                 conn = "Connection: keep-alive";
55
56         ustream_printf(cl->us, "%s %03i %s\r\n%s\r\n%s",
57                 http_versions[cl->request.version],
58                 code, summary, conn, enc);
59 }
60
61 static void uh_connection_close(struct client *cl)
62 {
63         cl->state = CLIENT_STATE_CLOSE;
64         cl->us->eof = true;
65         ustream_state_change(cl->us);
66 }
67
68 static void uh_dispatch_done(struct client *cl)
69 {
70         if (cl->dispatch.free)
71                 cl->dispatch.free(cl);
72 }
73
74 void uh_request_done(struct client *cl)
75 {
76         uh_chunk_eof(cl);
77         uh_dispatch_done(cl);
78         cl->us->notify_write = NULL;
79         memset(&cl->dispatch, 0, sizeof(cl->dispatch));
80
81         if (cl->request.version != UH_HTTP_VER_1_1 || !conf.http_keepalive) {
82                 uh_connection_close(cl);
83                 return;
84         }
85
86         cl->state = CLIENT_STATE_INIT;
87         uloop_timeout_set(&cl->timeout, conf.http_keepalive * 1000);
88 }
89
90 void __printf(4, 5)
91 uh_client_error(struct client *cl, int code, const char *summary, const char *fmt, ...)
92 {
93         va_list arg;
94
95         uh_http_header(cl, code, summary);
96         ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
97
98         uh_chunk_printf(cl, "<h1>%s</h1>", summary);
99
100         if (fmt) {
101                 va_start(arg, fmt);
102                 uh_chunk_vprintf(cl, fmt, arg);
103                 va_end(arg);
104         }
105
106         uh_request_done(cl);
107 }
108
109 static void uh_header_error(struct client *cl, int code, const char *summary)
110 {
111         uh_client_error(cl, code, summary, NULL);
112         uh_connection_close(cl);
113 }
114
115 static void client_timeout(struct uloop_timeout *timeout)
116 {
117         struct client *cl = container_of(timeout, struct client, timeout);
118
119         cl->state = CLIENT_STATE_CLOSE;
120         uh_connection_close(cl);
121 }
122
123 static int find_idx(const char * const *list, int max, const char *str)
124 {
125         int i;
126
127         for (i = 0; i < max; i++)
128                 if (!strcmp(list[i], str))
129                         return i;
130
131         return -1;
132 }
133
134 static int client_parse_request(struct client *cl, char *data)
135 {
136         struct http_request *req = &cl->request;
137         char *type, *path, *version;
138         int h_method, h_version;
139
140         type = strtok(data, " ");
141         path = strtok(NULL, " ");
142         version = strtok(NULL, " ");
143         if (!type || !path || !version)
144                 return CLIENT_STATE_DONE;
145
146         blobmsg_add_string(&cl->hdr, "URL", path);
147
148         memset(&cl->request, 0, sizeof(cl->request));
149         h_method = find_idx(http_methods, ARRAY_SIZE(http_methods), type);
150         h_version = find_idx(http_versions, ARRAY_SIZE(http_versions), version);
151         if (h_method < 0 || h_version < 0) {
152                 req->version = UH_HTTP_VER_1_0;
153                 return CLIENT_STATE_DONE;
154         }
155
156         req->method = h_method;
157         req->version = h_version;
158
159         return CLIENT_STATE_HEADER;
160 }
161
162 static bool client_init_cb(struct client *cl, char *buf, int len)
163 {
164         char *newline;
165
166         newline = strstr(buf, "\r\n");
167         if (!newline)
168                 return false;
169
170         *newline = 0;
171         blob_buf_init(&cl->hdr, 0);
172         cl->state = client_parse_request(cl, buf);
173         ustream_consume(cl->us, newline + 2 - buf);
174         if (cl->state == CLIENT_STATE_DONE)
175                 uh_header_error(cl, 400, "Bad Request");
176
177         return true;
178 }
179
180 static bool rfc1918_filter_check(struct client *cl)
181 {
182         if (!conf.rfc1918_filter)
183                 return true;
184
185         if (!uh_addr_rfc1918(&cl->peer_addr) || uh_addr_rfc1918(&cl->srv_addr))
186                 return true;
187
188         uh_client_error(cl, 403, "Forbidden",
189                         "Rejected request from RFC1918 IP "
190                         "to public server address");
191         return false;
192 }
193
194 static void client_header_complete(struct client *cl)
195 {
196         if (!rfc1918_filter_check(cl))
197                 return;
198
199         if (cl->request.expect_cont)
200                 ustream_printf(cl->us, "HTTP/1.1 100 Continue\r\n\r\n");
201
202         uh_handle_request(cl);
203 }
204
205 static void client_parse_header(struct client *cl, char *data)
206 {
207         struct http_request *r = &cl->request;
208         char *err;
209         char *name;
210         char *val;
211
212         if (!*data) {
213                 uloop_timeout_cancel(&cl->timeout);
214                 cl->state = CLIENT_STATE_DATA;
215                 client_header_complete(cl);
216                 return;
217         }
218
219         val = uh_split_header(data);
220         if (!val) {
221                 cl->state = CLIENT_STATE_DONE;
222                 return;
223         }
224
225         for (name = data; *name; name++)
226                 if (isupper(*name))
227                         *name = tolower(*name);
228
229         if (!strcmp(data, "expect")) {
230                 if (!strcasecmp(val, "100-continue"))
231                         r->expect_cont = true;
232                 else {
233                         uh_header_error(cl, 412, "Precondition Failed");
234                         return;
235                 }
236         } else if (!strcmp(data, "content-length")) {
237                 r->content_length = strtoul(val, &err, 0);
238                 if (err && *err) {
239                         uh_header_error(cl, 400, "Bad Request");
240                         return;
241                 }
242         } else if (!strcmp(data, "transfer-encoding")) {
243                 if (!strcmp(val, "chunked"))
244                         r->transfer_chunked = true;
245         }
246
247
248         blobmsg_add_string(&cl->hdr, data, val);
249
250         cl->state = CLIENT_STATE_HEADER;
251 }
252
253 void client_poll_post_data(struct client *cl)
254 {
255         struct dispatch *d = &cl->dispatch;
256         struct http_request *r = &cl->request;
257         char *buf;
258         int len;
259
260         if (cl->state == CLIENT_STATE_DONE)
261                 return;
262
263         while (1) {
264                 char *sep;
265                 int offset = 0;
266                 int cur_len;
267
268                 buf = ustream_get_read_buf(cl->us, &len);
269                 if (!buf || !len)
270                         break;
271
272                 if (!d->data_send)
273                         return;
274
275                 cur_len = min(r->content_length, len);
276                 if (cur_len) {
277                         if (d->data_blocked)
278                                 break;
279
280                         if (d->data_send)
281                                 cur_len = d->data_send(cl, buf, cur_len);
282
283                         r->content_length -= cur_len;
284                         ustream_consume(cl->us, cur_len);
285                         continue;
286                 }
287
288                 if (!r->transfer_chunked)
289                         break;
290
291                 if (r->transfer_chunked > 1)
292                         offset = 2;
293
294                 sep = strstr(buf + offset, "\r\n");
295                 if (!sep)
296                         break;
297
298                 *sep = 0;
299
300                 r->content_length = strtoul(buf + offset, &sep, 16);
301                 r->transfer_chunked++;
302                 ustream_consume(cl->us, sep + 2 - buf);
303
304                 /* invalid chunk length */
305                 if (sep && *sep) {
306                         r->content_length = 0;
307                         r->transfer_chunked = 0;
308                         break;
309                 }
310
311                 /* empty chunk == eof */
312                 if (!r->content_length) {
313                         r->transfer_chunked = false;
314                         break;
315                 }
316         }
317
318         buf = ustream_get_read_buf(cl->us, &len);
319         if (!r->content_length && !r->transfer_chunked &&
320                 cl->state != CLIENT_STATE_DONE) {
321                 if (cl->dispatch.data_done)
322                         cl->dispatch.data_done(cl);
323
324                 cl->state = CLIENT_STATE_DONE;
325         }
326 }
327
328 static bool client_data_cb(struct client *cl, char *buf, int len)
329 {
330         client_poll_post_data(cl);
331         return false;
332 }
333
334 static bool client_header_cb(struct client *cl, char *buf, int len)
335 {
336         char *newline;
337         int line_len;
338
339         newline = strstr(buf, "\r\n");
340         if (!newline)
341                 return false;
342
343         *newline = 0;
344         client_parse_header(cl, buf);
345         line_len = newline + 2 - buf;
346         ustream_consume(cl->us, line_len);
347         if (cl->state == CLIENT_STATE_DATA)
348                 return client_data_cb(cl, newline + 2, len - line_len);
349
350         return true;
351 }
352
353 typedef bool (*read_cb_t)(struct client *cl, char *buf, int len);
354 static read_cb_t read_cbs[] = {
355         [CLIENT_STATE_INIT] = client_init_cb,
356         [CLIENT_STATE_HEADER] = client_header_cb,
357         [CLIENT_STATE_DATA] = client_data_cb,
358 };
359
360 void uh_client_read_cb(struct client *cl)
361 {
362         struct ustream *us = cl->us;
363         char *str;
364         int len;
365
366         do {
367                 str = ustream_get_read_buf(us, &len);
368                 if (!str || !len)
369                         break;
370
371                 if (cl->state >= array_size(read_cbs) || !read_cbs[cl->state])
372                         break;
373
374                 if (!read_cbs[cl->state](cl, str, len)) {
375                         if (len == us->r.buffer_len &&
376                             cl->state != CLIENT_STATE_DATA)
377                                 uh_header_error(cl, 413, "Request Entity Too Large");
378                         break;
379                 }
380         } while(1);
381 }
382
383 static void client_close(struct client *cl)
384 {
385         n_clients--;
386         uh_dispatch_done(cl);
387         uloop_timeout_cancel(&cl->timeout);
388         if (cl->tls)
389                 uh_tls_client_detach(cl);
390         ustream_free(&cl->sfd.stream);
391         close(cl->sfd.fd.fd);
392         list_del(&cl->list);
393         blob_buf_free(&cl->hdr);
394         free(cl);
395
396         uh_unblock_listeners();
397 }
398
399 void uh_client_notify_state(struct client *cl)
400 {
401         struct ustream *s = cl->us;
402
403         if (!s->write_error) {
404                 if (cl->state == CLIENT_STATE_DATA)
405                         return;
406
407                 if (!s->eof || s->w.data_bytes)
408                         return;
409         }
410
411         return client_close(cl);
412 }
413
414 static void client_ustream_read_cb(struct ustream *s, int bytes)
415 {
416         struct client *cl = container_of(s, struct client, sfd);
417
418         uh_client_read_cb(cl);
419 }
420
421 static void client_ustream_write_cb(struct ustream *s, int bytes)
422 {
423         struct client *cl = container_of(s, struct client, sfd);
424
425         if (cl->dispatch.write_cb)
426                 cl->dispatch.write_cb(cl);
427 }
428
429 static void client_notify_state(struct ustream *s)
430 {
431         struct client *cl = container_of(s, struct client, sfd);
432
433         uh_client_notify_state(cl);
434 }
435
436 static void set_addr(struct uh_addr *addr, void *src)
437 {
438         struct sockaddr_in *sin = src;
439         struct sockaddr_in6 *sin6 = src;
440
441         addr->family = sin->sin_family;
442         if (addr->family == AF_INET) {
443                 addr->port = ntohs(sin->sin_port);
444                 memcpy(&addr->in, &sin->sin_addr, sizeof(addr->in));
445         } else {
446                 addr->port = ntohs(sin6->sin6_port);
447                 memcpy(&addr->in6, &sin6->sin6_addr, sizeof(addr->in6));
448         }
449 }
450
451 bool uh_accept_client(int fd, bool tls)
452 {
453         static struct client *next_client;
454         struct client *cl;
455         unsigned int sl;
456         int sfd;
457         static int client_id = 0;
458         struct sockaddr_in6 addr;
459
460         if (!next_client)
461                 next_client = calloc(1, sizeof(*next_client));
462
463         cl = next_client;
464
465         sl = sizeof(addr);
466         sfd = accept(fd, (struct sockaddr *) &addr, &sl);
467         if (sfd < 0)
468                 return false;
469
470         set_addr(&cl->peer_addr, &addr);
471         sl = sizeof(addr);
472         getsockname(fd, (struct sockaddr *) &addr, &sl);
473         set_addr(&cl->srv_addr, &addr);
474
475         cl->us = &cl->sfd.stream;
476         if (tls) {
477                 uh_tls_client_attach(cl);
478         } else {
479                 cl->us->notify_read = client_ustream_read_cb;
480                 cl->us->notify_write = client_ustream_write_cb;
481                 cl->us->notify_state = client_notify_state;
482         }
483
484         cl->us->string_data = true;
485         ustream_fd_init(&cl->sfd, sfd);
486
487         cl->timeout.cb = client_timeout;
488         uloop_timeout_set(&cl->timeout, conf.network_timeout * 1000);
489
490         list_add_tail(&cl->list, &clients);
491
492         next_client = NULL;
493         n_clients++;
494         cl->id = client_id++;
495
496         return true;
497 }
498
499 void uh_close_fds(void)
500 {
501         struct client *cl;
502
503         uloop_done();
504         uh_close_listen_fds();
505         list_for_each_entry(cl, &clients, list) {
506                 close(cl->sfd.fd.fd);
507                 if (cl->dispatch.close_fds)
508                         cl->dispatch.close_fds(cl);
509         }
510 }