[package] uhttpd: do not dispatch pipe error events, fixes use after free for cgi...
[openwrt.git] / package / uhttpd / src / uhttpd.c
1 /*
2  * uhttpd - Tiny single-threaded httpd - Main component
3  *
4  *   Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  */
18
19 #define _XOPEN_SOURCE 500       /* crypt() */
20
21 #include "uhttpd.h"
22 #include "uhttpd-utils.h"
23 #include "uhttpd-file.h"
24
25 #ifdef HAVE_CGI
26 #include "uhttpd-cgi.h"
27 #endif
28
29 #ifdef HAVE_LUA
30 #include "uhttpd-lua.h"
31 #endif
32
33 #ifdef HAVE_TLS
34 #include "uhttpd-tls.h"
35 #endif
36
37
38 static int run = 1;
39
40 static void uh_sigterm(int sig)
41 {
42         run = 0;
43 }
44
45 static void uh_config_parse(struct config *conf)
46 {
47         FILE *c;
48         char line[512];
49         char *col1 = NULL;
50         char *col2 = NULL;
51         char *eol  = NULL;
52
53         const char *path = conf->file ? conf->file : "/etc/httpd.conf";
54
55
56         if ((c = fopen(path, "r")) != NULL)
57         {
58                 memset(line, 0, sizeof(line));
59
60                 while (fgets(line, sizeof(line) - 1, c))
61                 {
62                         if ((line[0] == '/') && (strchr(line, ':') != NULL))
63                         {
64                                 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
65                                     !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
66                                         !(eol = strchr(col2, '\n')) || (*eol++  = 0))
67                                 {
68                                         continue;
69                                 }
70
71                                 if (!uh_auth_add(line, col1, col2))
72                                 {
73                                         fprintf(stderr,
74                                                         "Notice: No password set for user %s, ignoring "
75                                                         "authentication on %s\n", col1, line
76                                         );
77                                 }
78                         }
79                         else if (!strncmp(line, "I:", 2))
80                         {
81                                 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
82                                     !(eol = strchr(col1, '\n')) || (*eol++  = 0))
83                                 {
84                                         continue;
85                                 }
86
87                                 conf->index_file = strdup(col1);
88                         }
89                         else if (!strncmp(line, "E404:", 5))
90                         {
91                                 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
92                                     !(eol = strchr(col1, '\n')) || (*eol++  = 0))
93                                 {
94                                         continue;
95                                 }
96
97                                 conf->error_handler = strdup(col1);
98                         }
99 #ifdef HAVE_CGI
100                         else if ((line[0] == '*') && (strchr(line, ':') != NULL))
101                         {
102                                 if (!(col1 = strchr(line, '*')) || (*col1++ = 0) ||
103                                     !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
104                                     !(eol = strchr(col2, '\n')) || (*eol++  = 0))
105                                 {
106                                         continue;
107                                 }
108
109                                 if (!uh_interpreter_add(col1, col2))
110                                 {
111                                         fprintf(stderr,
112                                                         "Unable to add interpreter %s for extension %s: "
113                                                         "Out of memory\n", col2, col1
114                                         );
115                                 }
116                         }
117 #endif
118                 }
119
120                 fclose(c);
121         }
122 }
123
124 static void uh_listener_cb(struct uloop_fd *u, unsigned int events);
125
126 static int uh_socket_bind(fd_set *serv_fds, int *max_fd,
127                                                   const char *host, const char *port,
128                                                   struct addrinfo *hints, int do_tls,
129                                                   struct config *conf)
130 {
131         int sock = -1;
132         int yes = 1;
133         int status;
134         int bound = 0;
135
136         int tcp_ka_idl, tcp_ka_int, tcp_ka_cnt;
137
138         struct listener *l = NULL;
139         struct addrinfo *addrs = NULL, *p = NULL;
140
141         if ((status = getaddrinfo(host, port, hints, &addrs)) != 0)
142         {
143                 fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
144         }
145
146         /* try to bind a new socket to each found address */
147         for (p = addrs; p; p = p->ai_next)
148         {
149                 /* get the socket */
150                 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
151                 {
152                         perror("socket()");
153                         goto error;
154                 }
155
156                 /* "address already in use" */
157                 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)))
158                 {
159                         perror("setsockopt()");
160                         goto error;
161                 }
162
163                 /* TCP keep-alive */
164                 if (conf->tcp_keepalive > 0)
165                 {
166                         tcp_ka_idl = 1;
167                         tcp_ka_cnt = 3;
168                         tcp_ka_int = conf->tcp_keepalive;
169
170                         if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) ||
171                             setsockopt(sock, SOL_TCP, TCP_KEEPIDLE,  &tcp_ka_idl, sizeof(tcp_ka_idl)) ||
172                             setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, &tcp_ka_int, sizeof(tcp_ka_int)) ||
173                             setsockopt(sock, SOL_TCP, TCP_KEEPCNT,   &tcp_ka_cnt, sizeof(tcp_ka_cnt)))
174                         {
175                             fprintf(stderr, "Notice: Unable to enable TCP keep-alive: %s\n",
176                                 strerror(errno));
177                         }
178                 }
179
180                 /* required to get parallel v4 + v6 working */
181                 if (p->ai_family == AF_INET6)
182                 {
183                         if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)) == -1)
184                         {
185                                 perror("setsockopt()");
186                                 goto error;
187                         }
188                 }
189
190                 /* bind */
191                 if (bind(sock, p->ai_addr, p->ai_addrlen) == -1)
192                 {
193                         perror("bind()");
194                         goto error;
195                 }
196
197                 /* listen */
198                 if (listen(sock, UH_LIMIT_CLIENTS) == -1)
199                 {
200                         perror("listen()");
201                         goto error;
202                 }
203
204                 /* add listener to global list */
205                 if (!(l = uh_listener_add(sock, conf)))
206                 {
207                         fprintf(stderr, "uh_listener_add(): Failed to allocate memory\n");
208                         goto error;
209                 }
210
211 #ifdef HAVE_TLS
212                 /* init TLS */
213                 l->tls = do_tls ? conf->tls : NULL;
214 #endif
215
216                 /* add socket to server fd set */
217                 FD_SET(sock, serv_fds);
218                 fd_cloexec(sock);
219                 *max_fd = max(*max_fd, sock);
220
221                 l->fd.cb = uh_listener_cb;
222                 uloop_fd_add(&l->fd, ULOOP_READ);
223
224                 bound++;
225                 continue;
226
227                 error:
228                 if (sock > 0)
229                         close(sock);
230         }
231
232         freeaddrinfo(addrs);
233
234         return bound;
235 }
236
237 static struct http_request * uh_http_header_parse(struct client *cl,
238                                                                                                   char *buffer, int buflen)
239 {
240         char *method  = buffer;
241         char *path    = NULL;
242         char *version = NULL;
243
244         char *headers = NULL;
245         char *hdrname = NULL;
246         char *hdrdata = NULL;
247
248         int i;
249         int hdrcount = 0;
250
251         struct http_request *req = &cl->request;
252
253
254         /* terminate initial header line */
255         if ((headers = strfind(buffer, buflen, "\r\n", 2)) != NULL)
256         {
257                 buffer[buflen-1] = 0;
258
259                 *headers++ = 0;
260                 *headers++ = 0;
261
262                 /* find request path */
263                 if ((path = strchr(buffer, ' ')) != NULL)
264                         *path++ = 0;
265
266                 /* find http version */
267                 if ((path != NULL) && ((version = strchr(path, ' ')) != NULL))
268                         *version++ = 0;
269
270
271                 /* check method */
272                 if (strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST"))
273                 {
274                         /* invalid method */
275                         uh_http_response(cl, 405, "Method Not Allowed");
276                         return NULL;
277                 }
278                 else
279                 {
280                         switch(method[0])
281                         {
282                                 case 'G':
283                                         req->method = UH_HTTP_MSG_GET;
284                                         break;
285
286                                 case 'H':
287                                         req->method = UH_HTTP_MSG_HEAD;
288                                         break;
289
290                                 case 'P':
291                                         req->method = UH_HTTP_MSG_POST;
292                                         break;
293                         }
294                 }
295
296                 /* check path */
297                 if (!path || !strlen(path))
298                 {
299                         /* malformed request */
300                         uh_http_response(cl, 400, "Bad Request");
301                         return NULL;
302                 }
303                 else
304                 {
305                         req->url = path;
306                 }
307
308                 /* check version */
309                 if ((version == NULL) || (strcmp(version, "HTTP/0.9") &&
310                     strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1")))
311                 {
312                         /* unsupported version */
313                         uh_http_response(cl, 400, "Bad Request");
314                         return NULL;
315                 }
316                 else
317                 {
318                         req->version = strtof(&version[5], NULL);
319                 }
320
321                 D("SRV: %s %s HTTP/%.1f\n",
322                   (req->method == UH_HTTP_MSG_POST) ? "POST" :
323                         (req->method == UH_HTTP_MSG_GET) ? "GET" : "HEAD",
324                   req->url, req->version);
325
326                 /* process header fields */
327                 for (i = (int)(headers - buffer); i < buflen; i++)
328                 {
329                         /* found eol and have name + value, push out header tuple */
330                         if (hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n'))
331                         {
332                                 buffer[i] = 0;
333
334                                 /* store */
335                                 if ((hdrcount + 1) < array_size(req->headers))
336                                 {
337                                         D("SRV: HTTP: %s: %s\n", hdrname, hdrdata);
338
339                                         req->headers[hdrcount++] = hdrname;
340                                         req->headers[hdrcount++] = hdrdata;
341
342                                         hdrname = hdrdata = NULL;
343                                 }
344
345                                 /* too large */
346                                 else
347                                 {
348                                         D("SRV: HTTP: header too big (too many headers)\n");
349                                         uh_http_response(cl, 413, "Request Entity Too Large");
350                                         return NULL;
351                                 }
352                         }
353
354                         /* have name but no value and found a colon, start of value */
355                         else if (hdrname && !hdrdata &&
356                                          ((i+1) < buflen) && (buffer[i] == ':'))
357                         {
358                                 buffer[i] = 0;
359                                 hdrdata = &buffer[i+1];
360
361                                 while ((hdrdata + 1) < (buffer + buflen) && *hdrdata == ' ')
362                                         hdrdata++;
363                         }
364
365                         /* have no name and found [A-Za-z], start of name */
366                         else if (!hdrname && isalpha(buffer[i]))
367                         {
368                                 hdrname = &buffer[i];
369                         }
370                 }
371
372                 /* valid enough */
373                 req->redirect_status = 200;
374                 return req;
375         }
376
377         /* Malformed request */
378         uh_http_response(cl, 400, "Bad Request");
379         return NULL;
380 }
381
382
383 static struct http_request * uh_http_header_recv(struct client *cl)
384 {
385         char *bufptr = cl->httpbuf.buf;
386         char *idxptr = NULL;
387
388         ssize_t blen = sizeof(cl->httpbuf.buf)-1;
389         ssize_t rlen = 0;
390
391         memset(bufptr, 0, sizeof(cl->httpbuf.buf));
392
393         while (blen > 0)
394         {
395                 /* receive data */
396                 ensure_out(rlen = uh_tcp_recv(cl, bufptr, blen));
397                 D("SRV: Client(%d) peek(%d) = %d\n", cl->fd.fd, blen, rlen);
398
399                 if (rlen <= 0)
400                 {
401                         D("SRV: Client(%d) dead [%s]\n", cl->fd.fd, strerror(errno));
402                         return NULL;
403                 }
404
405                 blen -= rlen;
406                 bufptr += rlen;
407
408                 if ((idxptr = strfind(cl->httpbuf.buf, sizeof(cl->httpbuf.buf),
409                                                           "\r\n\r\n", 4)))
410                 {
411                         /* header read complete ... */
412                         cl->httpbuf.ptr = idxptr + 4;
413                         cl->httpbuf.len = bufptr - cl->httpbuf.ptr;
414
415                         return uh_http_header_parse(cl, cl->httpbuf.buf,
416                                                                                 (cl->httpbuf.ptr - cl->httpbuf.buf));
417                 }
418         }
419
420         /* request entity too large */
421         D("SRV: HTTP: header too big (buffer exceeded)\n");
422         uh_http_response(cl, 413, "Request Entity Too Large");
423
424 out:
425         return NULL;
426 }
427
428 #if defined(HAVE_LUA) || defined(HAVE_CGI)
429 static int uh_path_match(const char *prefix, const char *url)
430 {
431         if ((strstr(url, prefix) == url) &&
432                 ((prefix[strlen(prefix)-1] == '/') ||
433                  (strlen(url) == strlen(prefix))   ||
434                  (url[strlen(prefix)] == '/')))
435         {
436                 return 1;
437         }
438
439         return 0;
440 }
441 #endif
442
443 static bool uh_dispatch_request(struct client *cl, struct http_request *req)
444 {
445         struct path_info *pin;
446         struct interpreter *ipr = NULL;
447         struct config *conf = cl->server->conf;
448
449 #ifdef HAVE_LUA
450         /* Lua request? */
451         if (conf->lua_state &&
452                 uh_path_match(conf->lua_prefix, req->url))
453         {
454                 return conf->lua_request(cl, conf->lua_state);
455         }
456         else
457 #endif
458
459 #ifdef HAVE_UBUS
460         /* ubus request? */
461         if (conf->ubus_state &&
462                 uh_path_match(conf->ubus_prefix, req->url))
463         {
464                 return conf->ubus_request(cl, conf->ubus_state);
465         }
466         else
467 #endif
468
469         /* dispatch request */
470         if ((pin = uh_path_lookup(cl, req->url)) != NULL)
471         {
472                 /* auth ok? */
473                 if (!pin->redirected && uh_auth_check(cl, req, pin))
474                 {
475 #ifdef HAVE_CGI
476                         if (uh_path_match(conf->cgi_prefix, pin->name) ||
477                                 (ipr = uh_interpreter_lookup(pin->phys)) != NULL)
478                         {
479                                 return uh_cgi_request(cl, pin, ipr);
480                         }
481 #endif
482                         return uh_file_request(cl, pin);
483                 }
484         }
485
486         /* 404 - pass 1 */
487         else
488         {
489                 /* Try to invoke an error handler */
490                 if ((pin = uh_path_lookup(cl, conf->error_handler)) != NULL)
491                 {
492                         /* auth ok? */
493                         if (uh_auth_check(cl, req, pin))
494                         {
495                                 req->redirect_status = 404;
496 #ifdef HAVE_CGI
497                                 if (uh_path_match(conf->cgi_prefix, pin->name) ||
498                                         (ipr = uh_interpreter_lookup(pin->phys)) != NULL)
499                                 {
500                                         return uh_cgi_request(cl, pin, ipr);
501                                 }
502 #endif
503                                 return uh_file_request(cl, pin);
504                         }
505                 }
506
507                 /* 404 - pass 2 */
508                 else
509                 {
510                         uh_http_sendhf(cl, 404, "Not Found", "No such file or directory");
511                 }
512         }
513
514         return false;
515 }
516
517 static void uh_client_cb(struct uloop_fd *u, unsigned int events);
518
519 static void uh_listener_cb(struct uloop_fd *u, unsigned int events)
520 {
521         int new_fd;
522         struct listener *serv;
523         struct client *cl;
524         struct config *conf;
525
526         serv = container_of(u, struct listener, fd);
527         conf = serv->conf;
528
529         /* defer client if maximum number of requests is exceeded */
530         if (serv->n_clients >= conf->max_requests)
531                 return;
532
533         /* handle new connections */
534         if ((new_fd = accept(u->fd, NULL, 0)) != -1)
535         {
536                 D("SRV: Server(%d) accept => Client(%d)\n", u->fd, new_fd);
537
538                 /* add to global client list */
539                 if ((cl = uh_client_add(new_fd, serv)) != NULL)
540                 {
541                         /* add client socket to global fdset */
542                         uloop_fd_add(&cl->fd, ULOOP_READ);
543
544 #ifdef HAVE_TLS
545                         /* setup client tls context */
546                         if (conf->tls)
547                         {
548                                 if (conf->tls_accept(cl) < 1)
549                                 {
550                                         D("SRV: Client(%d) SSL handshake failed, drop\n", new_fd);
551
552                                         /* remove from global client list */
553                                         uh_client_remove(cl);
554                                         return;
555                                 }
556                         }
557 #endif
558
559                         cl->fd.cb = uh_client_cb;
560                         fd_cloexec(new_fd);
561                 }
562
563                 /* insufficient resources */
564                 else
565                 {
566                         fprintf(stderr, "uh_client_add(): Cannot allocate memory\n");
567                         close(new_fd);
568                 }
569         }
570 }
571
572 static void uh_pipe_cb(struct uloop_fd *u, unsigned int events)
573 {
574         struct client *cl = container_of(u, struct client, pipe);
575
576         if (!u->error)
577         {
578                 D("SRV: Client(%d) pipe(%d) readable\n",
579                   cl->fd.fd, cl->pipe.fd);
580
581                 uh_client_cb(&cl->fd, ULOOP_WRITE);
582         }
583 }
584
585 static void uh_child_cb(struct uloop_process *p, int rv)
586 {
587         struct client *cl = container_of(p, struct client, proc);
588
589         D("SRV: Client(%d) child(%d) is dead\n", cl->fd.fd, cl->proc.pid);
590
591         cl->dead = true;
592         cl->fd.eof = true;
593         uh_client_cb(&cl->fd, ULOOP_READ | ULOOP_WRITE);
594 }
595
596 static void uh_kill9_cb(struct uloop_timeout *t)
597 {
598         struct client *cl = container_of(t, struct client, timeout);
599
600         if (!kill(cl->proc.pid, 0))
601         {
602                 D("SRV: Client(%d) child(%d) kill(SIGKILL)...\n",
603                   cl->fd.fd, cl->proc.pid);
604
605                 kill(cl->proc.pid, SIGKILL);
606         }
607 }
608
609 static void uh_timeout_cb(struct uloop_timeout *t)
610 {
611         struct client *cl = container_of(t, struct client, timeout);
612
613         D("SRV: Client(%d) child(%d) timed out\n", cl->fd.fd, cl->proc.pid);
614
615         if (!kill(cl->proc.pid, 0))
616         {
617                 D("SRV: Client(%d) child(%d) kill(SIGTERM)...\n",
618                   cl->fd.fd, cl->proc.pid);
619
620                 kill(cl->proc.pid, SIGTERM);
621
622                 cl->timeout.cb = uh_kill9_cb;
623                 uloop_timeout_set(&cl->timeout, 1000);
624         }
625 }
626
627 static void uh_client_cb(struct uloop_fd *u, unsigned int events)
628 {
629         int i;
630         struct client *cl;
631         struct config *conf;
632         struct http_request *req;
633
634         cl = container_of(u, struct client, fd);
635         conf = cl->server->conf;
636
637         D("SRV: Client(%d) enter callback\n", u->fd);
638
639         /* undispatched yet */
640         if (!cl->dispatched)
641         {
642                 /* we have no headers yet and this was a write event, ignore... */
643                 if (!(events & ULOOP_READ))
644                 {
645                         D("SRV: Client(%d) ignoring write event before headers\n", u->fd);
646                         return;
647                 }
648
649                 /* attempt to receive and parse headers */
650                 if (!(req = uh_http_header_recv(cl)))
651                 {
652                         D("SRV: Client(%d) failed to receive header\n", u->fd);
653                         uh_client_shutdown(cl);
654                         return;
655                 }
656
657                 /* process expect headers */
658                 foreach_header(i, req->headers)
659                 {
660                         if (strcasecmp(req->headers[i], "Expect"))
661                                 continue;
662
663                         if (strcasecmp(req->headers[i+1], "100-continue"))
664                         {
665                                 D("SRV: Client(%d) unknown expect header (%s)\n",
666                                   u->fd, req->headers[i+1]);
667
668                                 uh_http_response(cl, 417, "Precondition Failed");
669                                 uh_client_shutdown(cl);
670                                 return;
671                         }
672                         else
673                         {
674                                 D("SRV: Client(%d) sending HTTP/1.1 100 Continue\n", u->fd);
675
676                                 uh_http_sendf(cl, NULL, "HTTP/1.1 100 Continue\r\n\r\n");
677                                 cl->httpbuf.len = 0; /* client will re-send the body */
678                                 break;
679                         }
680                 }
681
682                 /* RFC1918 filtering */
683                 if (conf->rfc1918_filter &&
684                         sa_rfc1918(&cl->peeraddr) && !sa_rfc1918(&cl->servaddr))
685                 {
686                         uh_http_sendhf(cl, 403, "Forbidden",
687                                                    "Rejected request from RFC1918 IP "
688                                                    "to public server address");
689
690                         uh_client_shutdown(cl);
691                         return;
692                 }
693
694                 /* dispatch request */
695                 if (!uh_dispatch_request(cl, req))
696                 {
697                         D("SRV: Client(%d) failed to dispach request\n", u->fd);
698                         uh_client_shutdown(cl);
699                         return;
700                 }
701
702                 /* request handler spawned a pipe, register handler */
703                 if (cl->pipe.fd)
704                 {
705                         D("SRV: Client(%d) pipe(%d) spawned\n", u->fd, cl->pipe.fd);
706
707                         cl->pipe.cb = uh_pipe_cb;
708                         uloop_fd_add(&cl->pipe, ULOOP_READ);
709                 }
710
711                 /* request handler spawned a child, register handler */
712                 if (cl->proc.pid)
713                 {
714                         D("SRV: Client(%d) child(%d) spawned\n", u->fd, cl->proc.pid);
715
716                         cl->proc.cb = uh_child_cb;
717                         uloop_process_add(&cl->proc);
718
719                         cl->timeout.cb = uh_timeout_cb;
720                         uloop_timeout_set(&cl->timeout, conf->script_timeout * 1000);
721                 }
722
723                 /* header processing complete */
724                 D("SRV: Client(%d) dispatched\n", u->fd);
725                 cl->dispatched = true;
726         }
727
728         if (!cl->cb(cl))
729         {
730                 D("SRV: Client(%d) response callback signalized EOF\n", u->fd);
731                 uh_client_shutdown(cl);
732                 return;
733         }
734 }
735
736 #ifdef HAVE_TLS
737 static inline int uh_inittls(struct config *conf)
738 {
739         /* library handle */
740         void *lib;
741
742         /* already loaded */
743         if (conf->tls != NULL)
744                 return 0;
745
746         /* load TLS plugin */
747         if (!(lib = dlopen("uhttpd_tls.so", RTLD_LAZY | RTLD_GLOBAL)))
748         {
749                 fprintf(stderr,
750                                 "Notice: Unable to load TLS plugin - disabling SSL support! "
751                                 "(Reason: %s)\n", dlerror()
752                 );
753
754                 return 1;
755         }
756         else
757         {
758                 /* resolve functions */
759                 if (!(conf->tls_init   = dlsym(lib, "uh_tls_ctx_init"))      ||
760                     !(conf->tls_cert   = dlsym(lib, "uh_tls_ctx_cert"))      ||
761                     !(conf->tls_key    = dlsym(lib, "uh_tls_ctx_key"))       ||
762                     !(conf->tls_free   = dlsym(lib, "uh_tls_ctx_free"))      ||
763                     !(conf->tls_accept = dlsym(lib, "uh_tls_client_accept")) ||
764                     !(conf->tls_close  = dlsym(lib, "uh_tls_client_close"))  ||
765                     !(conf->tls_recv   = dlsym(lib, "uh_tls_client_recv"))   ||
766                     !(conf->tls_send   = dlsym(lib, "uh_tls_client_send")))
767                 {
768                         fprintf(stderr,
769                                         "Error: Failed to lookup required symbols "
770                                         "in TLS plugin: %s\n", dlerror()
771                         );
772                         exit(1);
773                 }
774
775                 /* init SSL context */
776                 if (!(conf->tls = conf->tls_init()))
777                 {
778                         fprintf(stderr, "Error: Failed to initalize SSL context\n");
779                         exit(1);
780                 }
781         }
782
783         return 0;
784 }
785 #endif
786
787 int main (int argc, char **argv)
788 {
789         /* master file descriptor list */
790         fd_set serv_fds;
791
792         /* working structs */
793         struct addrinfo hints;
794         struct sigaction sa;
795         struct config conf;
796
797         /* maximum file descriptor number */
798         int cur_fd, max_fd = 0;
799
800 #ifdef HAVE_TLS
801         int tls = 0;
802         int keys = 0;
803 #endif
804
805         int bound = 0;
806         int nofork = 0;
807
808         /* args */
809         int opt;
810         char bind[128];
811         char *port = NULL;
812
813 #ifdef HAVE_LUA
814         /* library handle */
815         void *lib;
816 #endif
817
818         FD_ZERO(&serv_fds);
819
820         /* handle SIGPIPE, SIGINT, SIGTERM */
821         sa.sa_flags = 0;
822         sigemptyset(&sa.sa_mask);
823
824         sa.sa_handler = SIG_IGN;
825         sigaction(SIGPIPE, &sa, NULL);
826
827         sa.sa_handler = uh_sigterm;
828         sigaction(SIGINT,  &sa, NULL);
829         sigaction(SIGTERM, &sa, NULL);
830
831         /* prepare addrinfo hints */
832         memset(&hints, 0, sizeof(hints));
833         hints.ai_family   = AF_UNSPEC;
834         hints.ai_socktype = SOCK_STREAM;
835         hints.ai_flags    = AI_PASSIVE;
836
837         /* parse args */
838         memset(&conf, 0, sizeof(conf));
839         memset(bind, 0, sizeof(bind));
840
841         uloop_init();
842
843         while ((opt = getopt(argc, argv,
844                                                  "fSDRC:K:E:I:p:s:h:c:l:L:d:r:m:n:x:i:t:T:A:u:U:")) > 0)
845         {
846                 switch(opt)
847                 {
848                         /* [addr:]port */
849                         case 'p':
850                         case 's':
851                                 if ((port = strrchr(optarg, ':')) != NULL)
852                                 {
853                                         if ((optarg[0] == '[') && (port > optarg) && (port[-1] == ']'))
854                                                 memcpy(bind, optarg + 1,
855                                                         min(sizeof(bind), (int)(port - optarg) - 2));
856                                         else
857                                                 memcpy(bind, optarg,
858                                                         min(sizeof(bind), (int)(port - optarg)));
859
860                                         port++;
861                                 }
862                                 else
863                                 {
864                                         port = optarg;
865                                 }
866
867 #ifdef HAVE_TLS
868                                 if (opt == 's')
869                                 {
870                                         if (uh_inittls(&conf))
871                                         {
872                                                 fprintf(stderr,
873                                                         "Notice: TLS support is disabled, "
874                                                         "ignoring '-s %s'\n", optarg
875                                                 );
876                                                 continue;
877                                         }
878
879                                         tls = 1;
880                                 }
881 #endif
882
883                                 /* bind sockets */
884                                 bound += uh_socket_bind(&serv_fds, &max_fd,
885                                                                                 bind[0] ? bind : NULL,
886                                                                                 port, &hints, (opt == 's'), &conf);
887
888                                 memset(bind, 0, sizeof(bind));
889                                 break;
890
891 #ifdef HAVE_TLS
892                         /* certificate */
893                         case 'C':
894                                 if (!uh_inittls(&conf))
895                                 {
896                                         if (conf.tls_cert(conf.tls, optarg) < 1)
897                                         {
898                                                 fprintf(stderr,
899                                                                 "Error: Invalid certificate file given\n");
900                                                 exit(1);
901                                         }
902
903                                         keys++;
904                                 }
905
906                                 break;
907
908                         /* key */
909                         case 'K':
910                                 if (!uh_inittls(&conf))
911                                 {
912                                         if (conf.tls_key(conf.tls, optarg) < 1)
913                                         {
914                                                 fprintf(stderr,
915                                                                 "Error: Invalid private key file given\n");
916                                                 exit(1);
917                                         }
918
919                                         keys++;
920                                 }
921
922                                 break;
923 #endif
924
925                         /* docroot */
926                         case 'h':
927                                 if (! realpath(optarg, conf.docroot))
928                                 {
929                                         fprintf(stderr, "Error: Invalid directory %s: %s\n",
930                                                         optarg, strerror(errno));
931                                         exit(1);
932                                 }
933                                 break;
934
935                         /* error handler */
936                         case 'E':
937                                 if ((strlen(optarg) == 0) || (optarg[0] != '/'))
938                                 {
939                                         fprintf(stderr, "Error: Invalid error handler: %s\n",
940                                                         optarg);
941                                         exit(1);
942                                 }
943                                 conf.error_handler = optarg;
944                                 break;
945
946                         /* index file */
947                         case 'I':
948                                 if ((strlen(optarg) == 0) || (optarg[0] == '/'))
949                                 {
950                                         fprintf(stderr, "Error: Invalid index page: %s\n",
951                                                         optarg);
952                                         exit(1);
953                                 }
954                                 conf.index_file = optarg;
955                                 break;
956
957                         /* don't follow symlinks */
958                         case 'S':
959                                 conf.no_symlinks = 1;
960                                 break;
961
962                         /* don't list directories */
963                         case 'D':
964                                 conf.no_dirlists = 1;
965                                 break;
966
967                         case 'R':
968                                 conf.rfc1918_filter = 1;
969                                 break;
970
971                         case 'n':
972                                 conf.max_requests = atoi(optarg);
973                                 break;
974
975 #ifdef HAVE_CGI
976                         /* cgi prefix */
977                         case 'x':
978                                 conf.cgi_prefix = optarg;
979                                 break;
980
981                         /* interpreter */
982                         case 'i':
983                                 if ((optarg[0] == '.') && (port = strchr(optarg, '=')))
984                                 {
985                                         *port++ = 0;
986                                         uh_interpreter_add(optarg, port);
987                                 }
988                                 else
989                                 {
990                                         fprintf(stderr, "Error: Invalid interpreter: %s\n",
991                                                         optarg);
992                                         exit(1);
993                                 }
994                                 break;
995 #endif
996
997 #ifdef HAVE_LUA
998                         /* lua prefix */
999                         case 'l':
1000                                 conf.lua_prefix = optarg;
1001                                 break;
1002
1003                         /* lua handler */
1004                         case 'L':
1005                                 conf.lua_handler = optarg;
1006                                 break;
1007 #endif
1008
1009 #ifdef HAVE_UBUS
1010                         /* ubus prefix */
1011                         case 'u':
1012                                 conf.ubus_prefix = optarg;
1013                                 break;
1014
1015                         /* ubus socket */
1016                         case 'U':
1017                                 conf.ubus_socket = optarg;
1018                                 break;
1019 #endif
1020
1021 #if defined(HAVE_CGI) || defined(HAVE_LUA)
1022                         /* script timeout */
1023                         case 't':
1024                                 conf.script_timeout = atoi(optarg);
1025                                 break;
1026 #endif
1027
1028                         /* network timeout */
1029                         case 'T':
1030                                 conf.network_timeout = atoi(optarg);
1031                                 break;
1032
1033                         /* tcp keep-alive */
1034                         case 'A':
1035                                 conf.tcp_keepalive = atoi(optarg);
1036                                 break;
1037
1038                         /* no fork */
1039                         case 'f':
1040                                 nofork = 1;
1041                                 break;
1042
1043                         /* urldecode */
1044                         case 'd':
1045                                 if ((port = malloc(strlen(optarg)+1)) != NULL)
1046                                 {
1047                                         /* "decode" plus to space to retain compat */
1048                                         for (opt = 0; optarg[opt]; opt++)
1049                                                 if (optarg[opt] == '+')
1050                                                         optarg[opt] = ' ';
1051                                         /* opt now contains strlen(optarg) -- no need to re-scan */
1052                                         memset(port, 0, opt+1);
1053                                         if (uh_urldecode(port, opt, optarg, opt) < 0)
1054                                             fprintf(stderr, "uhttpd: invalid encoding\n");
1055
1056                                         printf("%s", port);
1057                                         free(port);
1058                                         exit(0);
1059                                 }
1060                                 break;
1061
1062                         /* basic auth realm */
1063                         case 'r':
1064                                 conf.realm = optarg;
1065                                 break;
1066
1067                         /* md5 crypt */
1068                         case 'm':
1069                                 printf("%s\n", crypt(optarg, "$1$"));
1070                                 exit(0);
1071                                 break;
1072
1073                         /* config file */
1074                         case 'c':
1075                                 conf.file = optarg;
1076                                 break;
1077
1078                         default:
1079                                 fprintf(stderr,
1080                                         "Usage: %s -p [addr:]port [-h docroot]\n"
1081                                         "       -f              Do not fork to background\n"
1082                                         "       -c file         Configuration file, default is '/etc/httpd.conf'\n"
1083                                         "       -p [addr:]port  Bind to specified address and port, multiple allowed\n"
1084 #ifdef HAVE_TLS
1085                                         "       -s [addr:]port  Like -p but provide HTTPS on this port\n"
1086                                         "       -C file         ASN.1 server certificate file\n"
1087                                         "       -K file         ASN.1 server private key file\n"
1088 #endif
1089                                         "       -h directory    Specify the document root, default is '.'\n"
1090                                         "       -E string       Use given virtual URL as 404 error handler\n"
1091                                         "       -I string       Use given filename as index page for directories\n"
1092                                         "       -S              Do not follow symbolic links outside of the docroot\n"
1093                                         "       -D              Do not allow directory listings, send 403 instead\n"
1094                                         "       -R              Enable RFC1918 filter\n"
1095                                         "       -n count        Maximum allowed number of concurrent requests\n"
1096 #ifdef HAVE_LUA
1097                                         "       -l string       URL prefix for Lua handler, default is '/lua'\n"
1098                                         "       -L file         Lua handler script, omit to disable Lua\n"
1099 #endif
1100 #ifdef HAVE_UBUS
1101                                         "       -u string       URL prefix for HTTP/JSON handler, default is '/ubus'\n"
1102                                         "       -U file         Override ubus socket path\n"
1103 #endif
1104 #ifdef HAVE_CGI
1105                                         "       -x string       URL prefix for CGI handler, default is '/cgi-bin'\n"
1106                                         "       -i .ext=path    Use interpreter at path for files with the given extension\n"
1107 #endif
1108 #if defined(HAVE_CGI) || defined(HAVE_LUA) || defined(HAVE_UBUS)
1109                                         "       -t seconds      CGI, Lua and UBUS script timeout in seconds, default is 60\n"
1110 #endif
1111                                         "       -T seconds      Network timeout in seconds, default is 30\n"
1112                                         "       -d string       URL decode given string\n"
1113                                         "       -r string       Specify basic auth realm\n"
1114                                         "       -m string       MD5 crypt given string\n"
1115                                         "\n", argv[0]
1116                                 );
1117
1118                                 exit(1);
1119                 }
1120         }
1121
1122 #ifdef HAVE_TLS
1123         if ((tls == 1) && (keys < 2))
1124         {
1125                 fprintf(stderr, "Error: Missing private key or certificate file\n");
1126                 exit(1);
1127         }
1128 #endif
1129
1130         if (bound < 1)
1131         {
1132                 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
1133                 exit(1);
1134         }
1135
1136         /* default docroot */
1137         if (!conf.docroot[0] && !realpath(".", conf.docroot))
1138         {
1139                 fprintf(stderr, "Error: Can not determine default document root: %s\n",
1140                         strerror(errno));
1141                 exit(1);
1142         }
1143
1144         /* default realm */
1145         if (!conf.realm)
1146                 conf.realm = "Protected Area";
1147
1148         /* config file */
1149         uh_config_parse(&conf);
1150
1151         /* default max requests */
1152         if (conf.max_requests <= 0)
1153                 conf.max_requests = 3;
1154
1155         /* default network timeout */
1156         if (conf.network_timeout <= 0)
1157                 conf.network_timeout = 30;
1158
1159 #if defined(HAVE_CGI) || defined(HAVE_LUA) || defined(HAVE_UBUS)
1160         /* default script timeout */
1161         if (conf.script_timeout <= 0)
1162                 conf.script_timeout = 60;
1163 #endif
1164
1165 #ifdef HAVE_CGI
1166         /* default cgi prefix */
1167         if (!conf.cgi_prefix)
1168                 conf.cgi_prefix = "/cgi-bin";
1169 #endif
1170
1171 #ifdef HAVE_LUA
1172         /* load Lua plugin */
1173         if (!(lib = dlopen("uhttpd_lua.so", RTLD_LAZY | RTLD_GLOBAL)))
1174         {
1175                 fprintf(stderr,
1176                                 "Notice: Unable to load Lua plugin - disabling Lua support! "
1177                                 "(Reason: %s)\n", dlerror());
1178         }
1179         else
1180         {
1181                 /* resolve functions */
1182                 if (!(conf.lua_init    = dlsym(lib, "uh_lua_init"))    ||
1183                     !(conf.lua_close   = dlsym(lib, "uh_lua_close"))   ||
1184                     !(conf.lua_request = dlsym(lib, "uh_lua_request")))
1185                 {
1186                         fprintf(stderr,
1187                                         "Error: Failed to lookup required symbols "
1188                                         "in Lua plugin: %s\n", dlerror()
1189                         );
1190                         exit(1);
1191                 }
1192
1193                 /* init Lua runtime if handler is specified */
1194                 if (conf.lua_handler)
1195                 {
1196                         /* default lua prefix */
1197                         if (!conf.lua_prefix)
1198                                 conf.lua_prefix = "/lua";
1199
1200                         conf.lua_state = conf.lua_init(&conf);
1201                 }
1202         }
1203 #endif
1204
1205 #ifdef HAVE_UBUS
1206         /* load ubus plugin */
1207         if (!(lib = dlopen("uhttpd_ubus.so", RTLD_LAZY | RTLD_GLOBAL)))
1208         {
1209                 fprintf(stderr,
1210                                 "Notice: Unable to load ubus plugin - disabling ubus support! "
1211                                 "(Reason: %s)\n", dlerror());
1212         }
1213         else
1214         {
1215                 /* resolve functions */
1216                 if (!(conf.ubus_init    = dlsym(lib, "uh_ubus_init"))    ||
1217                     !(conf.ubus_close   = dlsym(lib, "uh_ubus_close"))   ||
1218                     !(conf.ubus_request = dlsym(lib, "uh_ubus_request")))
1219                 {
1220                         fprintf(stderr,
1221                                         "Error: Failed to lookup required symbols "
1222                                         "in ubus plugin: %s\n", dlerror()
1223                         );
1224                         exit(1);
1225                 }
1226
1227                 /* default ubus prefix */
1228                 if (!conf.ubus_prefix)
1229                         conf.ubus_prefix = "/ubus";
1230
1231                 conf.ubus_state = conf.ubus_init(&conf);
1232         }
1233 #endif
1234
1235         /* fork (if not disabled) */
1236         if (!nofork)
1237         {
1238                 switch (fork())
1239                 {
1240                         case -1:
1241                                 perror("fork()");
1242                                 exit(1);
1243
1244                         case 0:
1245                                 /* daemon setup */
1246                                 if (chdir("/"))
1247                                         perror("chdir()");
1248
1249                                 if ((cur_fd = open("/dev/null", O_WRONLY)) > -1)
1250                                         dup2(cur_fd, 0);
1251
1252                                 if ((cur_fd = open("/dev/null", O_RDONLY)) > -1)
1253                                         dup2(cur_fd, 1);
1254
1255                                 if ((cur_fd = open("/dev/null", O_RDONLY)) > -1)
1256                                         dup2(cur_fd, 2);
1257
1258                                 break;
1259
1260                         default:
1261                                 exit(0);
1262                 }
1263         }
1264
1265         /* server main loop */
1266         uloop_run();
1267
1268 #ifdef HAVE_LUA
1269         /* destroy the Lua state */
1270         if (conf.lua_state != NULL)
1271                 conf.lua_close(conf.lua_state);
1272 #endif
1273
1274 #ifdef HAVE_UBUS
1275         /* destroy the ubus state */
1276         if (conf.ubus_state != NULL)
1277                 conf.ubus_close(conf.ubus_state);
1278 #endif
1279
1280         return 0;
1281 }