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( !(col1
= strchr(line
, ':')) || (*col1
++ = 0) ||
70 !(col2
= strchr(col1
, ':')) || (*col2
++ = 0) ||
71 !(eol
= strchr(col2
, '\n')) || (*eol
++ = 0) )
74 if( !uh_auth_add(line
, col1
, col2
) )
77 "Notice: No password set for user %s, ignoring "
78 "authentication on %s\n", col1
, line
82 else if( !strncmp(line
, "I:", 2) )
84 if( !(col1
= strchr(line
, ':')) || (*col1
++ = 0) ||
85 !(eol
= strchr(col1
, '\n')) || (*eol
++ = 0) )
88 conf
->index_file
= strdup(col1
);
90 else if( !strncmp(line
, "E404:", 5) )
92 if( !(col1
= strchr(line
, ':')) || (*col1
++ = 0) ||
93 !(eol
= strchr(col1
, '\n')) || (*eol
++ = 0) )
96 conf
->error_handler
= strdup(col1
);
99 else if( (line
[0] == '*') && (strchr(line
, ':') != NULL
) )
101 if( !(col1
= strchr(line
, '*')) || (*col1
++ = 0) ||
102 !(col2
= strchr(col1
, ':')) || (*col2
++ = 0) ||
103 !(eol
= strchr(col2
, '\n')) || (*eol
++ = 0) )
106 if( !uh_interpreter_add(col1
, col2
) )
109 "Unable to add interpreter %s for extension %s: "
110 "Out of memory\n", col2
, col1
121 static int uh_socket_bind(
122 fd_set
*serv_fds
, int *max_fd
, const char *host
, const char *port
,
123 struct addrinfo
*hints
, int do_tls
, struct config
*conf
130 int tcp_ka_idl
, tcp_ka_int
, tcp_ka_cnt
;
132 struct listener
*l
= NULL
;
133 struct addrinfo
*addrs
= NULL
, *p
= NULL
;
135 if( (status
= getaddrinfo(host
, port
, hints
, &addrs
)) != 0 )
137 fprintf(stderr
, "getaddrinfo(): %s\n", gai_strerror(status
));
140 /* try to bind a new socket to each found address */
141 for( p
= addrs
; p
; p
= p
->ai_next
)
144 if( (sock
= socket(p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1 )
150 /* "address already in use" */
151 if( setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(yes
)) )
153 perror("setsockopt()");
158 if( conf
->tcp_keepalive
> 0 )
162 tcp_ka_int
= conf
->tcp_keepalive
;
164 if( setsockopt(sock
, SOL_SOCKET
, SO_KEEPALIVE
, &yes
, sizeof(yes
)) ||
165 setsockopt(sock
, SOL_TCP
, TCP_KEEPIDLE
, &tcp_ka_idl
, sizeof(tcp_ka_idl
)) ||
166 setsockopt(sock
, SOL_TCP
, TCP_KEEPINTVL
, &tcp_ka_int
, sizeof(tcp_ka_int
)) ||
167 setsockopt(sock
, SOL_TCP
, TCP_KEEPCNT
, &tcp_ka_cnt
, sizeof(tcp_ka_cnt
)) )
169 fprintf(stderr
, "Notice: Unable to enable TCP keep-alive: %s\n",
174 /* required to get parallel v4 + v6 working */
175 if( p
->ai_family
== AF_INET6
)
177 if( setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &yes
, sizeof(yes
)) == -1 )
179 perror("setsockopt()");
185 if( bind(sock
, p
->ai_addr
, p
->ai_addrlen
) == -1 )
192 if( listen(sock
, UH_LIMIT_CLIENTS
) == -1 )
198 /* add listener to global list */
199 if( ! (l
= uh_listener_add(sock
, conf
)) )
201 fprintf(stderr
, "uh_listener_add(): Failed to allocate memory\n");
207 l
->tls
= do_tls
? conf
->tls
: NULL
;
210 /* add socket to server fd set */
211 FD_SET(sock
, serv_fds
);
213 *max_fd
= max(*max_fd
, sock
);
228 static struct http_request
* uh_http_header_parse(struct client
*cl
, char *buffer
, int buflen
)
230 char *method
= &buffer
[0];
232 char *version
= NULL
;
234 char *headers
= NULL
;
235 char *hdrname
= NULL
;
236 char *hdrdata
= NULL
;
241 static struct http_request req
;
243 memset(&req
, 0, sizeof(req
));
246 /* terminate initial header line */
247 if( (headers
= strfind(buffer
, buflen
, "\r\n", 2)) != NULL
)
249 buffer
[buflen
-1] = 0;
254 /* find request path */
255 if( (path
= strchr(buffer
, ' ')) != NULL
)
258 /* find http version */
259 if( (path
!= NULL
) && ((version
= strchr(path
, ' ')) != NULL
) )
264 if( strcmp(method
, "GET") && strcmp(method
, "HEAD") && strcmp(method
, "POST") )
267 uh_http_response(cl
, 405, "Method Not Allowed");
275 req
.method
= UH_HTTP_MSG_GET
;
279 req
.method
= UH_HTTP_MSG_HEAD
;
283 req
.method
= UH_HTTP_MSG_POST
;
289 if( !path
|| !strlen(path
) )
291 /* malformed request */
292 uh_http_response(cl
, 400, "Bad Request");
301 if( (version
== NULL
) || (strcmp(version
, "HTTP/0.9") &&
302 strcmp(version
, "HTTP/1.0") && strcmp(version
, "HTTP/1.1")) )
304 /* unsupported version */
305 uh_http_response(cl
, 400, "Bad Request");
310 req
.version
= strtof(&version
[5], NULL
);
314 /* process header fields */
315 for( i
= (int)(headers
- buffer
); i
< buflen
; i
++ )
317 /* found eol and have name + value, push out header tuple */
318 if( hdrname
&& hdrdata
&& (buffer
[i
] == '\r' || buffer
[i
] == '\n') )
323 if( (hdrcount
+ 1) < array_size(req
.headers
) )
325 req
.headers
[hdrcount
++] = hdrname
;
326 req
.headers
[hdrcount
++] = hdrdata
;
328 hdrname
= hdrdata
= NULL
;
334 uh_http_response(cl
, 413, "Request Entity Too Large");
339 /* have name but no value and found a colon, start of value */
340 else if( hdrname
&& !hdrdata
&& ((i
+2) < buflen
) &&
341 (buffer
[i
] == ':') && (buffer
[i
+1] == ' ')
344 hdrdata
= &buffer
[i
+2];
347 /* have no name and found [A-Za-z], start of name */
348 else if( !hdrname
&& isalpha(buffer
[i
]) )
350 hdrname
= &buffer
[i
];
355 req
.redirect_status
= 200;
359 /* Malformed request */
360 uh_http_response(cl
, 400, "Bad Request");
365 static struct http_request
* uh_http_header_recv(struct client
*cl
)
367 static char buffer
[UH_LIMIT_MSGHEAD
];
368 char *bufptr
= &buffer
[0];
371 struct timeval timeout
;
375 ssize_t blen
= sizeof(buffer
)-1;
378 memset(buffer
, 0, sizeof(buffer
));
383 FD_SET(cl
->socket
, &reader
);
385 /* fail after 0.1s */
387 timeout
.tv_usec
= 100000;
389 /* check whether fd is readable */
390 if( select(cl
->socket
+ 1, &reader
, NULL
, NULL
, &timeout
) > 0 )
393 ensure_out(rlen
= uh_tcp_peek(cl
, bufptr
, blen
));
395 if( (idxptr
= strfind(buffer
, sizeof(buffer
), "\r\n\r\n", 4)) )
397 ensure_out(rlen
= uh_tcp_recv(cl
, bufptr
,
398 (int)(idxptr
- bufptr
) + 4));
400 /* header read complete ... */
402 return uh_http_header_parse(cl
, buffer
,
403 sizeof(buffer
) - blen
- 1);
407 ensure_out(rlen
= uh_tcp_recv(cl
, bufptr
, rlen
));
409 /* unexpected eof - #7904 */
419 /* invalid request (unexpected eof/timeout) */
424 /* request entity too large */
425 uh_http_response(cl
, 413, "Request Entity Too Large");
431 #if defined(HAVE_LUA) || defined(HAVE_CGI)
432 static int uh_path_match(const char *prefix
, const char *url
)
434 if( (strstr(url
, prefix
) == url
) &&
435 ((prefix
[strlen(prefix
)-1] == '/') ||
436 (strlen(url
) == strlen(prefix
)) ||
437 (url
[strlen(prefix
)] == '/'))
446 static void uh_dispatch_request(
447 struct client
*cl
, struct http_request
*req
, struct path_info
*pin
450 struct interpreter
*ipr
= NULL
;
452 if( uh_path_match(cl
->server
->conf
->cgi_prefix
, pin
->name
) ||
453 (ipr
= uh_interpreter_lookup(pin
->phys
)) )
455 uh_cgi_request(cl
, req
, pin
, ipr
);
460 uh_file_request(cl
, req
, pin
);
464 static void uh_mainloop(struct config
*conf
, fd_set serv_fds
, int max_fd
)
466 /* master file descriptor list */
467 fd_set used_fds
, read_fds
;
469 /* working structs */
470 struct http_request
*req
;
471 struct path_info
*pin
;
474 /* maximum file descriptor number */
475 int new_fd
, cur_fd
= 0;
477 /* clear the master and temp sets */
481 /* backup server descriptor set */
487 /* create a working copy of the used fd set */
490 /* sleep until socket activity */
491 if( select(max_fd
+ 1, &read_fds
, NULL
, NULL
, NULL
) == -1 )
497 /* run through the existing connections looking for data to be read */
498 for( cur_fd
= 0; cur_fd
<= max_fd
; cur_fd
++ )
500 /* is a socket managed by us */
501 if( FD_ISSET(cur_fd
, &read_fds
) )
503 /* is one of our listen sockets */
504 if( FD_ISSET(cur_fd
, &serv_fds
) )
506 /* handle new connections */
507 if( (new_fd
= accept(cur_fd
, NULL
, 0)) != -1 )
509 /* add to global client list */
510 if( (cl
= uh_client_add(new_fd
, uh_listener_lookup(cur_fd
))) != NULL
)
513 /* setup client tls context */
516 if( conf
->tls_accept(cl
) < 1 )
519 "tls_accept failed, "
520 "connection dropped\n");
522 /* close client socket */
525 /* remove from global client list */
526 uh_client_remove(new_fd
);
533 /* add client socket to global fdset */
534 FD_SET(new_fd
, &used_fds
);
536 max_fd
= max(max_fd
, new_fd
);
539 /* insufficient resources */
543 "uh_client_add(): Cannot allocate memory\n");
550 /* is a client socket */
553 if( ! (cl
= uh_client_lookup(cur_fd
)) )
555 /* this should not happen! */
557 "uh_client_lookup(): No entry for fd %i!\n",
563 /* parse message header */
564 if( (req
= uh_http_header_recv(cl
)) != NULL
)
566 /* RFC1918 filtering required? */
567 if( conf
->rfc1918_filter
&&
568 sa_rfc1918(&cl
->peeraddr
) &&
569 !sa_rfc1918(&cl
->servaddr
) )
571 uh_http_sendhf(cl
, 403, "Forbidden",
572 "Rejected request from RFC1918 IP "
573 "to public server address");
578 if( conf
->lua_state
&&
579 uh_path_match(conf
->lua_prefix
, req
->url
) )
581 conf
->lua_request(cl
, req
, conf
->lua_state
);
585 /* dispatch request */
586 if( (pin
= uh_path_lookup(cl
, req
->url
)) != NULL
)
589 if( !pin
->redirected
&& uh_auth_check(cl
, req
, pin
) )
590 uh_dispatch_request(cl
, req
, pin
);
596 /* Try to invoke an error handler */
597 pin
= uh_path_lookup(cl
, conf
->error_handler
);
599 if( pin
&& uh_auth_check(cl
, req
, pin
) )
601 req
->redirect_status
= 404;
602 uh_dispatch_request(cl
, req
, pin
);
606 uh_http_sendhf(cl
, 404, "Not Found",
607 "No such file or directory");
613 /* free client tls context */
620 /* close client socket */
622 FD_CLR(cur_fd
, &used_fds
);
624 /* remove from global client list */
625 uh_client_remove(cur_fd
);
632 /* destroy the Lua state */
633 if( conf
->lua_state
!= NULL
)
634 conf
->lua_close(conf
->lua_state
);
639 static inline int uh_inittls(struct config
*conf
)
645 if( conf
->tls
!= NULL
)
648 /* load TLS plugin */
649 if( ! (lib
= dlopen("uhttpd_tls.so", RTLD_LAZY
| RTLD_GLOBAL
)) )
652 "Notice: Unable to load TLS plugin - disabling SSL support! "
653 "(Reason: %s)\n", dlerror()
660 /* resolve functions */
661 if( !(conf
->tls_init
= dlsym(lib
, "uh_tls_ctx_init")) ||
662 !(conf
->tls_cert
= dlsym(lib
, "uh_tls_ctx_cert")) ||
663 !(conf
->tls_key
= dlsym(lib
, "uh_tls_ctx_key")) ||
664 !(conf
->tls_free
= dlsym(lib
, "uh_tls_ctx_free")) ||
665 !(conf
->tls_accept
= dlsym(lib
, "uh_tls_client_accept")) ||
666 !(conf
->tls_close
= dlsym(lib
, "uh_tls_client_close")) ||
667 !(conf
->tls_recv
= dlsym(lib
, "uh_tls_client_recv")) ||
668 !(conf
->tls_send
= dlsym(lib
, "uh_tls_client_send"))
671 "Error: Failed to lookup required symbols "
672 "in TLS plugin: %s\n", dlerror()
677 /* init SSL context */
678 if( ! (conf
->tls
= conf
->tls_init()) )
680 fprintf(stderr
, "Error: Failed to initalize SSL context\n");
689 int main (int argc
, char **argv
)
691 /* master file descriptor list */
694 /* working structs */
695 struct addrinfo hints
;
702 /* maximum file descriptor number */
703 int cur_fd
, max_fd
= 0;
725 /* handle SIGPIPE, SIGINT, SIGTERM, SIGCHLD */
727 sigemptyset(&sa
.sa_mask
);
729 sa
.sa_handler
= SIG_IGN
;
730 sigaction(SIGPIPE
, &sa
, NULL
);
732 sa
.sa_handler
= uh_sigchld
;
733 sigaction(SIGCHLD
, &sa
, NULL
);
735 sa
.sa_handler
= uh_sigterm
;
736 sigaction(SIGINT
, &sa
, NULL
);
737 sigaction(SIGTERM
, &sa
, NULL
);
741 sigaddset(&ss
, SIGCHLD
);
742 sigprocmask(SIG_BLOCK
, &ss
, NULL
);
744 /* prepare addrinfo hints */
745 memset(&hints
, 0, sizeof(hints
));
746 hints
.ai_family
= AF_UNSPEC
;
747 hints
.ai_socktype
= SOCK_STREAM
;
748 hints
.ai_flags
= AI_PASSIVE
;
751 memset(&conf
, 0, sizeof(conf
));
752 memset(bind
, 0, sizeof(bind
));
755 while( (opt
= getopt(argc
, argv
,
756 "fSDRC:K:E:I:p:s:h:c:l:L:d:r:m:x:i:t:T:A:")) > 0
763 if( (port
= strrchr(optarg
, ':')) != NULL
)
765 if( (optarg
[0] == '[') && (port
> optarg
) && (port
[-1] == ']') )
766 memcpy(bind
, optarg
+ 1,
767 min(sizeof(bind
), (int)(port
- optarg
) - 2));
770 min(sizeof(bind
), (int)(port
- optarg
)));
782 if( uh_inittls(&conf
) )
785 "Notice: TLS support is disabled, "
786 "ignoring '-s %s'\n", optarg
796 bound
+= uh_socket_bind(
797 &serv_fds
, &max_fd
, bind
[0] ? bind
: NULL
, port
,
798 &hints
, (opt
== 's'), &conf
801 memset(bind
, 0, sizeof(bind
));
807 if( !uh_inittls(&conf
) )
809 if( conf
.tls_cert(conf
.tls
, optarg
) < 1 )
812 "Error: Invalid certificate file given\n");
823 if( !uh_inittls(&conf
) )
825 if( conf
.tls_key(conf
.tls
, optarg
) < 1 )
828 "Error: Invalid private key file given\n");
840 if( ! realpath(optarg
, conf
.docroot
) )
842 fprintf(stderr
, "Error: Invalid directory %s: %s\n",
843 optarg
, strerror(errno
));
850 if( (strlen(optarg
) == 0) || (optarg
[0] != '/') )
852 fprintf(stderr
, "Error: Invalid error handler: %s\n",
856 conf
.error_handler
= optarg
;
861 if( (strlen(optarg
) == 0) || (optarg
[0] == '/') )
863 fprintf(stderr
, "Error: Invalid index page: %s\n",
867 conf
.index_file
= optarg
;
870 /* don't follow symlinks */
872 conf
.no_symlinks
= 1;
875 /* don't list directories */
877 conf
.no_dirlists
= 1;
881 conf
.rfc1918_filter
= 1;
887 conf
.cgi_prefix
= optarg
;
892 if( (optarg
[0] == '.') && (port
= strchr(optarg
, '=')) )
895 uh_interpreter_add(optarg
, port
);
899 fprintf(stderr
, "Error: Invalid interpreter: %s\n",
909 conf
.lua_prefix
= optarg
;
914 conf
.lua_handler
= optarg
;
918 #if defined(HAVE_CGI) || defined(HAVE_LUA)
921 conf
.script_timeout
= atoi(optarg
);
925 /* network timeout */
927 conf
.network_timeout
= atoi(optarg
);
932 conf
.tcp_keepalive
= atoi(optarg
);
942 if( (port
= malloc(strlen(optarg
)+1)) != NULL
)
944 /* "decode" plus to space to retain compat */
945 for (opt
= 0; optarg
[opt
]; opt
++)
946 if (optarg
[opt
] == '+')
949 memset(port
, 0, strlen(optarg
)+1);
950 uh_urldecode(port
, strlen(optarg
), optarg
, strlen(optarg
));
958 /* basic auth realm */
965 printf("%s\n", crypt(optarg
, "$1$"));
976 "Usage: %s -p [addr:]port [-h docroot]\n"
977 " -f Do not fork to background\n"
978 " -c file Configuration file, default is '/etc/httpd.conf'\n"
979 " -p [addr:]port Bind to specified address and port, multiple allowed\n"
981 " -s [addr:]port Like -p but provide HTTPS on this port\n"
982 " -C file ASN.1 server certificate file\n"
983 " -K file ASN.1 server private key file\n"
985 " -h directory Specify the document root, default is '.'\n"
986 " -E string Use given virtual URL as 404 error handler\n"
987 " -I string Use given filename as index page for directories\n"
988 " -S Do not follow symbolic links outside of the docroot\n"
989 " -D Do not allow directory listings, send 403 instead\n"
990 " -R Enable RFC1918 filter\n"
992 " -l string URL prefix for Lua handler, default is '/lua'\n"
993 " -L file Lua handler script, omit to disable Lua\n"
996 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
997 " -i .ext=path Use interpreter at path for files with the given extension\n"
999 #if defined(HAVE_CGI) || defined(HAVE_LUA)
1000 " -t seconds CGI and Lua script timeout in seconds, default is 60\n"
1002 " -T seconds Network timeout in seconds, default is 30\n"
1003 " -d string URL decode given string\n"
1004 " -r string Specify basic auth realm\n"
1005 " -m string MD5 crypt given string\n"
1014 if( (tls
== 1) && (keys
< 2) )
1016 fprintf(stderr
, "Error: Missing private key or certificate file\n");
1023 fprintf(stderr
, "Error: No sockets bound, unable to continue\n");
1027 /* default docroot */
1028 if( !conf
.docroot
[0] && !realpath(".", conf
.docroot
) )
1030 fprintf(stderr
, "Error: Can not determine default document root: %s\n",
1037 conf
.realm
= "Protected Area";
1040 uh_config_parse(&conf
);
1042 /* default network timeout */
1043 if( conf
.network_timeout
<= 0 )
1044 conf
.network_timeout
= 30;
1046 #if defined(HAVE_CGI) || defined(HAVE_LUA)
1047 /* default script timeout */
1048 if( conf
.script_timeout
<= 0 )
1049 conf
.script_timeout
= 60;
1053 /* default cgi prefix */
1054 if( ! conf
.cgi_prefix
)
1055 conf
.cgi_prefix
= "/cgi-bin";
1059 /* load Lua plugin */
1060 if( ! (lib
= dlopen("uhttpd_lua.so", RTLD_LAZY
| RTLD_GLOBAL
)) )
1063 "Notice: Unable to load Lua plugin - disabling Lua support! "
1064 "(Reason: %s)\n", dlerror()
1069 /* resolve functions */
1070 if( !(conf
.lua_init
= dlsym(lib
, "uh_lua_init")) ||
1071 !(conf
.lua_close
= dlsym(lib
, "uh_lua_close")) ||
1072 !(conf
.lua_request
= dlsym(lib
, "uh_lua_request"))
1075 "Error: Failed to lookup required symbols "
1076 "in Lua plugin: %s\n", dlerror()
1081 /* init Lua runtime if handler is specified */
1082 if( conf
.lua_handler
)
1084 /* default lua prefix */
1085 if( ! conf
.lua_prefix
)
1086 conf
.lua_prefix
= "/lua";
1088 conf
.lua_state
= conf
.lua_init(conf
.lua_handler
);
1093 /* fork (if not disabled) */
1107 if( (cur_fd
= open("/dev/null", O_WRONLY
)) > -1 )
1110 if( (cur_fd
= open("/dev/null", O_RDONLY
)) > -1 )
1113 if( (cur_fd
= open("/dev/null", O_RDONLY
)) > -1 )
1123 /* server main loop */
1124 uh_mainloop(&conf
, serv_fds
, max_fd
);
1127 /* destroy the Lua state */
1128 if( conf
.lua_state
!= NULL
)
1129 conf
.lua_close(conf
.lua_state
);
This page took 0.129999 seconds and 5 git commands to generate.