2 * uhttpd - Tiny single-threaded httpd - Main component
4 * Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #define _XOPEN_SOURCE 500 /* crypt() */
22 #include "uhttpd-utils.h"
23 #include "uhttpd-file.h"
26 #include "uhttpd-cgi.h"
30 #include "uhttpd-lua.h"
34 #include "uhttpd-tls.h"
40 static void uh_sigterm(int sig
)
45 static void uh_sigchld(int sig
)
47 while( waitpid(-1, NULL
, WNOHANG
) > 0 ) { }
50 static void uh_config_parse(const char *path
)
58 if( (c
= fopen(path
? path
: "/etc/httpd.conf", "r")) != NULL
)
60 memset(line
, 0, sizeof(line
));
62 while( fgets(line
, sizeof(line
) - 1, c
) )
64 if( (line
[0] == '/') && (strchr(line
, ':') != NULL
) )
66 if( !(user
= strchr(line
, ':')) || (*user
++ = 0) ||
67 !(pass
= strchr(user
, ':')) || (*pass
++ = 0) ||
68 !(eol
= strchr(pass
, '\n')) || (*eol
++ = 0) )
71 if( !uh_auth_add(line
, user
, pass
) )
74 "Notice: No password set for user %s, ignoring "
75 "authentication on %s\n", user
, line
87 static int uh_socket_bind(
88 fd_set
*serv_fds
, int *max_fd
, const char *host
, const char *port
,
89 struct addrinfo
*hints
, int do_tls
, struct config
*conf
96 struct listener
*l
= NULL
;
97 struct addrinfo
*addrs
= NULL
, *p
= NULL
;
99 if( (status
= getaddrinfo(host
, port
, hints
, &addrs
)) != 0 )
101 fprintf(stderr
, "getaddrinfo(): %s\n", gai_strerror(status
));
104 /* try to bind a new socket to each found address */
105 for( p
= addrs
; p
; p
= p
->ai_next
)
108 if( (sock
= socket(p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1 )
114 /* "address already in use" */
115 if( setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(yes
)) == -1 )
117 perror("setsockopt()");
121 /* required to get parallel v4 + v6 working */
122 if( p
->ai_family
== AF_INET6
)
124 if( setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &yes
, sizeof(yes
)) == -1 )
126 perror("setsockopt()");
132 if( bind(sock
, p
->ai_addr
, p
->ai_addrlen
) == -1 )
139 if( listen(sock
, UH_LIMIT_CLIENTS
) == -1 )
145 /* add listener to global list */
146 if( ! (l
= uh_listener_add(sock
, conf
)) )
149 "uh_listener_add(): Can not create more than "
150 "%i listen sockets\n", UH_LIMIT_LISTENERS
158 l
->tls
= do_tls
? conf
->tls
: NULL
;
161 /* add socket to server fd set */
162 FD_SET(sock
, serv_fds
);
164 *max_fd
= max(*max_fd
, sock
);
179 static struct http_request
* uh_http_header_parse(struct client
*cl
, char *buffer
, int buflen
)
181 char *method
= &buffer
[0];
183 char *version
= NULL
;
185 char *headers
= NULL
;
186 char *hdrname
= NULL
;
187 char *hdrdata
= NULL
;
192 static struct http_request req
;
194 memset(&req
, 0, sizeof(req
));
197 /* terminate initial header line */
198 if( (headers
= strfind(buffer
, buflen
, "\r\n", 2)) != NULL
)
200 buffer
[buflen
-1] = 0;
205 /* find request path */
206 if( (path
= strchr(buffer
, ' ')) != NULL
)
209 /* find http version */
210 if( (path
!= NULL
) && ((version
= strchr(path
, ' ')) != NULL
) )
215 if( strcmp(method
, "GET") && strcmp(method
, "HEAD") && strcmp(method
, "POST") )
218 uh_http_response(cl
, 405, "Method Not Allowed");
226 req
.method
= UH_HTTP_MSG_GET
;
230 req
.method
= UH_HTTP_MSG_HEAD
;
234 req
.method
= UH_HTTP_MSG_POST
;
240 if( !path
|| !strlen(path
) )
242 /* malformed request */
243 uh_http_response(cl
, 400, "Bad Request");
252 if( strcmp(version
, "HTTP/0.9") && strcmp(version
, "HTTP/1.0") && strcmp(version
, "HTTP/1.1") )
254 /* unsupported version */
255 uh_http_response(cl
, 400, "Bad Request");
260 req
.version
= strtof(&version
[5], NULL
);
264 /* process header fields */
265 for( i
= (int)(headers
- buffer
); i
< buflen
; i
++ )
267 /* found eol and have name + value, push out header tuple */
268 if( hdrname
&& hdrdata
&& (buffer
[i
] == '\r' || buffer
[i
] == '\n') )
273 if( (hdrcount
+ 1) < array_size(req
.headers
) )
275 req
.headers
[hdrcount
++] = hdrname
;
276 req
.headers
[hdrcount
++] = hdrdata
;
278 hdrname
= hdrdata
= NULL
;
284 uh_http_response(cl
, 413, "Request Entity Too Large");
289 /* have name but no value and found a colon, start of value */
290 else if( hdrname
&& !hdrdata
&& ((i
+2) < buflen
) &&
291 (buffer
[i
] == ':') && (buffer
[i
+1] == ' ')
294 hdrdata
= &buffer
[i
+2];
297 /* have no name and found [A-Z], start of name */
298 else if( !hdrname
&& isalpha(buffer
[i
]) && isupper(buffer
[i
]) )
300 hdrname
= &buffer
[i
];
308 /* Malformed request */
309 uh_http_response(cl
, 400, "Bad Request");
314 static struct http_request
* uh_http_header_recv(struct client
*cl
)
316 static char buffer
[UH_LIMIT_MSGHEAD
];
317 char *bufptr
= &buffer
[0];
320 struct timeval timeout
;
324 ssize_t blen
= sizeof(buffer
)-1;
328 memset(buffer
, 0, sizeof(buffer
));
333 FD_SET(cl
->socket
, &reader
);
335 /* fail after 0.1s */
337 timeout
.tv_usec
= 100000;
339 /* check whether fd is readable */
340 if( select(cl
->socket
+ 1, &reader
, NULL
, NULL
, &timeout
) > 0 )
343 rlen
= uh_tcp_peek(cl
, bufptr
, blen
);
347 if( (idxptr
= strfind(buffer
, sizeof(buffer
), "\r\n\r\n", 4)) )
349 blen
-= uh_tcp_recv(cl
, bufptr
, (int)(idxptr
- bufptr
) + 4);
351 /* header read complete ... */
352 return uh_http_header_parse(cl
, buffer
, sizeof(buffer
) - blen
- 1);
356 rlen
= uh_tcp_recv(cl
, bufptr
, rlen
);
363 /* invalid request (unexpected eof/timeout) */
364 uh_http_response(cl
, 408, "Request Timeout");
370 /* invalid request (unexpected eof/timeout) */
371 uh_http_response(cl
, 408, "Request Timeout");
376 /* request entity too large */
377 uh_http_response(cl
, 413, "Request Entity Too Large");
381 static int uh_path_match(const char *prefix
, const char *url
)
383 if( (strstr(url
, prefix
) == url
) &&
384 ((prefix
[strlen(prefix
)-1] == '/') ||
385 (strlen(url
) == strlen(prefix
)) ||
386 (url
[strlen(prefix
)] == '/'))
395 int main (int argc
, char **argv
)
402 /* master file descriptor list */
403 fd_set used_fds
, serv_fds
, read_fds
;
405 /* working structs */
406 struct addrinfo hints
;
407 struct http_request
*req
;
408 struct path_info
*pin
;
416 /* maximum file descriptor number */
417 int new_fd
, cur_fd
, max_fd
= 0;
432 #if defined(HAVE_TLS) || defined(HAVE_LUA)
437 /* clear the master and temp sets */
442 /* handle SIGPIPE, SIGINT, SIGTERM, SIGCHLD */
444 sigemptyset(&sa
.sa_mask
);
446 sa
.sa_handler
= SIG_IGN
;
447 sigaction(SIGPIPE
, &sa
, NULL
);
449 sa
.sa_handler
= uh_sigchld
;
450 sigaction(SIGCHLD
, &sa
, NULL
);
452 sa
.sa_handler
= uh_sigterm
;
453 sigaction(SIGINT
, &sa
, NULL
);
454 sigaction(SIGTERM
, &sa
, NULL
);
458 sigaddset(&ss
, SIGCHLD
);
459 sigprocmask(SIG_BLOCK
, &ss
, NULL
);
461 /* prepare addrinfo hints */
462 memset(&hints
, 0, sizeof(hints
));
463 hints
.ai_family
= AF_UNSPEC
;
464 hints
.ai_socktype
= SOCK_STREAM
;
465 hints
.ai_flags
= AI_PASSIVE
;
468 memset(&conf
, 0, sizeof(conf
));
469 memset(bind
, 0, sizeof(bind
));
472 /* load TLS plugin */
473 if( ! (lib
= dlopen("uhttpd_tls.so", RTLD_LAZY
| RTLD_GLOBAL
)) )
476 "Notice: Unable to load TLS plugin - disabling SSL support! "
477 "(Reason: %s)\n", dlerror()
482 /* resolve functions */
483 if( !(conf
.tls_init
= dlsym(lib
, "uh_tls_ctx_init")) ||
484 !(conf
.tls_cert
= dlsym(lib
, "uh_tls_ctx_cert")) ||
485 !(conf
.tls_key
= dlsym(lib
, "uh_tls_ctx_key")) ||
486 !(conf
.tls_free
= dlsym(lib
, "uh_tls_ctx_free")) ||
487 !(conf
.tls_accept
= dlsym(lib
, "uh_tls_client_accept")) ||
488 !(conf
.tls_close
= dlsym(lib
, "uh_tls_client_close")) ||
489 !(conf
.tls_recv
= dlsym(lib
, "uh_tls_client_recv")) ||
490 !(conf
.tls_send
= dlsym(lib
, "uh_tls_client_send"))
493 "Error: Failed to lookup required symbols "
494 "in TLS plugin: %s\n", dlerror()
499 /* init SSL context */
500 if( ! (conf
.tls
= conf
.tls_init()) )
502 fprintf(stderr
, "Error: Failed to initalize SSL context\n");
508 while( (opt
= getopt(argc
, argv
, "fSC:K:p:s:h:c:l:L:d:r:m:x:t:T:")) > 0 )
515 if( (port
= strrchr(optarg
, ':')) != NULL
)
517 if( (optarg
[0] == '[') && (port
> optarg
) && (port
[-1] == ']') )
518 memcpy(bind
, optarg
+ 1,
519 min(sizeof(bind
), (int)(port
- optarg
) - 2));
522 min(sizeof(bind
), (int)(port
- optarg
)));
537 "Notice: TLS support is disabled, "
538 "ignoring '-s %s'\n", optarg
548 bound
+= uh_socket_bind(
549 &serv_fds
, &max_fd
, bind
[0] ? bind
: NULL
, port
,
550 &hints
, (opt
== 's'), &conf
553 memset(bind
, 0, sizeof(bind
));
561 if( conf
.tls_cert(conf
.tls
, optarg
) < 1 )
564 "Error: Invalid certificate file given\n");
577 if( conf
.tls_key(conf
.tls
, optarg
) < 1 )
580 "Error: Invalid private key file given\n");
592 if( ! realpath(optarg
, conf
.docroot
) )
594 fprintf(stderr
, "Error: Invalid directory %s: %s\n",
595 optarg
, strerror(errno
));
600 /* don't follow symlinks */
602 conf
.no_symlinks
= 1;
608 conf
.cgi_prefix
= optarg
;
615 conf
.lua_prefix
= optarg
;
620 conf
.lua_handler
= optarg
;
624 #if defined(HAVE_CGI) || defined(HAVE_LUA)
627 conf
.script_timeout
= atoi(optarg
);
631 /* network timeout */
633 conf
.network_timeout
= atoi(optarg
);
643 if( (port
= malloc(strlen(optarg
)+1)) != NULL
)
645 memset(port
, 0, strlen(optarg
)+1);
646 uh_urldecode(port
, strlen(optarg
), optarg
, strlen(optarg
));
653 /* basic auth realm */
660 printf("%s\n", crypt(optarg
, "$1$"));
671 "Usage: %s -p [addr:]port [-h docroot]\n"
672 " -f Do not fork to background\n"
673 " -c file Configuration file, default is '/etc/httpd.conf'\n"
674 " -p [addr:]port Bind to specified address and port, multiple allowed\n"
676 " -s [addr:]port Like -p but provide HTTPS on this port\n"
677 " -C file ASN.1 server certificate file\n"
678 " -K file ASN.1 server private key file\n"
680 " -h directory Specify the document root, default is '.'\n"
681 " -S Do not follow symbolic links outside of the docroot\n"
683 " -l string URL prefix for Lua handler, default is '/lua'\n"
684 " -L file Lua handler script, omit to disable Lua\n"
687 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
689 #if defined(HAVE_CGI) || defined(HAVE_LUA)
690 " -t seconds CGI and Lua script timeout in seconds, default is 60\n"
692 " -T seconds Network timeout in seconds, default is 30\n"
693 " -d string URL decode given string\n"
694 " -r string Specify basic auth realm\n"
695 " -m string MD5 crypt given string\n"
704 if( (tls
== 1) && (keys
< 2) )
706 fprintf(stderr
, "Error: Missing private key or certificate file\n");
713 fprintf(stderr
, "Error: No sockets bound, unable to continue\n");
717 /* default docroot */
718 if( !conf
.docroot
[0] && !realpath(".", conf
.docroot
) )
720 fprintf(stderr
, "Error: Can not determine default document root: %s\n",
727 conf
.realm
= "Protected Area";
730 uh_config_parse(conf
.file
);
732 /* default network timeout */
733 if( conf
.network_timeout
<= 0 )
734 conf
.network_timeout
= 30;
736 #if defined(HAVE_CGI) || defined(HAVE_LUA)
737 /* default script timeout */
738 if( conf
.script_timeout
<= 0 )
739 conf
.script_timeout
= 60;
743 /* default cgi prefix */
744 if( ! conf
.cgi_prefix
)
745 conf
.cgi_prefix
= "/cgi-bin";
749 /* load Lua plugin */
750 if( ! (lib
= dlopen("uhttpd_lua.so", RTLD_LAZY
| RTLD_GLOBAL
)) )
753 "Notice: Unable to load Lua plugin - disabling Lua support! "
754 "(Reason: %s)\n", dlerror()
759 /* resolve functions */
760 if( !(conf
.lua_init
= dlsym(lib
, "uh_lua_init")) ||
761 !(conf
.lua_close
= dlsym(lib
, "uh_lua_close")) ||
762 !(conf
.lua_request
= dlsym(lib
, "uh_lua_request"))
765 "Error: Failed to lookup required symbols "
766 "in Lua plugin: %s\n", dlerror()
771 /* init Lua runtime if handler is specified */
772 if( conf
.lua_handler
)
774 /* default lua prefix */
775 if( ! conf
.lua_prefix
)
776 conf
.lua_prefix
= "/lua";
778 L
= conf
.lua_init(conf
.lua_handler
);
783 /* fork (if not disabled) */
797 if( (cur_fd
= open("/dev/null", O_WRONLY
)) > -1 )
800 if( (cur_fd
= open("/dev/null", O_RDONLY
)) > -1 )
803 if( (cur_fd
= open("/dev/null", O_RDONLY
)) > -1 )
813 /* backup server descriptor set */
819 /* create a working copy of the used fd set */
822 /* sleep until socket activity */
823 if( select(max_fd
+ 1, &read_fds
, NULL
, NULL
, NULL
) == -1 )
829 /* run through the existing connections looking for data to be read */
830 for( cur_fd
= 0; cur_fd
<= max_fd
; cur_fd
++ )
832 /* is a socket managed by us */
833 if( FD_ISSET(cur_fd
, &read_fds
) )
835 /* is one of our listen sockets */
836 if( FD_ISSET(cur_fd
, &serv_fds
) )
838 /* handle new connections */
839 if( (new_fd
= accept(cur_fd
, NULL
, 0)) != -1 )
841 /* add to global client list */
842 if( (cl
= uh_client_add(new_fd
, uh_listener_lookup(cur_fd
))) != NULL
)
845 /* setup client tls context */
850 /* add client socket to global fdset */
851 FD_SET(new_fd
, &used_fds
);
853 max_fd
= max(max_fd
, new_fd
);
856 /* insufficient resources */
860 "uh_client_add(): Can not manage more than "
861 "%i client sockets, connection dropped\n",
870 /* is a client socket */
873 if( ! (cl
= uh_client_lookup(cur_fd
)) )
875 /* this should not happen! */
877 "uh_client_lookup(): No entry for fd %i!\n",
883 /* parse message header */
884 if( (req
= uh_http_header_recv(cl
)) != NULL
)
888 if( L
&& uh_path_match(conf
.lua_prefix
, req
->url
) )
890 conf
.lua_request(cl
, req
, L
);
894 /* dispatch request */
895 if( (pin
= uh_path_lookup(cl
, req
->url
)) != NULL
)
898 if( uh_auth_check(cl
, req
, pin
) )
901 if( uh_path_match(conf
.cgi_prefix
, pin
->name
) )
903 uh_cgi_request(cl
, req
, pin
);
908 uh_file_request(cl
, req
, pin
);
916 uh_http_sendhf(cl
, 404, "Not Found",
917 "No such file or directory");
924 uh_http_sendhf(cl
, 400, "Bad Request",
925 "Malformed request received");
929 /* free client tls context */
936 /* close client socket */
938 FD_CLR(cur_fd
, &used_fds
);
940 /* remove from global client list */
941 uh_client_remove(cur_fd
);
948 /* destroy the Lua state */
This page took 0.110524 seconds and 5 git commands to generate.