Tinyhttpd
tinyhttpd是一个超轻量型Http Server,使用C语言开发,全部代码只有502行(包括注释),附带一个简单的Client,可以通过阅读这段代码理解一个 Http Server 的本质
/* 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 <winsock2.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>
//isspace 若参数c为空格字符,则返回TRUE,否则返回NULL(0) 此为宏定义,非真正函数。
#define ISspace(x) isspace((int)(x))
#define SERVER_STRING "Server: jdbhttpd/0.1.0\r\n"
//处理从套接字上监听到的一个HTTP请求,在这里可以很大一部分的体现服务器处理请求的流程
void accept_request(int);
//返回给客户端这是个错误请求,HTTP状态码是400 BAD REQUEST
void bad_request(int);
//读取服务器上某个文件写到socket套接字
void cat(int, FILE *);
//主要执行在处理cgi程序的处理,也是个主要函数
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);
//把HTTP相应头写到套接字
void headers(int, const char *);
//主要处理找不到请求的文件时的情况
void not_found(int);
//调用cat把服务器文件返回给浏览器
void serve_file(int, const char *);
//初始化httpd服务,包括建立套接字,绑定端口,进行监听等
int startup(u_short *);
//返回给浏览器表示接收到的http请求所用的method不被支持
void unimplemented(int);
/**********************************************************************/
/* 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
http 服务响应返回
而Post 方法通过 HTTP post 机制,将表单内各字段名称与其内容放置在 HTML 表头(header)内
一起传送给服务器端交由 action 属性能所指的程序处理,
该程序会通过标准输入(stdin)方式,将表单的数据读出并加以处理
*/
/**********************************************************************/
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; //struct stat这个结构体是用来描述一个linux系统文件系统中的文件属性的结构。
int cgi = 0; /* becomes true if server decides this is a CGI
* program */
char *query_string = NULL;
//获取第一行客户端的请求 GET / HTTP/1.1 类似这样的
//读取 client端发送的数据并且 返回的参数是 numchars,get_line将所有换行回车转为换行
numchars = get_line(client, buf, sizeof(buf));
i = 0; j = 0;
//ISspace判断是否为空格
//获取第一个单词,一般为GET或POST 两种请求方法,此处循环查询直到空格,就得到了GET或POST这两个字符串
while (!ISspace(buf[j]) && (i < sizeof(method) - 1))
{
method[i] = buf[j];
i++; j++;
}
method[i] = '\0';//结尾增加结束符
//如果不是GET或POST方法的,那么就回复一个不支持的请求方法页面。strcasecmp用忽略大小写比较字符串.
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
{
//回给浏览器表明收到的 HTTP 请求所用的 method 不被支持
unimplemented(client);
return;
}
//如果是使用POST方法,那么就一定是cgi程序
if (strcasecmp(method, "POST") == 0)
cgi = 1;
i = 0;
//http请求行格式是 method urI http-version,
//前面j已定位到method之后的空格,这里找到空格之后第一个不是空的位置
while (ISspace(buf[j]) && (j < sizeof(buf)))
j++;
// GET / HTTP/1.1 接下来是取第二个字符串,第二个串是此次请求的页面地址url
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))
{
url[i] = buf[j];//包含请求行中的URI
i++; j++;
}
url[i] = '\0';
//如果是GET方法,那么需要从?分解开来,GET方法和POST方法是有点区别的,GET方法是通过URL请求来传递用户的数据,
//将表单等各个字段名称与内容,以成对的字符串进行连接来传递参数的。
//例如 http://www.baidu.com/s?wd=cnblogs 这个URL就是使用百度搜索cnblogs的URL地址,
//baidu搜索怎么知道我在输入框中输入的是什么数据?就是通过这样的一个参数来告诉它的。一般参数都是在?(问号)后面的。
if (strcasecmp(method, "GET") == 0)///获取发送数据中的URI//get方法 是将参数传递在URI中的?后面如果元素多用&进行链接
{
query_string = url;//将首地址赋给query_string
//一直读,直到遇到问号
while ((*query_string != '?') && (*query_string != '\0'))
query_string++;
//如果有问号,就表示可能要调用cgi程序了,不是简单的静态HTML页面的。// get 请求? 后面为参数
if (*query_string == '?')
{
cgi = 1;
*query_string = '\0';
query_string++;
}
}
//htdocs这个是web服务器的主目录
//格式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) {{//当取文件内容失败时
//可能的问题是没有该文件,或是权限什么的问题,具体失败的原因可以查看errno
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));//取请求的后面所有行,返回给客户端
not_found(client);
}
else//取文件内容成功时
{
//如果该文件名对应的是一个目录,那么就访问该目录下的默认主页index.html
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)
//如果不是cgi程序,而是一个简单的静态页面//调用cat 把服务器文件返回给浏览器 post方法或者拥有执行权限
serve_file(client, path);
else//执行一个cgi程序
execute_cgi(client, path, method, query_string);
}
close(client);
}
/**********************************************************************/
/* Inform the client that a request it has made has a problem.
* Parameters: client socket
http 返回客户端请求错误
*/
/**********************************************************************/
void bad_request(int client)
{
char buf[1024];
//按照http协议返回错误的请求消息
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];
//取文件消息,发回socket
fgets(buf, sizeof(buf), resource);
while (!feof(resource))
{//检测流上的文件结束符 如果文件结束,则返回非0值,否则返回0,文件结束符只能被clearerr()清除。
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.
通知这个客户端,CGI脚本不能运行
*/
/**********************************************************************/
void cannot_execute(int client)
{
char buf[1024];
//返回500错误,服务器问题
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脚本,execute_cgi这个函数,用来执行cgi程序的
//在父进程中,关闭cgi_input的读入端和cgi_output的写入端,如果post的话
//把post数据写入到cgi_input,已被重定向到stdin,读取cgi_output的管道
//输出到客户端,该管道输入是stdout,接着关闭所有管道,等待子进程结束。
*/
/**********************************************************************/
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';
//同什么的serve_file函数,对那些请求头进行忽略
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';
//但是考虑到在请求头后面还有信息要读,而信息的大小就在这里,HTTP的post请求里有Content-Length参数。
//这个Content-Length后面,也就是上面截图是所说的。看了这个代码是不是对刚才说的有了更深的理解了
if (strcasecmp(buf, "Content-Length:") == 0)
content_length = atoi(&(buf[16]));//获取后面字符的个数
numchars = get_line(client, buf, sizeof(buf));
}
//注意到了这里后Post请求头后面的附带信息还没有读出来,要在下面才读取。
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;
}
//子进程中,用刚才初始化的管道替换掉标准输入标准输出,将请求参数加到环境变量中,调用execl执行cgi程序获得输出。
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];
dup2(cgi_output[1], 1);;//将文件描述符为1(stdout)的句柄复制到output中
dup2(cgi_input[0], 0);//将文件描述符为0(stdin)的句柄复制到input中
close(cgi_output[0]);//关闭output的读端
close(cgi_input[1]);//关闭input的写端
sprintf(meth_env, "REQUEST_METHOD=%s", method);
putenv(meth_env);//putenv保存到环境变量中
if (strcasecmp(method, "GET") == 0) {
sprintf(query_env, "QUERY_STRING=%s", query_string);
putenv(query_env);
}
else { /* POST */
sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
putenv(length_env);
}
execl(path, path, NULL);;
//保存在环境变量中的数据,还有parent进行的write到cgi_input[1]中的数据,都是存在的,
//可以在cgi程序本身中进行判断。看起来有点复杂,我到时候实现就实现个简单的吧。
//原来的代码就是那样,但据说好像是错的。
//应该是:execl(path,参数列表,NULL);
//而参数列表对于get方法就是query_string,
//而对于post方法就没有参数,它的参数是在父进程中第80行处通过stdin进行输入,所以cgi程序要手动从控制台stdin读取数据
exit(0);
} else { /* parent */
close(cgi_output[1]);//关闭output的写端
close(cgi_input[0]);//关闭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);//读取到的信息一个一个字符写到input的写端
}
while (read(cgi_output[0], &c, 1) > 0)//循环读取output的读端,然后发送个客户端,注意这里接收的是cgi程序的输出(也就是打印在stdin上的数据)
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)
替换http协议中的\r\n为\n,将所有单独的\r替换为\n,最后加一个字符串结束符\0
将取到的第一行放入buf
*/
/**********************************************************************/
int get_line(int sock, char *buf, int size)
{
int i = 0;
char c = '\0';
int n;
while ((i < size - 1) && (c != '\n'))
{
//接收socket内容(复制tcp的socket缓存中的数据移除数据)
n = recv(sock, &c, 1, 0);
/* DEBUG printf("%02X\n", c); */
//如果接收内容不为空
if (n > 0)
{
if (c == '\r')
{
//复制tcp的缓存中的数据,但不移除数据(查看数据)
n = recv(sock, &c, 1, MSG_PEEK);
/* DEBUG printf("%02X\n", c); */
//如果是\r\n,那么就替换成\n,如果只是\r,那么替换为\n,因为http协议用\r\n来换行
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.
给客户端一个404,表示没找到
*/
/**********************************************************************/
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);
}
/**********************************************************************/
/* 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
发送文件给客户端,用头和包体
对一个简单的HTML静态页面进行返回
*/
/**********************************************************************/
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));
//取得除第一行之后的每行
//根据GET 后面的文件名,将文件打开。
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 allocate 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
在某个端口上启动一个进程用来监听web连接,如果端口是0,那么自动分配一个端口
修改原始端口变量反射到一个真实的端口
getsockname函数是,如果传进来的port为0,那么就前面的bind就会失败,
所以要使用getsockname函数来获取一个当前可用的可连接的Socket套接字的名字。此时返回的端口就是随机的。
*/
/**********************************************************************/
int startup(u_short *port)
{
int httpd = 0;
struct sockaddr_in name;
//定义一个socket
httpd = socket(PF_INET, SOCK_STREAM, 0);
if (httpd == -1)
error_die("socket");
memset(&name, 0, sizeof(name));
name.sin_family = AF_INET;
//htons是将整型变量从主机字节顺序转变成网络字节顺序
name.sin_port = htons(*port);
//将主机数转换成无符号长整型的网络字节顺序。本函数将一个32位数从主机字节顺序转换成网络字节顺序。
name.sin_addr.s_addr = htonl(INADDR_ANY);
//初始化,对于SOCK_DGRAM(udp)和SOCK_STREAM(tcp)类套接口,
//名字由三部分组成:主机地址,协议号(显式设置为UDP和TCP)和用以区分应用的端口号
//如果一个应用并不关心分配给它的地址,则可将Internet地址设置为INADDR_ANY,或将端口号置为0。
//如果Internet地址段为INADDR_ANY,则可使用任意网络接口,且在有多种主机环境下可简化编程
if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)//绑定socket
error_die("bind");
if (*port == 0) /* if dynamically allocating a port */
{
int namelen = sizeof(name);
//getsockname()函数用于获取一个套接字的名字。它用于一个已捆绑或已连接套接字s,本地地址将被返回
//本调用特别适用于如下情况:未调用bind()就调用了connect(),这时唯有getsockname()调用可以获知系统内定的本地地址
if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
error_die("getsockname");
//网络字节顺序转为主机字节顺序
*port = ntohs(name.sin_port);
}
//listen函数使用主动连接套接字变为被连接套接口,使得一个进程可以接受其它进程的请求,从而成为一个服务器进程
//连接请求队列(queue of pending connections)的最大长度
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)
{
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);
}
/**********************************************************************/
/*
*从主函数我们可以知道,这个服务器是对于每一个客户端的连接都采用一个线程对其处理。
startup函数是对指定的端口进行socket的创建,绑定,监听。
*/
/**********************************************************************/
int main(void)
{
int server_sock = -1;
u_short port = 0;
int client_sock = -1;
//声明一个socket
struct sockaddr_in client_name;
int client_name_len = sizeof(client_name);
//定义新进程
pthread_t newthread;
//建立httpd的socket监听
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);
}
//GET,POST的区别 http://blog.sina.com.cn/s/blog_50e4caf701009eys.html
//什么是CGI http://www.doc88.com/p-173100939493.html