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