http://blog.csdn.net/jcjc918/article/details/42129311
tinyhttpd 是一个不到 500 行的超轻量型 Http Server,用来学习非常不错,可以帮助我们真正理解服务器程序的本质。
看完所有源码,真的感觉有很大收获,无论是 unix 的编程,还是 GET/POST 的 Web 处理流程,都清晰了不少。废话不说,开始我们的 Server 探索之旅。
(水平有限,如有错误之处,欢迎指正)
项目主页
http://sourceforge.net/projects/tinyhttpd/
主要函数
这是所有函数的声明:
- void accept_request(int);
- void bad_request(int);
- void cat(int, FILE *);
- void cannot_execute(int);
- void error_die(const char *);
- void execute_cgi(int, const char *, const char *, const char *);
- int get_line(int, char *, int);
- void headers(int, const char *);
- void not_found(int);
- void serve_file(int, const char *);
- int startup(u_short *);
- void unimplemented(int);
先简单地解释每个函数的作用:
accept_request: 处理从套接字上监听到的一个 HTTP 请求,在这里可以很大一部分地体现服务器处理请求流程。
bad_request: 返回给客户端这是个错误请求,HTTP 状态吗 400 BAD REQUEST.
cat: 读取服务器上某个文件写到 socket 套接字。
cannot_execute: 主要处理发生在执行 cgi 程序时出现的错误。
error_die: 把错误信息写到 perror 并退出。
execute_cgi: 运行 cgi 程序的处理,也是个主要函数。
get_line: 读取套接字的一行,把回车换行等情况都统一为换行符结束。
headers: 把 HTTP 响应的头部写到套接字。
not_found: 主要处理找不到请求的文件时的情况。
sever_file: 调用 cat 把服务器文件返回给浏览器。
startup: 初始化 httpd 服务,包括建立套接字,绑定端口,进行监听等。
unimplemented: 返回给浏览器表明收到的 HTTP 请求所用的 method 不被支持。
建议源码阅读顺序: main -> startup -> accept_request -> execute_cgi, 通晓主要工作流程后再仔细把每个函数的源码看一看。
工作流程
(1) 服务器启动,在指定端口或随机选取端口绑定 httpd 服务。
(2)收到一个 HTTP 请求时(其实就是 listen 的端口 accpet 的时候),派生一个线程运行 accept_request 函数。
(3)取出 HTTP 请求中的 method (GET 或 POST) 和 url,。对于 GET 方法,如果有携带参数,则 query_string 指针指向 url 中 ? 后面的 GET 参数。
(4) 格式化 url 到 path 数组,表示浏览器请求的服务器文件路径,在 tinyhttpd 中服务器文件是在 htdocs 文件夹下。当 url 以 / 结尾,或 url 是个目录,则默认在 path 中加上 index.html,表示访问主页。
(5)如果文件路径合法,对于无参数的 GET 请求,直接输出服务器文件到浏览器,即用 HTTP 格式写到套接字上,跳到(10)。其他情况(带参数 GET,POST 方式,url 为可执行文件),则调用 excute_cgi 函数执行 cgi 脚本。
(6)读取整个 HTTP 请求并丢弃,如果是 POST 则找出 Content-Length. 把 HTTP 200 状态码写到套接字。
(7) 建立两个管道,cgi_input 和 cgi_output, 并 fork 一个进程。
(8) 在子进程中,把 STDOUT 重定向到 cgi_outputt 的写入端,把 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 数据写入 cgi_input,已被重定向到 STDIN,读取 cgi_output 的管道输出到客户端,该管道输入是 STDOUT。接着关闭所有管道,等待子进程结束。这一部分比较乱,见下图说明:
图 1 管道初始状态
图 2 管道最终状态
(10) 关闭与浏览器的连接,完成了一次 HTTP 请求与回应,因为 HTTP 是无连接的。
注释版源码
源码已写了注释,放在 Github: 这里
懒得跳转的同学看下面....
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #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);
- void bad_request(int);
- void cat(int, FILE *);
- void cannot_execute(int);
- void error_die(const char *);
- void execute_cgi(int, const char *, const char *, const char *);
- int get_line(int, char *, int);
- void headers(int, const char *);
- void not_found(int);
- void serve_file(int, const char *);
- int startup(u_short *);
- void unimplemented(int);
-
-
-
-
-
-
- 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;
- char *query_string = NULL;
-
-
- numchars = get_line(client, buf, sizeof(buf));
- i = 0; j = 0;
-
- while (!ISspace(buf[j]) && (i < sizeof(method) - 1))
- {
- method[i] = buf[j];
- i++; j++;
- }
- method[i] = '\0';
-
-
- if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
- {
- unimplemented(client);
- return;
- }
-
-
- if (strcasecmp(method, "POST") == 0)
- cgi = 1;
-
-
- i = 0;
- while (ISspace(buf[j]) && (j < sizeof(buf)))
- j++;
- while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))
- {
-
- url[i] = buf[j];
- i++; j++;
- }
- url[i] = '\0';
-
-
- if (strcasecmp(method, "GET") == 0)
- {
-
- query_string = url;
- while ((*query_string != '?') && (*query_string != '\0'))
- query_string++;
-
- if (*query_string == '?')
- {
-
- cgi = 1;
- *query_string = '\0';
- query_string++;
- }
- }
-
-
- sprintf(path, "htdocs%s", url);
-
- if (path[strlen(path) - 1] == '/')
- strcat(path, "index.html");
-
- if (stat(path, &st) == -1) {
-
- while ((numchars > 0) && strcmp("\n", buf))
- 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;
-
- if (!cgi)
- serve_file(client, path);
- else
- execute_cgi(client, path, method, query_string);
- }
-
-
- close(client);
- }
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
-
-
- void cat(int client, FILE *resource)
- {
- char buf[1024];
-
-
- fgets(buf, sizeof(buf), resource);
- while (!feof(resource))
- {
- send(client, buf, strlen(buf), 0);
- fgets(buf, sizeof(buf), resource);
- }
- }
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
- void error_die(const char *sc)
- {
-
- perror(sc);
- exit(1);
- }
-
-
-
-
-
-
-
- void execute_cgi(int client, const char *path, const char *method, const char *query_string)
- {
- char buf[1024];
- int cgi_output[2];
- int cgi_input[2];
- 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))
- numchars = get_line(client, buf, sizeof(buf));
- else
- {
-
- 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)
- {
- char meth_env[255];
- char query_env[255];
- char length_env[255];
-
-
- dup2(cgi_output[1], 1);
-
- dup2(cgi_input[0], 0);
-
- close(cgi_output[0]);
- close(cgi_input[1]);
-
- sprintf(meth_env, "REQUEST_METHOD=%s", method);
- putenv(meth_env);
- if (strcasecmp(method, "GET") == 0) {
-
- sprintf(query_env, "QUERY_STRING=%s", query_string);
- putenv(query_env);
- }
- else {
-
- sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
- putenv(length_env);
- }
-
- execl(path, path, NULL);
- exit(0);
- } else {
-
- close(cgi_output[1]);
- close(cgi_input[0]);
- if (strcasecmp(method, "POST") == 0)
-
- for (i = 0; i < content_length; i++) {
- recv(client, &c, 1, 0);
-
- write(cgi_input[1], &c, 1);
- }
-
- 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);
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
-
- if (n > 0)
- {
-
- if (c == '\r')
- {
-
- n = recv(sock, &c, 1, MSG_PEEK);
-
-
- 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);
- }
-
-
-
-
-
-
- void headers(int client, const char *filename)
- {
- char buf[1024];
- (void)filename;
-
-
- 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);
- }
-
-
-
-
- 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);
- 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);
- }
-
-
-
-
-
-
-
-
- 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))
- 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);
- }
-
-
-
-
-
-
-
-
-
- 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);
- if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
- error_die("bind");
-
- if (*port == 0)
- {
- 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);
- }
-
-
-
-
-
-
- void unimplemented(int client)
- {
- char buf[1024];
-
-
- 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");
-
-
- if (pthread_create(&newthread , NULL, accept_request, client_sock) != 0)
- perror("pthread_create");
- }
-
- close(server_sock);
-
- return(0);
- }
编译运行
这里我们如何让这个服务器跑起来呢?看评论区应该不少人遇到问题,这里我简单说下。
首先,需要修改 Makefile 文件,如果直接执行 make 的话,你会遇到这个错误:cannot find -lsocket。解决方法简单说就是在 linux 系统中没有这样一个库,而且这个库在 linux 中的实现位于 libc 中,编译时被默认包含,所以可以直接在 Makefile 中去掉 -lsocket。详见:stackoverflow
另外,在 htdocs 文件下,有 cgi 的程序和 html 代码,cgi 是用 perl 写的,但文件中声明的 perl 执行程序位置在我这是错的,我这里 perl 脚本位于 /usr/bin 中(用 which perl 可以查看),所以把 cgi 文件中的第一行改为:
现在都没问题了。mkae 编译后,用 ./httpd 运行,在浏览器中输入 127.0.0.1:端口,就可以看到网页了: