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(struct config
*conf
)
58 const char *path
= conf
->file
? conf
->file
: "/etc/httpd.conf";
61 if( (c
= fopen(path
, "r")) != NULL
)
63 memset(line
, 0, sizeof(line
));
65 while( fgets(line
, sizeof(line
) - 1, c
) )
67 if( (line
[0] == '/') && (strchr(line
, ':') != NULL
) )
69 if( !(user
= strchr(line
, ':')) || (*user
++ = 0) ||
70 !(pass
= strchr(user
, ':')) || (*pass
++ = 0) ||
71 !(eol
= strchr(pass
, '\n')) || (*eol
++ = 0) )
74 if( !uh_auth_add(line
, user
, pass
) )
77 "Notice: No password set for user %s, ignoring "
78 "authentication on %s\n", user
, line
82 else if( !strncmp(line
, "I:", 2) )
84 if( !(user
= strchr(line
, ':')) || (*user
++ = 0) ||
85 !(eol
= strchr(user
, '\n')) || (*eol
++ = 0) )
88 conf
->index_file
= strdup(user
);
90 else if( !strncmp(line
, "E404:", 5) )
92 if( !(user
= strchr(line
, ':')) || (*user
++ = 0) ||
93 !(eol
= strchr(user
, '\n')) || (*eol
++ = 0) )
96 conf
->error_handler
= strdup(user
);
104 static int uh_socket_bind(
105 fd_set
*serv_fds
, int *max_fd
, const char *host
, const char *port
,
106 struct addrinfo
*hints
, int do_tls
, struct config
*conf
113 struct listener
*l
= NULL
;
114 struct addrinfo
*addrs
= NULL
, *p
= NULL
;
116 if( (status
= getaddrinfo(host
, port
, hints
, &addrs
)) != 0 )
118 fprintf(stderr
, "getaddrinfo(): %s\n", gai_strerror(status
));
121 /* try to bind a new socket to each found address */
122 for( p
= addrs
; p
; p
= p
->ai_next
)
125 if( (sock
= socket(p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1 )
131 /* "address already in use" */
132 if( setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(yes
)) == -1 )
134 perror("setsockopt()");
138 /* required to get parallel v4 + v6 working */
139 if( p
->ai_family
== AF_INET6
)
141 if( setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &yes
, sizeof(yes
)) == -1 )
143 perror("setsockopt()");
149 if( bind(sock
, p
->ai_addr
, p
->ai_addrlen
) == -1 )
156 if( listen(sock
, UH_LIMIT_CLIENTS
) == -1 )
162 /* add listener to global list */
163 if( ! (l
= uh_listener_add(sock
, conf
)) )
166 "uh_listener_add(): Can not create more than "
167 "%i listen sockets\n", UH_LIMIT_LISTENERS
175 l
->tls
= do_tls
? conf
->tls
: NULL
;
178 /* add socket to server fd set */
179 FD_SET(sock
, serv_fds
);
181 *max_fd
= max(*max_fd
, sock
);
196 static struct http_request
* uh_http_header_parse(struct client
*cl
, char *buffer
, int buflen
)
198 char *method
= &buffer
[0];
200 char *version
= NULL
;
202 char *headers
= NULL
;
203 char *hdrname
= NULL
;
204 char *hdrdata
= NULL
;
209 static struct http_request req
;
211 memset(&req
, 0, sizeof(req
));
214 /* terminate initial header line */
215 if( (headers
= strfind(buffer
, buflen
, "\r\n", 2)) != NULL
)
217 buffer
[buflen
-1] = 0;
222 /* find request path */
223 if( (path
= strchr(buffer
, ' ')) != NULL
)
226 /* find http version */
227 if( (path
!= NULL
) && ((version
= strchr(path
, ' ')) != NULL
) )
232 if( strcmp(method
, "GET") && strcmp(method
, "HEAD") && strcmp(method
, "POST") )
235 uh_http_response(cl
, 405, "Method Not Allowed");
243 req
.method
= UH_HTTP_MSG_GET
;
247 req
.method
= UH_HTTP_MSG_HEAD
;
251 req
.method
= UH_HTTP_MSG_POST
;
257 if( !path
|| !strlen(path
) )
259 /* malformed request */
260 uh_http_response(cl
, 400, "Bad Request");
269 if( strcmp(version
, "HTTP/0.9") && strcmp(version
, "HTTP/1.0") && strcmp(version
, "HTTP/1.1") )
271 /* unsupported version */
272 uh_http_response(cl
, 400, "Bad Request");
277 req
.version
= strtof(&version
[5], NULL
);
281 /* process header fields */
282 for( i
= (int)(headers
- buffer
); i
< buflen
; i
++ )
284 /* found eol and have name + value, push out header tuple */
285 if( hdrname
&& hdrdata
&& (buffer
[i
] == '\r' || buffer
[i
] == '\n') )
290 if( (hdrcount
+ 1) < array_size(req
.headers
) )
292 req
.headers
[hdrcount
++] = hdrname
;
293 req
.headers
[hdrcount
++] = hdrdata
;
295 hdrname
= hdrdata
= NULL
;
301 uh_http_response(cl
, 413, "Request Entity Too Large");
306 /* have name but no value and found a colon, start of value */
307 else if( hdrname
&& !hdrdata
&& ((i
+2) < buflen
) &&
308 (buffer
[i
] == ':') && (buffer
[i
+1] == ' ')
311 hdrdata
= &buffer
[i
+2];
314 /* have no name and found [A-Z], start of name */
315 else if( !hdrname
&& isalpha(buffer
[i
]) && isupper(buffer
[i
]) )
317 hdrname
= &buffer
[i
];
322 req
.redirect_status
= 200;
326 /* Malformed request */
327 uh_http_response(cl
, 400, "Bad Request");
332 static struct http_request
* uh_http_header_recv(struct client
*cl
)
334 static char buffer
[UH_LIMIT_MSGHEAD
];
335 char *bufptr
= &buffer
[0];
338 struct timeval timeout
;
342 ssize_t blen
= sizeof(buffer
)-1;
346 memset(buffer
, 0, sizeof(buffer
));
351 FD_SET(cl
->socket
, &reader
);
353 /* fail after 0.1s */
355 timeout
.tv_usec
= 100000;
357 /* check whether fd is readable */
358 if( select(cl
->socket
+ 1, &reader
, NULL
, NULL
, &timeout
) > 0 )
361 rlen
= uh_tcp_peek(cl
, bufptr
, blen
);
365 if( (idxptr
= strfind(buffer
, sizeof(buffer
), "\r\n\r\n", 4)) )
367 blen
-= uh_tcp_recv(cl
, bufptr
, (int)(idxptr
- bufptr
) + 4);
369 /* header read complete ... */
370 return uh_http_header_parse(cl
, buffer
, sizeof(buffer
) - blen
- 1);
374 rlen
= uh_tcp_recv(cl
, bufptr
, rlen
);
381 /* invalid request (unexpected eof/timeout) */
382 uh_http_response(cl
, 408, "Request Timeout");
388 /* invalid request (unexpected eof/timeout) */
389 uh_http_response(cl
, 408, "Request Timeout");
394 /* request entity too large */
395 uh_http_response(cl
, 413, "Request Entity Too Large");
399 static int uh_path_match(const char *prefix
, const char *url
)
401 if( (strstr(url
, prefix
) == url
) &&
402 ((prefix
[strlen(prefix
)-1] == '/') ||
403 (strlen(url
) == strlen(prefix
)) ||
404 (url
[strlen(prefix
)] == '/'))
413 int main (int argc
, char **argv
)
420 /* master file descriptor list */
421 fd_set used_fds
, serv_fds
, read_fds
;
423 /* working structs */
424 struct addrinfo hints
;
425 struct http_request
*req
;
426 struct path_info
*pin
;
434 /* maximum file descriptor number */
435 int new_fd
, cur_fd
, max_fd
= 0;
450 #if defined(HAVE_TLS) || defined(HAVE_LUA)
455 /* clear the master and temp sets */
460 /* handle SIGPIPE, SIGINT, SIGTERM, SIGCHLD */
462 sigemptyset(&sa
.sa_mask
);
464 sa
.sa_handler
= SIG_IGN
;
465 sigaction(SIGPIPE
, &sa
, NULL
);
467 sa
.sa_handler
= uh_sigchld
;
468 sigaction(SIGCHLD
, &sa
, NULL
);
470 sa
.sa_handler
= uh_sigterm
;
471 sigaction(SIGINT
, &sa
, NULL
);
472 sigaction(SIGTERM
, &sa
, NULL
);
476 sigaddset(&ss
, SIGCHLD
);
477 sigprocmask(SIG_BLOCK
, &ss
, NULL
);
479 /* prepare addrinfo hints */
480 memset(&hints
, 0, sizeof(hints
));
481 hints
.ai_family
= AF_UNSPEC
;
482 hints
.ai_socktype
= SOCK_STREAM
;
483 hints
.ai_flags
= AI_PASSIVE
;
486 memset(&conf
, 0, sizeof(conf
));
487 memset(bind
, 0, sizeof(bind
));
490 /* load TLS plugin */
491 if( ! (lib
= dlopen("uhttpd_tls.so", RTLD_LAZY
| RTLD_GLOBAL
)) )
494 "Notice: Unable to load TLS plugin - disabling SSL support! "
495 "(Reason: %s)\n", dlerror()
500 /* resolve functions */
501 if( !(conf
.tls_init
= dlsym(lib
, "uh_tls_ctx_init")) ||
502 !(conf
.tls_cert
= dlsym(lib
, "uh_tls_ctx_cert")) ||
503 !(conf
.tls_key
= dlsym(lib
, "uh_tls_ctx_key")) ||
504 !(conf
.tls_free
= dlsym(lib
, "uh_tls_ctx_free")) ||
505 !(conf
.tls_accept
= dlsym(lib
, "uh_tls_client_accept")) ||
506 !(conf
.tls_close
= dlsym(lib
, "uh_tls_client_close")) ||
507 !(conf
.tls_recv
= dlsym(lib
, "uh_tls_client_recv")) ||
508 !(conf
.tls_send
= dlsym(lib
, "uh_tls_client_send"))
511 "Error: Failed to lookup required symbols "
512 "in TLS plugin: %s\n", dlerror()
517 /* init SSL context */
518 if( ! (conf
.tls
= conf
.tls_init()) )
520 fprintf(stderr
, "Error: Failed to initalize SSL context\n");
526 while( (opt
= getopt(argc
, argv
,
527 "fSDC:K:E:I:p:s:h:c:l:L:d:r:m:x:t:T:")) > 0
534 if( (port
= strrchr(optarg
, ':')) != NULL
)
536 if( (optarg
[0] == '[') && (port
> optarg
) && (port
[-1] == ']') )
537 memcpy(bind
, optarg
+ 1,
538 min(sizeof(bind
), (int)(port
- optarg
) - 2));
541 min(sizeof(bind
), (int)(port
- optarg
)));
556 "Notice: TLS support is disabled, "
557 "ignoring '-s %s'\n", optarg
567 bound
+= uh_socket_bind(
568 &serv_fds
, &max_fd
, bind
[0] ? bind
: NULL
, port
,
569 &hints
, (opt
== 's'), &conf
572 memset(bind
, 0, sizeof(bind
));
580 if( conf
.tls_cert(conf
.tls
, optarg
) < 1 )
583 "Error: Invalid certificate file given\n");
596 if( conf
.tls_key(conf
.tls
, optarg
) < 1 )
599 "Error: Invalid private key file given\n");
611 if( ! realpath(optarg
, conf
.docroot
) )
613 fprintf(stderr
, "Error: Invalid directory %s: %s\n",
614 optarg
, strerror(errno
));
621 if( (strlen(optarg
) == 0) || (optarg
[0] != '/') )
623 fprintf(stderr
, "Error: Invalid error handler: %s\n",
627 conf
.error_handler
= optarg
;
632 if( (strlen(optarg
) == 0) || (optarg
[0] == '/') )
634 fprintf(stderr
, "Error: Invalid index page: %s\n",
638 conf
.index_file
= optarg
;
641 /* don't follow symlinks */
643 conf
.no_symlinks
= 1;
646 /* don't list directories */
648 conf
.no_dirlists
= 1;
654 conf
.cgi_prefix
= optarg
;
661 conf
.lua_prefix
= optarg
;
666 conf
.lua_handler
= optarg
;
670 #if defined(HAVE_CGI) || defined(HAVE_LUA)
673 conf
.script_timeout
= atoi(optarg
);
677 /* network timeout */
679 conf
.network_timeout
= atoi(optarg
);
689 if( (port
= malloc(strlen(optarg
)+1)) != NULL
)
691 memset(port
, 0, strlen(optarg
)+1);
692 uh_urldecode(port
, strlen(optarg
), optarg
, strlen(optarg
));
699 /* basic auth realm */
706 printf("%s\n", crypt(optarg
, "$1$"));
717 "Usage: %s -p [addr:]port [-h docroot]\n"
718 " -f Do not fork to background\n"
719 " -c file Configuration file, default is '/etc/httpd.conf'\n"
720 " -p [addr:]port Bind to specified address and port, multiple allowed\n"
722 " -s [addr:]port Like -p but provide HTTPS on this port\n"
723 " -C file ASN.1 server certificate file\n"
724 " -K file ASN.1 server private key file\n"
726 " -h directory Specify the document root, default is '.'\n"
727 " -E string Use given virtual URL as 404 error handler\n"
728 " -I string Use given filename as index page for directories\n"
729 " -S Do not follow symbolic links outside of the docroot\n"
730 " -D Do not allow directory listings, send 403 instead\n"
732 " -l string URL prefix for Lua handler, default is '/lua'\n"
733 " -L file Lua handler script, omit to disable Lua\n"
736 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
738 #if defined(HAVE_CGI) || defined(HAVE_LUA)
739 " -t seconds CGI and Lua script timeout in seconds, default is 60\n"
741 " -T seconds Network timeout in seconds, default is 30\n"
742 " -d string URL decode given string\n"
743 " -r string Specify basic auth realm\n"
744 " -m string MD5 crypt given string\n"
753 if( (tls
== 1) && (keys
< 2) )
755 fprintf(stderr
, "Error: Missing private key or certificate file\n");
762 fprintf(stderr
, "Error: No sockets bound, unable to continue\n");
766 /* default docroot */
767 if( !conf
.docroot
[0] && !realpath(".", conf
.docroot
) )
769 fprintf(stderr
, "Error: Can not determine default document root: %s\n",
776 conf
.realm
= "Protected Area";
779 uh_config_parse(&conf
);
781 /* default network timeout */
782 if( conf
.network_timeout
<= 0 )
783 conf
.network_timeout
= 30;
785 #if defined(HAVE_CGI) || defined(HAVE_LUA)
786 /* default script timeout */
787 if( conf
.script_timeout
<= 0 )
788 conf
.script_timeout
= 60;
792 /* default cgi prefix */
793 if( ! conf
.cgi_prefix
)
794 conf
.cgi_prefix
= "/cgi-bin";
798 /* load Lua plugin */
799 if( ! (lib
= dlopen("uhttpd_lua.so", RTLD_LAZY
| RTLD_GLOBAL
)) )
802 "Notice: Unable to load Lua plugin - disabling Lua support! "
803 "(Reason: %s)\n", dlerror()
808 /* resolve functions */
809 if( !(conf
.lua_init
= dlsym(lib
, "uh_lua_init")) ||
810 !(conf
.lua_close
= dlsym(lib
, "uh_lua_close")) ||
811 !(conf
.lua_request
= dlsym(lib
, "uh_lua_request"))
814 "Error: Failed to lookup required symbols "
815 "in Lua plugin: %s\n", dlerror()
820 /* init Lua runtime if handler is specified */
821 if( conf
.lua_handler
)
823 /* default lua prefix */
824 if( ! conf
.lua_prefix
)
825 conf
.lua_prefix
= "/lua";
827 L
= conf
.lua_init(conf
.lua_handler
);
832 /* fork (if not disabled) */
846 if( (cur_fd
= open("/dev/null", O_WRONLY
)) > -1 )
849 if( (cur_fd
= open("/dev/null", O_RDONLY
)) > -1 )
852 if( (cur_fd
= open("/dev/null", O_RDONLY
)) > -1 )
862 /* backup server descriptor set */
868 /* create a working copy of the used fd set */
871 /* sleep until socket activity */
872 if( select(max_fd
+ 1, &read_fds
, NULL
, NULL
, NULL
) == -1 )
878 /* run through the existing connections looking for data to be read */
879 for( cur_fd
= 0; cur_fd
<= max_fd
; cur_fd
++ )
881 /* is a socket managed by us */
882 if( FD_ISSET(cur_fd
, &read_fds
) )
884 /* is one of our listen sockets */
885 if( FD_ISSET(cur_fd
, &serv_fds
) )
887 /* handle new connections */
888 if( (new_fd
= accept(cur_fd
, NULL
, 0)) != -1 )
890 /* add to global client list */
891 if( (cl
= uh_client_add(new_fd
, uh_listener_lookup(cur_fd
))) != NULL
)
894 /* setup client tls context */
899 /* add client socket to global fdset */
900 FD_SET(new_fd
, &used_fds
);
902 max_fd
= max(max_fd
, new_fd
);
905 /* insufficient resources */
909 "uh_client_add(): Can not manage more than "
910 "%i client sockets, connection dropped\n",
919 /* is a client socket */
922 if( ! (cl
= uh_client_lookup(cur_fd
)) )
924 /* this should not happen! */
926 "uh_client_lookup(): No entry for fd %i!\n",
932 /* parse message header */
933 if( (req
= uh_http_header_recv(cl
)) != NULL
)
937 if( L
&& uh_path_match(conf
.lua_prefix
, req
->url
) )
939 conf
.lua_request(cl
, req
, L
);
943 /* dispatch request */
944 if( (pin
= uh_path_lookup(cl
, req
->url
)) != NULL
)
947 if( uh_auth_check(cl
, req
, pin
) )
950 if( uh_path_match(conf
.cgi_prefix
, pin
->name
) )
952 uh_cgi_request(cl
, req
, pin
);
957 uh_file_request(cl
, req
, pin
);
965 /* Try to invoke an error handler */
966 pin
= uh_path_lookup(cl
, conf
.error_handler
);
968 if( pin
&& uh_auth_check(cl
, req
, pin
) )
970 req
->redirect_status
= 404;
973 if( uh_path_match(conf
.cgi_prefix
, pin
->name
) )
975 uh_cgi_request(cl
, req
, pin
);
980 uh_file_request(cl
, req
, pin
);
985 uh_http_sendhf(cl
, 404, "Not Found",
986 "No such file or directory");
994 uh_http_sendhf(cl
, 400, "Bad Request",
995 "Malformed request received");
999 /* free client tls context */
1006 /* close client socket */
1008 FD_CLR(cur_fd
, &used_fds
);
1010 /* remove from global client list */
1011 uh_client_remove(cur_fd
);
1018 /* destroy the Lua state */
This page took 0.087518 seconds and 5 git commands to generate.