tinyhttpd ------ C 语言实现最简单的 HTTP 服务器
2016-06-23 11:17
651 查看
工作流程:
1>服务器启动,在指定端口或随机选取端口绑定httpd服务。
2>收到一个http请求时(其实就是listen端口accept的时候),派生一个线程运行accept_request函数。
3>取出http请求中method(get或post)和url,对于get方法,如果有携带参数,则query_string指针指向url中?后面的get参数。
4>格式化url到path数组,表示浏览器请求的文件路径,在tinyhttpd中服务器文件是在htdocs文件夹下。当url以/结尾,或者url是个目录,则默认在path中加上index.thml,表示访问主页。
5>如果文件路径合法,对于无参数的get请求,直接输出服务器文件到浏览器,即用http格式写到套接字上,跳到(10)。其他情况(带参数get,post方法,url为科执行文件),则调用execute_cgi函数执行cgi脚本。
6>读取整个http请求并丢弃,如果是post则找出content-length,把http状态码200写到套接字里面。
7>建立两个管道,cgi_input和cgi_output,并fork一个子进程。
8>在子进程中,把stdout重定向到cgi_output的写入端,把stdin重定向到cgi_input的读取端,关闭cgi_input的写入端和cgi_output的读取端,是指request_method的环境变量,get的话设置query_string的环境变量,post的话设置content-length的环境变量,这些环境变量都是为了给cgi脚本调用,接着用execl运行cgi程序。
9>在父进程中,关闭cgi_input的读取端和cgi_output的写入端,如果post的话,把post数据写入到cgo_input,已被重定向到stdin读取cgi_output的管道输出到客户端,等待子进程结束。
10>关闭与浏览器的链接,完成一次http请求与回应,因为http是无连接的。
1>服务器启动,在指定端口或随机选取端口绑定httpd服务。
2>收到一个http请求时(其实就是listen端口accept的时候),派生一个线程运行accept_request函数。
3>取出http请求中method(get或post)和url,对于get方法,如果有携带参数,则query_string指针指向url中?后面的get参数。
4>格式化url到path数组,表示浏览器请求的文件路径,在tinyhttpd中服务器文件是在htdocs文件夹下。当url以/结尾,或者url是个目录,则默认在path中加上index.thml,表示访问主页。
5>如果文件路径合法,对于无参数的get请求,直接输出服务器文件到浏览器,即用http格式写到套接字上,跳到(10)。其他情况(带参数get,post方法,url为科执行文件),则调用execute_cgi函数执行cgi脚本。
6>读取整个http请求并丢弃,如果是post则找出content-length,把http状态码200写到套接字里面。
7>建立两个管道,cgi_input和cgi_output,并fork一个子进程。
8>在子进程中,把stdout重定向到cgi_output的写入端,把stdin重定向到cgi_input的读取端,关闭cgi_input的写入端和cgi_output的读取端,是指request_method的环境变量,get的话设置query_string的环境变量,post的话设置content-length的环境变量,这些环境变量都是为了给cgi脚本调用,接着用execl运行cgi程序。
9>在父进程中,关闭cgi_input的读取端和cgi_output的写入端,如果post的话,把post数据写入到cgo_input,已被重定向到stdin读取cgi_output的管道输出到客户端,等待子进程结束。
10>关闭与浏览器的链接,完成一次http请求与回应,因为http是无连接的。
/* J. David's webserver */ /* This is a simple webserver. * Created November 1999 by J. David Blackstone. * CSE 4344 (Network concepts), Prof. Zeigler * University of Texas at Arlington */ /* This program compiles for Sparc Solaris 2.6. * To compile for Linux: * 1) Comment out the #include <pthread.h> line. * 2) Comment out the line that defines the variable newthread. * 3) Comment out the two lines that run pthread_create(). * 4) Uncomment the line that runs accept_request(). * 5) Remove -lsocket from the Makefile. */ #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <ctype.h> #include <strings.h> #include <string.h> #include <sys/stat.h> #include <pthread.h> #include <sys/wait.h> #include <stdlib.h> #define ISspace(x) isspace((int)(x)) #define SERVER_STRING "Server: jdbhttpd/0.1.0\r\n" void accept_request(int); //处理从套接字上监听到的一个HTTP请求,在这里可以很大一部分的体现服务器处理请求的流程 void bad_request(int); //返回给客户端这是个错误请求,HTTP状态码是400 BAD REQUEST void cat(int, FILE *); //读取服务器上某个文件写到socket套接字 void cannot_execute(int); //主要执行在处理cgi程序的处理,也是个主要函数 void error_die(const char *); //把错误信息写到perror并退出 void execute_cgi(int, const char *, const char *, const char *); //运行cgi程序的处理,也是哥主函数 int get_line(int, char *, int); //读取套接字的一行,把回车换行等情况都统一为换行符结束 void headers(int, const char *); //把HTTP相应头写到套接字 void not_found(int); //主要处理找不到请求的文件时的情况 void serve_file(int, const char *); //调用cat把服务器文件返回给浏览器 int startup(u_short *); //初始化httpd服务,包括建立套接字,绑定端口,进行监听等 void unimplemented(int); //返回给浏览器表示接收到的http请求所用的method不被支持 /**********************************************************************/ /* A request has caused a call to accept() on the server port to * return. Process the request appropriately. * Parameters: the socket connected to the client */ /**********************************************************************/ void accept_request(int client) { char buf[1024]; int numchars; char method[255]; char url[255]; char path[512]; size_t i, j; struct stat st; int cgi = 0; /* becomes true if server decides this is a CGI * program */ char *query_string = NULL; numchars = get_line(client, buf, sizeof(buf)); //读取 client端发送的数据并且 返回的参数是 numchars i = 0; j = 0; while (!ISspace(buf[j]) && (i < sizeof(method) - 1)) { method[i] = buf[j]; i++; j++; } //得到传递的参数是post 还是get方法 还是其他 method[i] = '\0'; if (strcasecmp(method, "GET") && strcasecmp(method, "POST")) { //回给浏览器表明收到的 HTTP 请求所用的 method 不被支持 unimplemented(client); return; } if (strcasecmp(method, "POST") == 0) cgi = 1; i = 0; //http请求行格式是 method urI http-version while (ISspace(buf[j]) && (j < sizeof(buf))) j++; while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf))) { url[i] = buf[j]; //包含请求行中的URI i++; j++; } url[i] = '\0'; ///获取发送数据中的URI if (strcasecmp(method, "GET") == 0) { //get方法 是将参数传递在URI中的?后面如果元素多用&进行链接 query_string = url; while ((*query_string != '?') && (*query_string != '\0')) query_string++; // get 请求? 后面为参数 if (*query_string == '?') { cgi = 1; *query_string = '\0'; query_string++; } } //格式url存储在path数组 并且html存储在 htdocs文件中 sprintf(path, "htdocs%s", url); if (path[strlen(path) - 1] == '/') strcat(path, "index.html"); //字符串进行衔接 + index.html //stat函数 根据path路径 获取文件内容 存储在 st 结构体中 成功返回0 错误返回-1 if (stat(path, &st) == -1) { while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */ numchars = get_line(client, buf, sizeof(buf)); not_found(client); } else { if ((st.st_mode & S_IFMT) == S_IFDIR) strcat(path, "/index.html"); //文件的权限 属主 属组 其它 三种任一个拥有执行权 if ((st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH) ) cgi = 1; //调用cat 把服务器文件返回给浏览器 post方法或者拥有执行权限 if (!cgi) serve_file(client, path); else execute_cgi(client, path, method, query_string) //运行cgi程序的处理,也是个主要函数 } close(client); } /**********************************************************************/ /* Inform the client that a request it has made has a problem. * Parameters: client socket */ /**********************************************************************/ void bad_request(int client) { char buf[1024]; sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "Content-type: text/html\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "\r\n"); send(client, buf, sizeof(buf), 0); sprintf(buf, "<P>Your browser sent a bad request, "); send(client, buf, sizeof(buf), 0); sprintf(buf, "such as a POST without a Content-Length.\r\n"); send(client, buf, sizeof(buf), 0); } /**********************************************************************/ /* Put the entire contents of a file out on a socket. This function * is named after the UNIX "cat" command, because it might have been * easier just to do something like pipe, fork, and exec("cat"). * Parameters: the client socket descriptor * FILE pointer for the file to cat */ /**********************************************************************/ //读取服务器上的某个文件 写到socket套接字上 void cat(int client, FILE *resource) { char buf[1024]; fgets(buf, sizeof(buf), resource); //检测流上的文件结束符 如果文件结束,则返回非0值,否则返回0,文件结束符只能被clearerr()清除。 while (!feof(resource)) { send(client, buf, strlen(buf), 0); fgets(buf, sizeof(buf), resource); } } /**********************************************************************/ /* Inform the client that a CGI script could not be executed. * Parameter: the client socket descriptor. */ /**********************************************************************/ void cannot_execute(int client) { char buf[1024]; sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-type: text/html\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "<P>Error prohibited CGI execution.\r\n"); send(client, buf, strlen(buf), 0); } /**********************************************************************/ /* Print out an error message with perror() (for system errors; based * on value of errno, which indicates system call errors) and exit the * program indicating an error. */ /**********************************************************************/ void error_die(const char *sc) { perror(sc); exit(1); } /**********************************************************************/ /* Execute a CGI script. Will need to set environment variables as * appropriate. * Parameters: client socket descriptor * path to the CGI script */ /**********************************************************************/ //运行cgi程序 也是个主函数 void execute_cgi(int client, const char *path, const char *method, const char *query_string) { //在父进程中,关闭cgi_input的读入端和cgi_output的写入端,如果post的话 //把post数据写入到cgi_input,已被重定向到stdin,读取cgi_output的管道 //输出到客户端,该管道输入是stdout,接着关闭所有管道,等待子进程结束。 char buf[1024]; int cgi_output[2]; int cgi_input[2]; //cgi_output[1] cgi_input[1] 为输入端 //cgi_input[0] cgi_output[0] 为输出端 pid_t pid; int status; int i; char c; int numchars = 1; int content_length = -1; buf[0] = 'A'; buf[1] = '\0'; //读入请求头 if (strcasecmp(method, "GET") == 0) while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */ numchars = get_line(client, buf, sizeof(buf)); else /* POST */ { numchars = get_line(client, buf, sizeof(buf)); while ((numchars > 0) && strcmp("\n", buf)) { buf[15] = '\0'; if (strcasecmp(buf, "Content-Length:") == 0) content_length = atoi(&(buf[16])); numchars = get_line(client, buf, sizeof(buf)); } if (content_length == -1) { bad_request(client); return; } } sprintf(buf, "HTTP/1.0 200 OK\r\n"); send(client, buf, strlen(buf), 0); if (pipe(cgi_output) < 0) { cannot_execute(client); return; } if (pipe(cgi_input) < 0) { cannot_execute(client); return; } if ( (pid = fork()) < 0 ) { cannot_execute(client); return; } if (pid == 0) /* child: CGI script */ { char meth_env[255]; char query_env[255]; char length_env[255]; //把stdout重定向到cgi_output的写入端 dup2(cgi_output[1], 1); //把stdin重定向到cgi_input的读入端 dup2(cgi_input[0], 0); //关闭cgi_output的读入端 和 cgi_input的 写入端 close(cgi_output[0]); close(cgi_input[1]); //设置request_method的环境变量 sprintf(meth_env, "REQUEST_METHOD=%s", method); putenv(meth_env); if (strcasecmp(method, "GET") == 0) { //设置query_string的环境变量 sprintf(query_env, "QUERY_STRING=%s", query_string); putenv(query_env); } else /* POST */ { //设置content_length的环境变量 sprintf(length_env, "CONTENT_LENGTH=%d", content_length); putenv(length_env); } //用execl运行cgi程序 execl(path, path, NULL); exit(0); } else /* parent */ { close(cgi_output[1]); close(cgi_input[0]); //关闭cgi_output的 写入端 和 cgi_input的读取端 if (strcasecmp(method, "POST") == 0) //接受post的数据 for (i = 0; i < content_length; i++) { recv(client, &c, 1, 0); write(cgi_input[1], &c, 1); //讲post数据写入cgi_input,并且重定向到stdin中 } //读取cgi_output的管道输出到客户端,该管道输入时stdout while (read(cgi_output[0], &c, 1) > 0) send(client, &c, 1, 0); //关闭管道 close(cgi_output[0]); close(cgi_input[1]); //等待子进程 waitpid(pid, &status, 0); } } /**********************************************************************/ /* Get a line from a socket, whether the line ends in a newline, * carriage return, or a CRLF combination. Terminates the string read * with a null character. If no newline indicator is found before the * end of the buffer, the string is terminated with a null. If any of * the above three line terminators is read, the last character of the * string will be a linefeed and the string will be terminated with a * null character. * Parameters: the socket descriptor * the buffer to save the data in * the size of the buffer * Returns: the number of bytes stored (excluding null) */ /**********************************************************************/ int get_line(int sock, char *buf, int size) { int i = 0; char c = '\0'; int n; while ((i < size - 1) && (c != '\n')) { //每次接受一个字符 n = recv(sock, &c, 1, 0); /* DEBUG printf("%02X\n", c); */ if (n > 0) { if (c == '\r') { n = recv(sock, &c, 1, MSG_PEEK); /* DEBUG printf("%02X\n", c); */ if ((n > 0) && (c == '\n')) recv(sock, &c, 1, 0); else c = '\n'; } buf[i] = c; i++; } else c = '\n'; } buf[i] = '\0'; return(i); } /**********************************************************************/ /* Return the informational HTTP headers about a file. */ /* Parameters: the socket to print the headers on * the name of the file */ /**********************************************************************/ //http 响应体 void headers(int client, const char *filename) { char buf[1024]; (void)filename; /* could use filename to determine file type */ strcpy(buf, "HTTP/1.0 200 OK\r\n");//响应的状态行 send(client, buf, strlen(buf), 0); strcpy(buf, SERVER_STRING); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Type: text/html\r\n"); //响应头 send(client, buf, strlen(buf), 0); strcpy(buf, "\r\n"); //响应正文段 send(client, buf, strlen(buf), 0); } /**********************************************************************/ /* Give a client a 404 not found status message. */ /**********************************************************************/ void not_found(int client) { //客户端发送的请求无法实现 char buf[1024]; //响应行 sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, SERVER_STRING); send(client, buf, strlen(buf), 0); //响应头 sprintf(buf, "Content-Type: text/html\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); //响应头和响应正文段之间有一个空行 表示响应行结束 send(client, buf, strlen(buf), 0); //响应正文段 text/html sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "<BODY><P>The server could not fulfill\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "your request because the resource specified\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "is unavailable or nonexistent.\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "</BODY></HTML>\r\n"); send(client, buf, strlen(buf), 0); } /**********************************************************************/ /* Send a regular file to the client. Use headers, and report * errors to client if they occur. * Parameters: a pointer to a file structure produced from the socket * file descriptor * the name of the file to serve */ /**********************************************************************/ void serve_file(int client, const char *filename) { FILE *resource = NULL; int numchars = 1; char buf[1024]; buf[0] = 'A'; buf[1] = '\0'; while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */ numchars = get_line(client, buf, sizeof(buf)); resource = fopen(filename, "r"); if (resource == NULL) not_found(client); else { headers(client, filename); cat(client, resource); } fclose(resource); } /**********************************************************************/ /* This function starts the process of listening for web connections * on a specified port. If the port is 0, then dynamically allo //响应正文段cate a * port and modify the original port variable to reflect the actual * port. * Parameters: pointer to variable containing the port to connect on * Returns: the socket */ /**********************************************************************/ int startup(u_short *port) { int httpd = 0; struct sockaddr_in name; //建立套接字 httpd = socket(PF_INET, SOCK_STREAM, 0); if (httpd == -1) error_die("socket"); memset(&name, 0, sizeof(name)); name.sin_family = AF_INET; name.sin_port = htons(*port); name.sin_addr.s_addr = htonl(INADDR_ANY); //绑定端口和ip if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0) error_die("bind"); if (*port == 0) /* if dynamically allocating a port */ { int namelen = sizeof(name); if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1) error_die("getsockname"); *port = ntohs(name.sin_port); } //监听 if (listen(httpd, 5) < 0) error_die("listen"); return(httpd); } /**********************************************************************/ /* Inform the client that the requested web method has not been * implemented. * Parameter: the client socket */ /**********************************************************************/ void unimplemented(int client) { //发回响应信息 http的请求方法不被接受 char buf[1024]; //返回501 错误 未实现 (Not implemented)是指Web 服务器不理解或不支持发送给它的 HTTP 数据流中找到的 HTTP 方法 sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, SERVER_STRING); send(client, buf, strlen(buf), 0); sprintf(buf, "Content-Type: text/html\r\n");//响应头 send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); //响应正文段 sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "</TITLE></HEAD>\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "</BODY></HTML>\r\n"); send(client, buf, strlen(buf), 0); } /**********************************************************************/ int main(void) { int server_sock = -1; u_short port = 0; int client_sock = -1; struct sockaddr_in client_name; int client_name_len = sizeof(client_name); pthread_t newthread; server_sock = startup(&port); printf("httpd running on port %d\n", port); while (1) { client_sock = accept(server_sock, (struct sockaddr *)&client_name, &client_name_len); //建立链接 if (client_sock == -1) error_die("accept"); /* accept_request(client_sock); */ //多线程进行控制 if (pthread_create(&newthread , NULL, accept_request, client_sock) != 0) perror("pthread_create"); } close(server_sock); return(0); }
相关文章推荐
- TCP/IP分层结构
- HTTPS 进阶
- 保护网络传输的实现
- PHP服务器信息探针可以检测网络流量,CPU,硬盘,内存使用情况,网站管理员必备
- HTTP Status 405 - HTTP method POST is not supported by this URL
- xmlns:android="http://schemas.android.com/apk/res/android" 是什么意思?
- Use Apache HttpClient to Post json data
- iOS开发——网络编程OC篇&Socket编程
- motorola单VLAN网络环境配置network.16
- Android最流行的网络框架
- 图解HTTP
- http字符编码的解释说明
- HttpClient保持登录cookie状态,继续操作
- 一次完整的HTTP事务是怎样一个过程?
- http相应get和post请求示例
- Http协议
- APPCLOUD 判断网络
- linux查看tcp的状态命令:
- 在ubuntu16.04 下安装haproxy 1.5.11 做tcp负载均衡
- HTTP POST GET 本质区别详解