1
0
mirror of https://github.com/fumiama/simple-http-server.git synced 2026-06-10 13:00:28 +08:00

修复内存泄漏

This commit is contained in:
源文雨
2022-03-05 14:14:38 +08:00
parent f61d3ce71f
commit bde4b52ada

View File

@@ -7,7 +7,7 @@
* Modified June 2021 by Fumiama(源文雨) * Modified June 2021 by Fumiama(源文雨)
*/ */
/* See feature_test_macros(7) */ /* See feature_test_macros(7) */
#define _GNU_SOURCE 1 #define _GNU_SOURCE
#include <arpa/inet.h> #include <arpa/inet.h>
#include <ctype.h> #include <ctype.h>
#include <fcntl.h> #include <fcntl.h>
@@ -77,7 +77,6 @@ static void unimplemented(int);
#define skiptext(buf, j, cap) while(!ISspace(buf[j]) && (j < (cap))) j++ #define skiptext(buf, j, cap) while(!ISspace(buf[j]) && (j < (cap))) j++
#define skipspace(buf, j, cap) while(ISspace(buf[j]) && (j < (cap))) j++ #define skipspace(buf, j, cap) while(ISspace(buf[j]) && (j < (cap))) j++
#define getmethod(method_type) ((method_type == GET)?"GET":"POST") #define getmethod(method_type) ((method_type == GET)?"GET":"POST")
static void accept_request(void *cli) { static void accept_request(void *cli) {
int client = (int)cli; int client = (int)cli;
char buf[1024], *path, *query_string; char buf[1024], *path, *query_string;
@@ -85,9 +84,9 @@ static void accept_request(void *cli) {
struct stat st; struct stat st;
METHOD_TYPE method_type; METHOD_TYPE method_type;
signal(SIGCHLD, SIG_IGN);
signal(SIGQUIT, handle_quit); signal(SIGQUIT, handle_quit);
signal(SIGPIPE, handle_quit); signal(SIGPIPE, handle_quit);
pthread_detach(pthread_self());
numchars = get_line(client, buf, sizeof(buf)); numchars = get_line(client, buf, sizeof(buf));
j = 0; j = 0;
@@ -235,39 +234,30 @@ static void error_die(const char *sc) {
* path to the CGI script */ * path to the CGI script */
/**********************************************************************/ /**********************************************************************/
static void execute_cgi(int client, int content_length, const HTTP_REQUEST* request) { static void execute_cgi(int client, int content_length, const HTTP_REQUEST* request) {
int cgi_output[2], cgi_input[2], i; int cgi_output[2], cgi_input[2];
pid_t pid; pid_t pid;
char buf[1024];
if(pipe(cgi_output) < 0 || pipe(cgi_input) < 0 || (pid = fork()) < 0) internal_error(client); if(pipe(cgi_output) < 0 || pipe(cgi_input) < 0 || (pid = fork()) < 0) {
internal_error(client);
return;
}
/* child: CGI script */ /* child: CGI script */
else if(pid == 0) { if(pid == 0) {
char env[255];
dup2(cgi_output[1], 1); dup2(cgi_output[1], 1);
dup2(cgi_input[0], 0); dup2(cgi_input[0], 0);
close(cgi_output[0]); close(cgi_output[0]);
close(cgi_input[1]); close(cgi_input[1]);
sprintf(env, "REQUEST_METHOD=%s", request->method);
putenv(env);
if(request->method_type == GET) {
sprintf(env, "QUERY_STRING=%s", request->query_string);
putenv(env);
}
else { /* POST */
sprintf(env, "CONTENT_LENGTH=%d", content_length);
putenv(env);
}
execl(request->path, request->path, request->method, request->query_string, NULL);
exit(0);
}
else { /* parent */
char buf[1024];
execl(request->path, request->path, request->method, request->query_string, NULL);
exit(EXIT_SUCCESS);
}
/* parent */
close(cgi_output[1]); close(cgi_output[1]);
close(cgi_input[0]); close(cgi_input[0]);
if(request->method_type == POST) { if(request->method_type == POST) {
#if __APPLE__ #if __APPLE__
for(i = 0; i < content_length;) { for(int i = 0; i < content_length;) {
int cnt = recv(client, buf, 1024, 0); int cnt = recv(client, buf, 1024, 0);
if(cnt > 0) { if(cnt > 0) {
write(cgi_input[1], buf, cnt); write(cgi_input[1], buf, cnt);
@@ -305,15 +295,14 @@ static void execute_cgi(int client, int content_length, const HTTP_REQUEST* requ
int len = 0; int len = 0;
#if __APPLE__ #if __APPLE__
int cap = (cnt>1024)?1024:cnt; int cap = (cnt>1024)?1024:cnt;
char data[cap];
while(len < cnt) { while(len < cnt) {
int n = read(cgi_output[0], data, cap); int n = read(cgi_output[0], buf, cap);
if(n <= 0) { if(n <= 0) {
internal_error(client); internal_error(client);
goto CGI_CLOSE; goto CGI_CLOSE;
} }
len += n; len += n;
send(client, data, cap, 0); send(client, buf, n, 0);
} }
#else #else
while(len < cnt) { while(len < cnt) {
@@ -327,11 +316,10 @@ static void execute_cgi(int client, int content_length, const HTTP_REQUEST* requ
#endif #endif
printf("CGI send %d bytes\n", len); printf("CGI send %d bytes\n", len);
} }
CGI_CLOSE: CGI_CLOSE:
close(cgi_output[0]); close(cgi_output[0]);
close(cgi_input[1]); close(cgi_input[1]);
waitpid(pid, &i, 0); waitpid(pid, NULL, 0);
}
} }
/**********************************************************************/ /**********************************************************************/
@@ -397,14 +385,13 @@ static void handle_quit(int signo) {
/* Parameters: the socket to print the headers on /* Parameters: the socket to print the headers on
* the name of the file */ * the name of the file */
/**********************************************************************/ /**********************************************************************/
#define ADD_HERDER(h)\ #define add_header(h)\
strcpy(buf + offset, h);\ strcpy(buf + offset, h);\
offset += sizeof(h) - 1; offset += sizeof(h) - 1;
#define ADD_HERDER_PARAM(h, p)\ #define add_header_para(h, p)\
sprintf(buf + offset, h,(p));\ sprintf(buf + offset, h,(p));\
offset += strlen(buf + offset); offset += strlen(buf + offset);
#define EXTNM_IS_NOT(name)(strcmp(filepath+extpos, name)) #define extisnot(name) (strcmp(filepath+extpos, name))
#define HTTP200 "HTTP/1.0 200 OK\r\n" #define HTTP200 "HTTP/1.0 200 OK\r\n"
#define CONTENT_TYPE "Content-Type: %s\r\n" #define CONTENT_TYPE "Content-Type: %s\r\n"
#define CONTENT_LEN "Content-Length: %d\r\n" #define CONTENT_LEN "Content-Length: %d\r\n"
@@ -414,9 +401,9 @@ static int headers(int client, const char *filepath) {
uint32_t extpos = strlen(filepath) - 4; uint32_t extpos = strlen(filepath) - 4;
uint32_t file_size = get_file_size(filepath, client); uint32_t file_size = get_file_size(filepath, client);
if(file_size) { if(file_size) {
ADD_HERDER(HTTP200 SERVER_STRING); add_header(HTTP200 SERVER_STRING);
ADD_HERDER_PARAM(CONTENT_TYPE, EXTNM_IS_NOT("html")?(EXTNM_IS_NOT(".css")?(EXTNM_IS_NOT(".ico")?"text/plain":"image/x-icon"):"text/css"):"text/html"); add_header_para(CONTENT_TYPE, extisnot("html")?(extisnot(".css")?(extisnot(".ico")?"text/plain":"image/x-icon"):"text/css"):"text/html");
ADD_HERDER_PARAM(CONTENT_LEN "\r\n", file_size); add_header_para(CONTENT_LEN "\r\n", file_size);
send(client, buf, offset, 0); send(client, buf, offset, 0);
puts("200 OK."); puts("200 OK.");
return 1; return 1;
@@ -467,7 +454,6 @@ static void serve_file(int client, const char *filename) {
static struct sockaddr_in name; static struct sockaddr_in name;
static struct sockaddr_in client_name; static struct sockaddr_in client_name;
#endif #endif
static int startup(uint16_t *port) { static int startup(uint16_t *port) {
int httpd = 0; int httpd = 0;
@@ -484,6 +470,7 @@ static int startup(uint16_t *port) {
httpd = socket(AF_INET, SOCK_STREAM, 0); httpd = socket(AF_INET, SOCK_STREAM, 0);
#endif #endif
if(httpd < 0) error_die("socket"); if(httpd < 0) error_die("socket");
if(bind(httpd,(struct sockaddr *)&name, struct_len) < 0) error_die("bind"); if(bind(httpd,(struct sockaddr *)&name, struct_len) < 0) error_die("bind");
/* if dynamically allocating a port */ /* if dynamically allocating a port */
if(*port == 0) { if(*port == 0) {
@@ -495,22 +482,26 @@ static int startup(uint16_t *port) {
#endif #endif
} }
if(listen(httpd, 5) < 0) error_die("listen"); if(listen(httpd, 5) < 0) error_die("listen");
return httpd; return httpd;
} }
static struct sockaddr_un uname; static struct sockaddr_un uname;
static int startupunix(char *path) { static int startupunix(char *path) {
int httpd = socket(AF_UNIX, SOCK_STREAM, 0); int httpd = socket(AF_UNIX, SOCK_STREAM, 0);
if(httpd < 0) error_die("unix socket");
uname.sun_family = AF_UNIX; uname.sun_family = AF_UNIX;
strncpy(uname.sun_path, path, sizeof(uname.sun_path)); strncpy(uname.sun_path, path, sizeof(uname.sun_path));
uname.sun_path[sizeof(uname.sun_path)-1] = 0; // avoid overlap uname.sun_path[sizeof(uname.sun_path)-1] = 0; // avoid overlap
#if __APPLE__ #if __APPLE__
uname.sun_len = strlen(uname.sun_path); uname.sun_len = strlen(uname.sun_path);
#endif #endif
if(httpd < 0) error_die("unix socket");
unlink(path); // in case it already exists unlink(path); // in case it already exists
if(bind(httpd, (struct sockaddr *)&uname, SUN_LEN(&uname)) < 0) error_die("bind"); if(bind(httpd, (struct sockaddr *)&uname, SUN_LEN(&uname)) < 0) error_die("bind");
if(listen(httpd, 5) < 0) error_die("listen"); if(listen(httpd, 5) < 0) error_die("listen");
return httpd; return httpd;
} }
@@ -533,7 +524,7 @@ static pthread_attr_t attr;
static int accept_client(int is_unix_sock) { static int accept_client(int is_unix_sock) {
pthread_attr_init(&attr); pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, 1); pthread_attr_setdetachstate(&attr, 1);
signal(SIGCHLD, SIG_IGN);
while(1) { while(1) {
socklen_t client_name_len = sizeof(client_name); socklen_t client_name_len = sizeof(client_name);
int client_sock = accept(server_sock, (struct sockaddr *)(is_unix_sock?NULL:&client_name), is_unix_sock?NULL:&client_name_len); int client_sock = accept(server_sock, (struct sockaddr *)(is_unix_sock?NULL:&client_name), is_unix_sock?NULL:&client_name_len);
@@ -558,15 +549,13 @@ static int accept_client(int is_unix_sock) {
} }
pthread_t accept_thread; pthread_t accept_thread;
if(pthread_create(&accept_thread, &attr, &accept_request, client_sock) != 0) perror("pthread_create"); if(pthread_create(&accept_thread, &attr, &accept_request, client_sock) != 0) perror("pthread_create");
printf("Created new thread at 0x%x\n", accept_thread); printf("Created new thread at 0x%p\n", (void*)accept_thread);
} }
} }
#define argequ(arg) (*(uint16_t*)argv[i] == *(uint16_t*)(arg)) #define argequ(arg) (*(uint16_t*)argv[i] == *(uint16_t*)(arg))
#define USAGE "Usage:\tsimple-http-server [-h] [-d] [-p <port|unix socket path>] [-r <rootdir>] [-u <uid>]\n -h:\tdisplay this help.\n -d:\trun as daemon.\n -p:\tif not set, we will choose a random port.\n -r:\thttp root dir.\n -u:\trun as this uid." #define USAGE "Usage:\tsimple-http-server [-h] [-d] [-p <port|unix socket path>] [-r <rootdir>] [-u <uid>]\n -h:\tdisplay this help.\n -d:\trun as daemon.\n -p:\tif not set, we will choose a random port.\n -r:\thttp root dir.\n -u:\trun as this uid."
int main(int argc, char **argv) { int main(int argc, char **argv) {
if(argc > 8) puts(USAGE);
else {
int as_daemon = 0; int as_daemon = 0;
uint16_t port = 0; uint16_t port = 0;
char* socket_path = NULL; char* socket_path = NULL;
@@ -574,6 +563,11 @@ int main(int argc, char **argv) {
uid_t uid = -1; uid_t uid = -1;
int pid = -1; int pid = -1;
if(argc > 8) {
puts(USAGE);
exit(EXIT_SUCCESS);
}
for(int i = 1; i < argc; i++) { for(int i = 1; i < argc; i++) {
if(!as_daemon && argequ("-d")) as_daemon = 1; if(!as_daemon && argequ("-d")) as_daemon = 1;
else if(argequ("-p")) { else if(argequ("-p")) {
@@ -595,24 +589,28 @@ int main(int argc, char **argv) {
} }
if(chdir(cdir)) error_die("chdir"); if(chdir(cdir)) error_die("chdir");
server_sock = (!port&&socket_path)?startupunix(socket_path):startup(&port); server_sock = (!port&&socket_path)?startupunix(socket_path):startup(&port);
if(port) printf("httpd running on 0.0.0.0:%d at %s\n", port, cdir); if(port) printf("httpd running on 0.0.0.0:%d at %s\n", port, cdir);
else printf("httpd running on %s at %s\n", socket_path, cdir); else printf("httpd running on %s at %s\n", socket_path, cdir);
if(as_daemon) {
if(uid > 0) { if(uid > 0) {
setuid(uid); setuid(uid);
setgid(uid); setgid(uid);
} }
if(as_daemon) {
pid = fork(); pid = fork();
if(pid == 0) pid = fork(); if(pid == 0) pid = fork();
else return 0; else return 0;
while(pid > 0) { // 主进程监控子进程状态,如果子进程异常终止则重启之 while(pid > 0) { // 主进程监控子进程状态,如果子进程异常终止则重启之
wait(NULL); wait(NULL);
puts("Server subprocess exited. Restart..."); puts("Server subprocess exited. Restart...");
pid = fork(); pid = fork();
} }
if(pid < 0) perror("fork"); if(pid < 0) perror("fork");
else accept_client(!port); else accept_client(!port);
} else accept_client(!port); } else accept_client(!port);
}
} }