简介
tinyhttpd 是一个超轻量型 Http Server,使用C语言开发,全部代码只有502行(包括注释),附带一个简单的Client,用来学习非常不错,可以通过阅读这段代码理解一个 Http Server 的本质。
tinyhttpd的职责
- 接收客户端链接
- 读取客户端发送的信息
- 解析请求
- 处理请求(可能会执行对应的脚本)
- 返回响应
http请求和响应报文格式
参照菜鸟教程
请求
一般格式:
请求行(请求方法 路径 协议)
头信息(格式为 key:value)
空行
主体信息(可选)(发送内容)
响应
一般格式:
响应行(协议 状态码 状态文字)
响应头信息(格式为 key:value)
空行
主体信息(也可能没有)
运行代码
make一下发现有错误:
把makefile中的-lsocket删除就行了。
运行./httpd 打开浏览器请求index.html发现服务器直接退出了,查看了一下html的属性,发现居然是可执行的文件,需要修改一下权限。
我的项目在共享文件夹中无法修改:
放到别的目录就行了:
代码执行流程
在浏览器中输入http://127.0.0.1:37137/
输入颜色点击提交
color.cgi是用perl写的,看不懂。。。我用shell重新写了一下
#!/bin/bash
read -n $CONTENT_LENGTH key_value # color=xxx
array=(${key_value//=/ })
echo "Content-Type: text/html"
echo
echo "<!doctype html>"
echo "<html>"
echo "<head><title>${array[1]}</title></head>"
echo "<body style=\"background-color:${array[1]};\" ><h1>this is ${array[1]}</h1></body>"
echo "</html>"
源代码
源代码不多就直接贴下面了
#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>
// 检查所传的字符是否是空白字符 空格(' ')、定位字符('\t')、CR('\r')、换行('\n')、垂直定位字符('\v')或翻页('\f')
#define ISspace(x) isspace((int)(x))
// 响应报文头Server
#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;
// 得到请求行 <method>空格<url>空格<协议>
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';
// 只支持get和post请求
// strcasecmp()用来比较参数s1 和s2 字符串,比较时会自动忽略大小写的差异。
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
{
unimplemented(client);
return;
}
// post请求当成脚本处理
if (strcasecmp(method, "POST") == 0)
{
cgi = 1;
}
// 跳过请求方法和url之间的空格
i = 0;
while (ISspace(buf[j]) && (j < sizeof(buf)))
{
j++;
}
// 解析出请求路径url
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))
{
url[i] = buf[j];
i++; j++;
}
url[i] = '\0';
// 如果是get请求 读取键值对?key=vlaue&key=vlaue
if (strcasecmp(method, "GET") == 0)
{
query_string = url;
// 找到url里面的?
while ((*query_string != '?') && (*query_string != '\0'))
{
query_string++;
}
// 如果有?则当成脚本处理 替换?为字符串结尾\0 让query_string指向后面的键值对
if (*query_string == '?')
{
cgi = 1;
*query_string = '\0';
query_string++;
}
}
// 默认资源都在htdocs文件夹下
sprintf(path, "htdocs%s", url);
// 默认路径htdocs/index.html
if (path[strlen(path) - 1] == '/')
{
strcat(path, "index.html");
}
// stat通过path获取文件信息,并保存在st所指的结构体stat中
if (stat(path, &st) == -1) // 如果资源不存在
{
// 读取请求头信息
while ((numchars > 0) && strcmp("\n", buf))
{
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");
}
// 如果你的文件默认是有执行权限的,自动解析成cgi程序
// S_IXUSR:文件所有者具可执行权限
// S_IXGRP:用户组具可执行权限
// S_IXOTH:其他用户具可读取权限
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);
}
/**********************************************************************/
/* http响应:客户端请求语法错误 */
/**********************************************************************/
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);
}
}
/**********************************************************************/
/* http响应:脚本运行错误 */
/**********************************************************************/
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];
// 进程id
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) // 如果是get请求则读取请求头信息
{
while ((numchars > 0) && strcmp("\n", buf))
{
numchars = get_line(client, buf, sizeof(buf));
}
}
else // 如果是post请求则读取请求头信息并且找出Content-Length的信息
{
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);
// 建立管道
// pipe(cgi_output)执行成功后,cgi_output[0]:读通道 cgi_output[1]:写通道,这就是为什么说不要被名称所迷惑
if (pipe(cgi_output) < 0)
{
cannot_execute(client);
return;
}
if (pipe(cgi_input) < 0)
{
cannot_execute(client);
return;
}
// fork进程
if ( (pid = fork()) < 0 )
{
cannot_execute(client);
return;
}
if (pid == 0) // 子进程用于执行脚本
{
char meth_env[255];
char query_env[255];
char length_env[255];
// 1代表着stdout,0代表着stdin cgi程序中用的是标准输入输出进行交互
dup2(cgi_output[1], 1); // 将系统标准输出重定向为cgi_output[1]
dup2(cgi_input[0], 0); // 将系统标准输入重定向为cgi_input[0]
close(cgi_output[0]); // 关闭了cgi_output中的读通道
close(cgi_input[1]); // 关闭了cgi_input中的写通道
// CGI标准需要将请求的方法存储环境变量中,然后和cgi脚本进行交互
sprintf(meth_env, "REQUEST_METHOD=%s", method);
putenv(meth_env);
if (strcasecmp(method, "GET") == 0) // 如果是get请求则设置键值对
{
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字符串所代表的文件路径,接下来的参数代表执行该文件时传递过去的argv(0)、argv[1]……,最后一个参数必须用空指针(NULL)作结束。
execl(path, path, NULL);
exit(0);
}
else // 父进程用于收数据以及发送子进程处理的回复数据
{
close(cgi_output[1]); // 关闭了cgi_output中的写通道
close(cgi_input[0]); // 关闭了cgi_input中的读通道
// 如果是post请求 读取请求体 发送给cgi脚本
if (strcasecmp(method, "POST") == 0)
{
for (i = 0; i < content_length; i++)
{
recv(client, &c, 1, 0);
write(cgi_input[1], &c, 1);
}
}
// 得到cgi脚本输出 并且 发送响应信息
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);
}
}
/**********************************************************************/
/* 读取一行信息 可以处理三种结尾 返回读取长度
* Unix 结尾 \n
* Windows 结尾 \r\n
* Mac 结尾 \r */
/**********************************************************************/
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);
}
/**********************************************************************/
/* 发送响应头 */
/**********************************************************************/
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);
}
/**********************************************************************/
/* http响应: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);
}
/**********************************************************************/
/* 发送资源文件 */
/**********************************************************************/
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)
{
// 404 资源不存在
not_found(client);
}
else
{
// 发送响应头
headers(client, filename);
// 发送响应体
cat(client, resource);
}
fclose(resource);
}
/**********************************************************************/
/* 本函数开启web监听,端口由参数传递。
* 如果参数为0则动态分配。*/
/**********************************************************************/
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");
}
// 绑定服务器ip和端口号
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");
}
// 如果端口号为0 动态分配一个端口
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);
}
/**********************************************************************/
/* http响应:对应请求方法没实现 */
/**********************************************************************/
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)
{
// 服务器socket
int server_sock = -1;
// 端口
u_short port = 0;
// 客户端socket
int client_sock = -1;
// 用来存放 客户端地址 端口 协议 信息
struct sockaddr_in client_name;
int client_name_len = sizeof(client_name);
// 线程
pthread_t newthread;
// 开始web监听
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);
}
windows版
tinyhttpd_for_win.zip里面是别人修改的windows版本。
demo是我自己改的,需要有python3环境,运行效果如下:
登陆:http:/127.0.0.1:8080/
js:http:/127.0.0.1:8080/js.html
python脚本:http://127.0.0.1:8080/cgipy?p.py
获取文件夹:http://127.0.0.1:8080/dir/
静态网页:http:/127.0.0.1:8080/baidu/
用json文件渲染页面:http:/127.0.0.1:8080/json/
请求图片小于1mb:http:/127.0.0.1:8080/1mb.jpg
请求图片大于1mb:http:/127.0.0.1:8080/1mb.png
用数据库数据渲染页面:http:/127.0.0.1:8080/stu/
百度云链接:https://pan.baidu.com/s/1DZw6mx8sOX0C_9m52CMHBg
提取码:10pb