1. 简介:

tinyhttpd是使用c语言开发的超轻量级http服务器,通过代码流程可以了解http服务器的基本处理流程,

并且涉及了网络套接字,线程,父子进程,管道等等知识点;

项目地址:http://sourceforge.net/projects/tinyhttpd/

2. 流程介绍:

(1) 服务器启动,等待客户端请求到来;

(2) 客户端请求到来,创建新线程处理该请求;

(3) 读取httpHeader中的method,截取url,其中GET方法需要记录url问号之后的参数串;

(4) 根据url构造完整路径,如果是/结尾,则指定为该目录下的index.html;

(5) 获取文件信息,如果找不到文件,返回404,找到文件则判断文件权限;

(6) 如果是GET请求并且没有参数,或者文件不可执行,则直接将文件内容构造http信息返回给客户端;

(7) 如果是GET带参数,POST,文件可执行,则执行CGI;

(8) GET请求略过httpHeader,POST方法需要记录httpHeader中的Content-Length:xx;

(9) 创建管道用于父子进程通信,fork产生子进程;

(10) 子进程设置环境变量,将标准输入和输出与管道相连,并且通过exec执行CGI;

(11) 如果是POST,父进程将读到post内容发送给子进程,并且接收子进程的输出,输出给客户端;

3. 管道说明:

4. 代码注释:

 /* 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);
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); /**********************************************************************/
/* 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[];
int numchars;
char method[];
char url[];
char path[];
size_t i, j;
struct stat st;
int cgi = ; /* becomes true if server decides this is a CGI
* program */
char *query_string = NULL; //读取第一行数据
numchars = get_line(client, buf, sizeof(buf));
i = ; j = ;
//读取http的头部method字段,读到空白为止
while (!ISspace(buf[j]) && (i < sizeof(method) - ))
{
method[i] = buf[j];
i++; j++;
}
method[i] = '\0'; //只支持GET和POST请求,其他请求方式返回未实现
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
{
unimplemented(client);
return;
}
//如果是POST请求,设置cgi标志为1
if (strcasecmp(method, "POST") == )
cgi = ; i = ;
//跳过空白字符
while (ISspace(buf[j]) && (j < sizeof(buf)))
j++;
//读取url字串
while (!ISspace(buf[j]) && (i < sizeof(url) - ) && (j < sizeof(buf)))
{
url[i] = buf[j];
i++; j++;
}
url[i] = '\0';
//如果是GET请求,需要从url中解析参数
if (strcasecmp(method, "GET") == )
{
query_string = url;
//找到?位置
while ((*query_string != '?') && (*query_string != '\0'))
query_string++;
//当前字符为?字符
if (*query_string == '?')
{
cgi = ; //标记cgi字段
*query_string = '\0'; //将?替换成\0
query_string++; //query_string指向get参数
}
}
//连接url资源路径
sprintf(path, "htdocs%s", url);
//如果访问的是/结尾的目录,那么指定为目录下的index.html
if (path[strlen(path) - ] == '/')
strcat(path, "index.html");
//获取文件信息失败
if (stat(path, &st) == -) {
//将header中的信息都丢弃
while ((numchars > ) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));
//返回404
not_found(client);
}
else
{
//如果访问的是目录,那么指定为目录下的index.html
if ((st.st_mode & S_IFMT) == S_IFDIR)
strcat(path, "/index.html");
//如果具有可执行权限,标记cgi
if ((st.st_mode & S_IXUSR) ||
(st.st_mode & S_IXGRP) ||
(st.st_mode & S_IXOTH) )
cgi = ;
//不需要cgi参与的文件直接进行服务
if (!cgi)
serve_file(client, path);
//否则执行cgi
else
execute_cgi(client, path, method, query_string);
} close(client);
} /**********************************************************************/
/* Inform the client that a request it has made has a problem.
* Parameters: client socket */
/**********************************************************************/
void bad_request(int client)
{
char buf[];
//发送BAD REQUEST提示信息到客户端
sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n");
send(client, buf, sizeof(buf), );
sprintf(buf, "Content-type: text/html\r\n");
send(client, buf, sizeof(buf), );
sprintf(buf, "\r\n");
send(client, buf, sizeof(buf), );
sprintf(buf, "<P>Your browser sent a bad request, ");
send(client, buf, sizeof(buf), );
sprintf(buf, "such as a POST without a Content-Length.\r\n");
send(client, buf, sizeof(buf), );
} /**********************************************************************/
/* 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 */
/**********************************************************************/
void cat(int client, FILE *resource)
{
char buf[];
//循环读取并发送文件内容
fgets(buf, sizeof(buf), resource);
while (!feof(resource))
{
send(client, buf, strlen(buf), );
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[];
//发送500服务器内部错误到客户端
sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "Content-type: text/html\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "<P>Error prohibited CGI execution.\r\n");
send(client, buf, strlen(buf), );
} /**********************************************************************/
/* 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();
} /**********************************************************************/
/* Execute a CGI script. Will need to set environment variables as
* appropriate.
* Parameters: client socket descriptor
* path to the CGI script */
/**********************************************************************/
void execute_cgi(int client, const char *path,
const char *method, const char *query_string)
{
char buf[];
int cgi_output[];
int cgi_input[];
pid_t pid;
int status;
int i;
char c;
int numchars = ;
int content_length = -; buf[] = 'A'; buf[] = '\0';
//如果是GET请求则读取并丢掉头部信息
if (strcasecmp(method, "GET") == )
while ((numchars > ) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));
//如果是POST请求
else /* POST */
{
//读取一行数据
numchars = get_line(client, buf, sizeof(buf));
while ((numchars > ) && strcmp("\n", buf))
{
//截取Content-Length:字段
buf[] = '\0';
//如果找到该字段,将该字段后面的字串转成整数长度
if (strcasecmp(buf, "Content-Length:") == )
content_length = atoi(&(buf[]));
//读取头部内容
numchars = get_line(client, buf, sizeof(buf));
}
//没有找到Content-Length,发送bad request
if (content_length == -) {
bad_request(client);
return;
}
}
//发送http200头
sprintf(buf, "HTTP/1.0 200 OK\r\n");
send(client, buf, strlen(buf), );
//创建输出管道,构造父子进程通信
if (pipe(cgi_output) < ) {
cannot_execute(client);
return;
}
//创建输入管道,构造父子进程通信
if (pipe(cgi_input) < ) {
cannot_execute(client);
return;
}
//创建子进程
if ( (pid = fork()) < ) {
cannot_execute(client);
return;
}
//子进程执行CGI脚本
if (pid == ) /* child: CGI script */
{
char meth_env[];
char query_env[];
char length_env[]; //子进程的标准输入输出与管道对接
dup2(cgi_output[], ); //将标准输出重定向到cgi输出管道的写端
dup2(cgi_input[], ); //将标准输入重定向到cgi输入管道的读端 close(cgi_output[]); //关闭cgi输出管道的读端
close(cgi_input[]); //关闭cgi输入管道的写端
//设置method环境变量
sprintf(meth_env, "REQUEST_METHOD=%s", method);
putenv(meth_env);
//如果是GET方式设置请求参数环境变量
if (strcasecmp(method, "GET") == ) {
sprintf(query_env, "QUERY_STRING=%s", query_string);
putenv(query_env);
}
//如果是POST方式设置内容长度环境变量
else { /* POST */
sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
putenv(length_env);
}
//执行CGI
execl(path, path, NULL);
exit();
} else { /* parent */
close(cgi_output[]); //关闭cgi输出管道的写端
close(cgi_input[]); //关闭cgi输入管道的读端
//如果是POST请求,循环读取post内容,并且输入到cgi子进程
if (strcasecmp(method, "POST") == )
for (i = ; i < content_length; i++) {
recv(client, &c, , );
write(cgi_input[], &c, );
}
//从cgi中循环读取输出内容,发送到客户端
while (read(cgi_output[], &c, ) > )
send(client, &c, , ); //关闭管道
close(cgi_output[]);
close(cgi_input[]);
//等待子进程结束
waitpid(pid, &status, );
}
} /**********************************************************************/
/* 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 = ;
char c = '\0';
int n;
//接收\n结束的一行数据或接收满缓冲区
while ((i < size - ) && (c != '\n'))
{
//接收一个字节
n = recv(sock, &c, , );
/* DEBUG printf("%02X\n", c); */
if (n > )
{
//如果接收到了\r符号
if (c == '\r')
{
//将下一个字字符预取出来,注意MSG_PEEK本地接收窗口不滑动,下次读取仍然可以读取到该字符
n = recv(sock, &c, , MSG_PEEK);
/* DEBUG printf("%02X\n", c); */
//如果下一个字符是\n的话,那么接收这个字符
if ((n > ) && (c == '\n'))
recv(sock, &c, , );
//不是\n的话,那么将\r替换成\n
else
c = '\n';
}
//字符存入buf,继续读取
buf[i] = c;
i++;
}
else
c = '\n';
}
//设置buf字符串结束符
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 */
/**********************************************************************/
void headers(int client, const char *filename)
{
char buf[];
(void)filename; /* could use filename to determine file type */
//发送http头 http码 服务器信息 内容类型等头部信息
strcpy(buf, "HTTP/1.0 200 OK\r\n");
send(client, buf, strlen(buf), );
strcpy(buf, SERVER_STRING);
send(client, buf, strlen(buf), );
sprintf(buf, "Content-Type: text/html\r\n");
send(client, buf, strlen(buf), );
strcpy(buf, "\r\n");
send(client, buf, strlen(buf), );
} /**********************************************************************/
/* Give a client a 404 not found status message. */
/**********************************************************************/
void not_found(int client)
{
char buf[];
//发送http头 http码 服务器信息 内容类型等头部信息 html提示信息
sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, SERVER_STRING);
send(client, buf, strlen(buf), );
sprintf(buf, "Content-Type: text/html\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "<BODY><P>The server could not fulfill\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "your request because the resource specified\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "is unavailable or nonexistent.\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "</BODY></HTML>\r\n");
send(client, buf, strlen(buf), );
} /**********************************************************************/
/* 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 = ;
char buf[]; //读取丢弃所有头部信息
buf[] = 'A'; buf[] = '\0';
while ((numchars > ) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf)); //打开资源文件
resource = fopen(filename, "r");
//打开失败,发送404
if (resource == NULL)
not_found(client);
else
{
headers(client, filename); //发送http头
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 */
/**********************************************************************/
int startup(u_short *port)
{
int httpd = ;
struct sockaddr_in name;
//创建tcp socket
httpd = socket(PF_INET, SOCK_STREAM, );
if (httpd == -)
error_die("socket");
memset(&name, , sizeof(name));
//设置sockaddr地址结构
name.sin_family = AF_INET;
name.sin_port = htons(*port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
//绑定到本地地址port指定端口
if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < )
error_die("bind");
//如果没有指定端口,则由系统指定,此处或得到系统指定的端口
if (*port == ) /* if dynamically allocating a port */
{
int namelen = sizeof(name);
if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -)
error_die("getsockname");
*port = ntohs(name.sin_port);
}
//服务器开始监听
if (listen(httpd, ) < )
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[];
//发送未实现的请求方法和提示消息给客户端
sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, SERVER_STRING);
send(client, buf, strlen(buf), );
sprintf(buf, "Content-Type: text/html\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "</TITLE></HEAD>\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n");
send(client, buf, strlen(buf), );
sprintf(buf, "</BODY></HTML>\r\n");
send(client, buf, strlen(buf), );
} /**********************************************************************/ int main(void)
{
int server_sock = -;
u_short port = ;
int client_sock = -;
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 ()
{
//等待客户端连接到来
client_sock = accept(server_sock,
(struct sockaddr *)&client_name,
&client_name_len);
if (client_sock == -)
error_die("accept");
/* accept_request(client_sock); */
//开启一个新线程处理客户端请求
if (pthread_create(&newthread , NULL, accept_request, client_sock) != )
perror("pthread_create");
}
//关闭服务器
close(server_sock); return();
}

源码分析之tinyhttpd-0.1的更多相关文章

  1. 模块化系列教程 | 深入源码分析阿里JarsLink1.0模块化框架

    1. 概述 1.1 模块动态加载卸载主流程 2. 模块动态加载 2.1 模块加载源码分析 2.1.1 AbstractModuleRefreshScheduler 2.1.2 ModuleLoader ...

  2. Android 框架学习2:源码分析 EventBus 3.0 如何实现事件总线

    Go beyond yourself rather than beyond others. 上篇文章 深入理解 EventBus 3.0 之使用篇 我们了解了 EventBus 的特性以及如何使用,这 ...

  3. Spring之WebContext不使用web.xml启动 初始化重要的类源码分析(Servlet3.0以上的)

    入口: org.springframework.web.SpringServletContainerInitializer implements ServletContainerInitializer ...

  4. ES bulk源码分析——ES 5.0

    对bulk request的处理流程: 1.遍历所有的request,对其做一些加工,主要包括:获取routing(如果mapping里有的话).指定的timestamp(如果没有带timestamp ...

  5. 源码分析 SpringCloud 2020.0.4 版本 EurekaClient 的注册过程

    1. 概述 老话说的好:要善于思考,有创新意识. 言归正传,之前聊了 Springboot 的启动过程,今天来聊聊 Eureka Client 的注册过程. 2. Eureka Client 的注册过 ...

  6. jQuery源码分析系列

    声明:本文为原创文章,如需转载,请注明来源并保留原文链接Aaron,谢谢! 版本截止到2013.8.24 jQuery官方发布最新的的2.0.3为准 附上每一章的源码注释分析 :https://git ...

  7. [转]jQuery源码分析系列

    文章转自:jQuery源码分析系列-Aaron 版本截止到2013.8.24 jQuery官方发布最新的的2.0.3为准 附上每一章的源码注释分析 :https://github.com/JsAaro ...

  8. 分布式缓存技术之Redis_Redis集群连接及底层源码分析

    目录 1. Jedis 单点连接 2. Jedis 基于sentinel连接 基本使用 源码分析 本次源码分析基于: jedis-3.0.1 1. Jedis 单点连接   当是单点服务时,Java ...

  9. 【转载】AsyncTask源码分析

    原文地址:https://github.com/white37/AndroidSdkSourceAnalysis/blob/master/article/AsyncTask%E5%92%8CAsync ...

  10. jQuery源码分析系列(转载来源Aaron.)

    声明:非本文原创文章,转载来源原文链接Aaron. 版本截止到2013.8.24 jQuery官方发布最新的的2.0.3为准 附上每一章的源码注释分析 :https://github.com/JsAa ...

随机推荐

  1. [计算机网络] DNS何时使用TCP协议,何时使用UDP协议

    DNS同时占用UDP和TCP端口53是公认的,这种单个应用协议同时使用两种传输协议的情况在TCP/IP栈也算是个另类.但很少有人知道DNS分别在什么情况下使用这两种协议. 先简单介绍下TCP与UDP. ...

  2. canvas画布上定位点击位置

    两种方法: 1. cvs.onclick = function (e) { if (e.offsetX || e.layerX) { var x = e.offsetX == undefined ? ...

  3. request设置属性 一般当做下一个页面的结果集

    request设置属性 一般当做下一个页面的结果集

  4. 【bzoj1212】[HNOI2004]L语言 AC自动机

    题目描述 标点符号的出现晚于文字的出现,所以以前的语言都是没有标点的.现在你要处理的就是一段没有标点的文章. 一段文章T是由若干小写字母构成.一个单词W也是由若干小写字母构成.一个字典D是若干个单词的 ...

  5. [BZOJ4589]Hard Nim

    description BZOJ 题意:\(n\)堆式子,每堆石子数量为\(\le m\)的质数,对于每一个局面玩\(Nim\)游戏,求后手必胜的方案数. data range \[n\le 10^9 ...

  6. BZOJ5290 & 洛谷4438:[HNOI/AHOI2018]道路——题解

    https://www.lydsy.com/JudgeOnline/problem.php?id=5290 https://www.luogu.org/problemnew/show/P4438 的确 ...

  7. ContestHunter暑假欢乐赛 SRM 05

    T1 组合数,求一下乘法逆元就行了 没取模 没1LL* 爆零了 T2 让最大子段和最小就行,跑最大子段和的时候若超过S就弹出堆中最大的数,每次有负数加进来不断弹出最小的数相加重新加进堆直到为正数,因为 ...

  8. uva 11424

    uva 11424 GCD - Extreme (I) 题意:思路:(见http://www.cnblogs.com/Duahanlang/p/3184994.html ) 差别在于数据规模和时间,其 ...

  9. JavaScript中this的用法详解

    JavaScript中this的用法详解 最近,跟身边学前端的朋友了解,有很多人对函数中的this的用法和指向问题比较模糊,这里写一篇博客跟大家一起探讨一下this的用法和指向性问题. 1定义 thi ...

  10. 用pip命令安装Python第三方库

    一.准备工作 1. 安装pip (1)下载 pip下载地址:https://pypi.python.org/pypi/pip#downloads (2)安装 下载后解压,控制台下进入解压后的目录,运行 ...