1
0
mirror of https://github.com/fumiama/simple-http-server.git synced 2026-06-09 20:40:41 +08:00

修正cgi,优化代码结构

This commit is contained in:
源文雨
2021-08-07 17:46:08 +08:00
parent 1b7e8a5119
commit fe8277a3bf
2 changed files with 324 additions and 349 deletions

View File

@@ -20,7 +20,6 @@ A necessary subset of `HTTP 1.0` with following options of request header being
- 200 OK - 200 OK
- 400 BAD REQUEST - 400 BAD REQUEST
- 404 NOT FOUND - 404 NOT FOUND
- 414 Request-URI Too Long
- 500 Internal Server Error - 500 Internal Server Error
- 501 Method Not Implemented - 501 Method Not Implemented

174
server.c
View File

@@ -54,11 +54,10 @@ static void execute_cgi(int, int, const HTTP_REQUEST*);
static uint32_t get_file_size(const char *, int); static uint32_t get_file_size(const char *, int);
static int get_line(int, char *, int); static int get_line(int, char *, int);
static void handle_quit(int); static void handle_quit(int);
static void headers(int, const char *); static int headers(int, const char *);
static void not_found(int); static void not_found(int);
static void serve_file(int, const char *); static void serve_file(int, const char *);
static int startup(u_int16_t *); static int startup(u_int16_t *);
static void toolong(int);
static void unimplemented(int); static void unimplemented(int);
/**********************************************************************/ /**********************************************************************/
@@ -70,61 +69,39 @@ static void unimplemented(int);
/* read & discard headers */ /* read & discard headers */
#define discard(client) \ #define discard(client) \
while((numchars > 0) && strcmp("\n", buf)) numchars = get_line(client, buf, sizeof(buf)) while((numchars > 0) && strcmp("\n", buf)) numchars = get_line(client, buf, sizeof(buf))
#define methodequ(str, method) (*(uint32_t*)(method) == *(uint32_t*)(str))
#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 getmethod(method_type) ((method_type == GET)?"GET":"POST")
static void accept_request(void *cli) { static void accept_request(void *cli) {
pthread_detach(pthread_self()); int client = (int)cli;
int client =(int)cli; char buf[1024], *path, *query_string;
char buf[1024]; int numchars, cgi = 0, j; // cgi becomes true if server decides this is a CGI program
int numchars;
char method[255];
char url[255];
char path[512];
size_t i, j;
struct stat st; struct stat st;
int cgi = 0; /* becomes true if server decides this is a CGI program */
char *query_string = NULL;
METHOD_TYPE method_type; METHOD_TYPE method_type;
pthread_detach(pthread_self());
numchars = get_line(client, buf, sizeof(buf)); numchars = get_line(client, buf, sizeof(buf));
i = 0;
j = 0; j = 0;
while(!ISspace(buf[j]) &&(i < sizeof(method) - 1)) { skiptext(buf, j, numchars - 1);
method[i] = buf[j]; buf[j] = '\0';
i++;
j++;
}
method[i] = '\0';
if(strcasecmp(method, "GET") == 0) { if(methodequ(buf, "GET")) method_type = GET;
method_type = GET; else if(methodequ(buf, "POST")) {
}
if(strcasecmp(method, "POST") == 0) {
if(method_type == GET) {
discard(client);
unimplemented(client);
return;
} else {
cgi = 1; cgi = 1;
method_type = POST; method_type = POST;
} }
}
i = 0; skipspace(buf, j, numchars - 1);
while(ISspace(buf[j]) && (j < sizeof(buf))) j++; path = buf + j + 1;
for(; !ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)); i++, j++) { skiptext(buf, j, numchars - 1);
url[i] = buf[j]; buf[j] = 0;
}
if(!ISspace(buf[j])) {
discard(client);
toolong(client);
return;
}
url[i] = '\0';
if(method_type == GET) { if(method_type == GET) {
query_string = url; query_string = path;
while((*query_string != '?') &&(*query_string != '\0')) query_string++; while((*query_string != '?') && (*query_string != '\0')) query_string++;
if(*query_string == '?') { if(*query_string == '?') {
cgi = 1; cgi = 1;
*query_string = '\0'; *query_string = '\0';
@@ -132,20 +109,32 @@ static void accept_request(void *cli) {
} }
} }
char* url_start = url + 1; // skip possible ../
//skip possible ../ while((*path == '.' || *path == '/' || *path == '#') && *path != 0) path++;
while((*url_start == '.' || *url_start == '/' || *url_start == '#') && *url_start != 0) url_start++; path -= 2;
path[0] = '.'; path[1] = '/'; path[2] = 0; path[0] = '.'; path[1] = '/';
if(*url_start) strncat(path, url_start, 499);
printf("%s %s with query '%s': ", method, path, query_string); printf("[%s] <%s> (%s) = ", getmethod(method_type), path, query_string);
//花括号不可省略 // 花括号不可省略
if(stat(path, &st) == -1) { if(stat(path, &st) == -1) {
discard(client); discard(client);
not_found(client); not_found(client);
} else { } else {
int pathlen = strlen(path) + 1;
char* path_heap = malloc(pathlen + 11); // 11 is for possible /index.html
memcpy(path_heap, path, pathlen);
printf("<%d> ", pathlen);
path = path_heap;
char* query_heap = query_string;
int query_length = strlen(query_heap) + 1;
query_string = malloc(query_length);
memcpy(query_string, query_heap, query_length);
printf("(%d) ", query_length);
if((st.st_mode & S_IFMT) == S_IFDIR) { if((st.st_mode & S_IFMT) == S_IFDIR) {
strcat(path, "/index.html"); strcat(path, "/index.html");
//花括号不可省略 // 花括号不可省略
if(stat(path, &st) == -1) { if(stat(path, &st) == -1) {
discard(client); discard(client);
not_found(client); not_found(client);
@@ -154,7 +143,7 @@ static void accept_request(void *cli) {
} }
} }
int content_length = 0; int content_length = 0;
if((st.st_mode & S_IXUSR) ||(st.st_mode & S_IXGRP) ||(st.st_mode & S_IXOTH)) cgi = 1; cgi &= ((st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH));
while((numchars > 0) && strcmp("\n", buf)) { while((numchars > 0) && strcmp("\n", buf)) {
numchars = get_line(client, buf, sizeof(buf)); numchars = get_line(client, buf, sizeof(buf));
if(!content_length && strcasestr(buf, "Content-Length: ")) { if(!content_length && strcasestr(buf, "Content-Length: ")) {
@@ -166,11 +155,12 @@ static void accept_request(void *cli) {
else { else {
HTTP_REQUEST request; HTTP_REQUEST request;
request.path = path; request.path = path;
request.method = method; request.method = getmethod(method_type);
request.method_type = method_type; request.method_type = method_type;
request.query_string = query_string; request.query_string = query_string;
execute_cgi(client, content_length, &request); execute_cgi(client, content_length, &request);
} }
free(path); free(query_string);
} }
close(client); close(client);
} }
@@ -182,6 +172,7 @@ static void accept_request(void *cli) {
#define HTTP400 "HTTP/1.0 400 BAD REQUEST\r\nContent-Type: text/html\r\n\r\n<P>Your browser sent a bad request, such as a POST without a Content-Length.\r\n" #define HTTP400 "HTTP/1.0 400 BAD REQUEST\r\nContent-Type: text/html\r\n\r\n<P>Your browser sent a bad request, such as a POST without a Content-Length.\r\n"
static void bad_request(int client) { static void bad_request(int client) {
send(client, HTTP400, sizeof(HTTP400)-1, 0); send(client, HTTP400, sizeof(HTTP400)-1, 0);
puts("400 BAD REQUEST.");
} }
/**********************************************************************/ /**********************************************************************/
@@ -201,7 +192,7 @@ static void cat(int client, FILE *resource) {
rewind(resource); rewind(resource);
sendfile(client, fileno(resource), &len, file_size); sendfile(client, fileno(resource), &len, file_size);
#endif #endif
printf("Send %lu bytes.\n", len); printf("Sendfile: %lu bytes.\n", len);
} }
/**********************************************************************/ /**********************************************************************/
@@ -211,6 +202,7 @@ static void cat(int client, FILE *resource) {
#define HTTP500 "HTTP/1.0 500 Internal Server Error\r\nContent-Type: text/html\r\n\r\n<P>Internal Server Error.\r\n" #define HTTP500 "HTTP/1.0 500 Internal Server Error\r\nContent-Type: text/html\r\n\r\n<P>Internal Server Error.\r\n"
static void cannot_execute(int client) { static void cannot_execute(int client) {
send(client, HTTP500, sizeof(HTTP500)-1, 0); send(client, HTTP500, sizeof(HTTP500)-1, 0);
puts("500 Internal Server Error.");
} }
/**********************************************************************/ /**********************************************************************/
@@ -230,12 +222,10 @@ 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]; int cgi_output[2], cgi_input[2], i;
int cgi_input[2];
pid_t pid; pid_t pid;
int i;
if(pipe(cgi_output) < 0 || pipe(cgi_input) < 0 ||(pid = fork()) < 0) cannot_execute(client); if(pipe(cgi_output) < 0 || pipe(cgi_input) < 0 || (pid = fork()) < 0) cannot_execute(client);
/* child: CGI script */ /* child: CGI script */
else if(pid == 0) { else if(pid == 0) {
char env[255]; char env[255];
@@ -285,13 +275,13 @@ static void execute_cgi(int client, int content_length, const HTTP_REQUEST* requ
} }
uint32_t cnt = 0; uint32_t cnt = 0;
char* p =(char*)&cnt; char* p = (char*)&cnt;
while(p -(char*)&cnt < sizeof(uint32_t)) { while(p - (char*)&cnt < sizeof(uint32_t)) {
int offset = read(cgi_output[0], p, sizeof(uint32_t)); int offset = read(cgi_output[0], p, sizeof(uint32_t));
if(offset > 0) p += offset; if(offset > 0) p += offset;
else cannot_execute(client); else cannot_execute(client);
} }
printf("cgi msg cnt: %u bytes.\n", cnt); printf("CGI msg len: %u bytes.\n", cnt);
if(cnt > 0) { if(cnt > 0) {
int len = 0; int len = 0;
#if __APPLE__ #if __APPLE__
@@ -311,7 +301,7 @@ static void execute_cgi(int client, int content_length, const HTTP_REQUEST* requ
len += delta; len += delta;
} }
#endif #endif
printf("cgi send %d bytes\n", len); printf("CGI send %d bytes\n", len);
} }
close(cgi_output[0]); close(cgi_output[0]);
close(cgi_input[1]); close(cgi_input[1]);
@@ -328,13 +318,10 @@ static uint32_t get_file_size(const char *filepath, int client) {
uint32_t sz; uint32_t sz;
if(!stat(filepath, &statbuf)) { if(!stat(filepath, &statbuf)) {
sz = statbuf.st_size; sz = statbuf.st_size;
printf("file size: %u\n", sz); printf("[%u] - ", sz);
return sz; return sz;
} }
else { else return 0;
cannot_execute(client);
error_die("stat");
}
} }
/**********************************************************************/ /**********************************************************************/
@@ -355,25 +342,21 @@ static int get_line(int sock, char *buf, int size) {
char c = '\0'; char c = '\0';
int n; int n;
while((i < size - 1) &&(c != '\n')) { while((i < size - 1) && (c != '\n')) {
n = recv(sock, &c, 1, 0); n = recv(sock, &c, 1, 0);
/* DEBUG printf("%02X\n", c); */
if(n > 0) { if(n > 0) {
if(c == '\r') { if(c == '\r') {
n = recv(sock, &c, 1, MSG_PEEK); n = recv(sock, &c, 1, MSG_PEEK);
/* DEBUG printf("%02X\n", c); */ /* DEBUG printf("%02X\n", c); */
if((n > 0) &&(c == '\n')) if((n > 0) && (c == '\n')) recv(sock, &c, 1, 0);
recv(sock, &c, 1, 0);
else c = '\n'; else c = '\n';
} }
buf[i] = c; buf[i++] = c;
i++; } else c = '\n';
}
else c = '\n';
} }
buf[i] = '\0'; buf[i] = '\0';
return(i); return i;
} }
/**********************************************************************/ /**********************************************************************/
@@ -400,16 +383,19 @@ static void handle_quit(int signo) {
#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"
static void headers(int client, const char *filepath) { static int headers(int client, const char *filepath) {
char buf[1024]; char buf[1024];
uint32_t offset = 0; uint32_t offset = 0;
uint32_t extpos = strlen(filepath) - 4; uint32_t extpos = strlen(filepath) - 4;
uint32_t file_size = get_file_size(filepath, client);
if(file_size) {
ADD_HERDER(HTTP200 SERVER_STRING); ADD_HERDER(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_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_HERDER_PARAM(CONTENT_LEN "\r\n", get_file_size(filepath, client)); ADD_HERDER_PARAM(CONTENT_LEN "\r\n", file_size);
send(client, buf, offset, 0); send(client, buf, offset, 0);
puts("200 OK."); puts("200 OK.");
return 1;
} else return 0;
} }
/**********************************************************************/ /**********************************************************************/
@@ -432,12 +418,11 @@ static void serve_file(int client, const char *filename) {
FILE *resource = NULL; FILE *resource = NULL;
resource = fopen(filename, "rb"); resource = fopen(filename, "rb");
if(resource == NULL) not_found(client); if(resource) {
else { if(headers(client, filename)) cat(client, resource);
headers(client, filename); else not_found(client);
cat(client, resource);
}
fclose(resource); fclose(resource);
} else not_found(client);
} }
/**********************************************************************/ /**********************************************************************/
@@ -486,16 +471,6 @@ static int startup(uint16_t *port) {
return(httpd); return(httpd);
} }
/**********************************************************************/
/* Inform the client that the requested web method has not been
* implemented.
* Parameter: the client socket */
/**********************************************************************/
#define HTTP414 "HTTP/1.0 414 Request-URI Too Long\r\n" SERVER_STRING "Content-Type: text/html\r\n\r\n<HTML><HEAD><TITLE>Request-URI Too Long\r\n</TITLE></HEAD>\r\n<BODY><P>HTTP request url length is over 254 chars.\r\n</BODY></HTML>\r\n"
static void toolong(int client) {
send(client, HTTP414, sizeof(HTTP414)-1, 0);
}
/**********************************************************************/ /**********************************************************************/
/* Inform the client that the requested web method has not been /* Inform the client that the requested web method has not been
* implemented. * implemented.
@@ -504,13 +479,14 @@ static void toolong(int client) {
#define HTTP501 "HTTP/1.0 501 Method Not Implemented\r\n" SERVER_STRING "Content-Type: text/html\r\n\r\n<HTML><HEAD><TITLE>Method Not Implemented\r\n</TITLE></HEAD>\r\n<BODY><P>HTTP request method not supported.\r\n</BODY></HTML>\r\n" #define HTTP501 "HTTP/1.0 501 Method Not Implemented\r\n" SERVER_STRING "Content-Type: text/html\r\n\r\n<HTML><HEAD><TITLE>Method Not Implemented\r\n</TITLE></HEAD>\r\n<BODY><P>HTTP request method not supported.\r\n</BODY></HTML>\r\n"
static void unimplemented(int client) { static void unimplemented(int client) {
send(client, HTTP501, sizeof(HTTP501)-1, 0); send(client, HTTP501, sizeof(HTTP501)-1, 0);
puts("501 Method Not Implemented.");
} }
/**********************************************************************/ /**********************************************************************/
/* simple-http-server /* simple-http-server
* Usage: simple-http-server -d port chdir * Usage: simple-http-server [-d] [-p <port>] [-r <rootdir>] [-u <uid>]
/**********************************************************************/ /**********************************************************************/
#define ACCEPT_CLI() {\ #define accept_client(client_sock, server_sock, client_name, client_name_len, newthread) {\
while(1) {\ while(1) {\
client_sock = accept(server_sock,(struct sockaddr *)&client_name, &client_name_len);\ client_sock = accept(server_sock,(struct sockaddr *)&client_name, &client_name_len);\
if(client_sock == -1) break;\ if(client_sock == -1) break;\
@@ -555,13 +531,13 @@ int main(int argc, char **argv) {
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_CLI(); else accept_client(client_sock, server_sock, client_name, client_name_len, newthread);
} else ACCEPT_CLI(); } else accept_client(client_sock, server_sock, client_name, client_name_len, newthread);
} }
} }