Tinyhttpd学习
个人结合其他网站对Tinyhttpd的细读和学习
个人仓库:https://github.com/dopamine-joker/Mythhpd
项目github: https://github.com/EZLippi/Tinyhttpd
原项目官网:http://tinyhttpd.sourceforge.net
学习参考网站:https://www.cnblogs.com/nengm1988/p/7816618.html
1. 简介
Tinyhttpd 是J. David Blackstone在1999年写的一个不到 500 行的超轻量型 Http Server,比较适合初学者学习。
原作者:
代码语言:javascript复制This software is copyright 1999 by J. David Blackstone. Permission is granted to redistribute and modify this software under the terms of the GNU General Public License, available at http://www.gnu.org/ .
If you use this software or examine the code, I would appreciate knowing and would be overjoyed to hear about it at jdavidb@sourceforge.net .
This software is not production quality. It comes with no warranty of any kind, not even an implied warranty of fitness for a particular purpose. I am not responsible for the damage that will likely result if you use this software on your computer system.
I wrote this webserver for an assignment in my networking class in 1999. We were told that at a bare minimum the server had to serve pages, and told that we would get extra credit for doing "extras." Perl had introduced me to a whole lot of UNIX functionality (I learned sockets and fork from Perl!), and O'Reilly's lion book on UNIX system calls plus O'Reilly's books on CGI and writing web clients in Perl got me thinking and I realized I could make my webserver support CGI with little trouble.
Now, if you're a member of the Apache core group, you might not be impressed. But my professor was blown over. Try the color.cgi sample script and type in "chartreuse." Made me seem smarter than I am, at any rate. :)
Apache it's not. But I do hope that this program is a good educational tool for those interested in http/socket programming, as well as UNIX system calls. (There's some textbook uses of pipes, environment variables, forks, and so on.)
One last thing: if you look at my webserver or (are you out of mind?!?) use it, I would just be overjoyed to hear about it. Please email me. I probably won't really be releasing major updates, but if I help you learn something, I'd love to know!
Happy hacking!
2. Tinyhttp运作流程
(参考博客的贴图):
具体文字流程也可在github项目找到,如下:
(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 是无连接的。
3. 注意
(1) 修改相关文件的权限
index.html必须不能有执行权限,否则代码中会将其当作cgi脚本处理。
代码语言:javascript复制if( (st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) ||(st.st_mode & S_IXOTH)){
//S_IXUSR 00100 owner has execute permission
//S_IXGRP 00010 group has execute permission
//S_IXOTH 00001 others have execute permission
cgi = 1;
}
因此需要先将index.html的运行权限去除,使用命令 chmod 600 index.html
而脚本文件color.cgi需要有执行权限
(2) color.cgi修改
color.cgi使用perl编写的,对原项目的color.cgi中的代码中perl解释器路径进行更改。
若linux系统中的perl解释器路径与代码中的一致则不用修改
文件中第一行
代码语言:javascript复制#!/usr/local/bin/perl -Tw
改为
代码语言:javascript复制#!/usr/bin/perl -Tw
若perl脚本执行时没有找到相关模块则需手动安装
4. 食用流程
(1) 直接拷贝或者自行敲码
(2) 修改相关文件权限和perl代码(上面有写)
(3) 在项目目录下使用makefile构建
代码语言:javascript复制[root@localhost Myhttpd]# make clean
rm httpd
[root@localhost Myhttpd]# make
gcc -g -W -Wall -pthread -o httpd httpd.c
(4) 运行
代码语言:javascript复制[root@localhost Myhttpd]# ./httpd
httpd running on port: 60555
(5) 测试
1) POST
2) GET
5. 代码
个人在学习时加了一点注释
代码语言:javascript复制#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>
#include <stdint.h>
#define ISspace(x) isspace((int)(x))
#define SERVER_STRING "Server: jdbhttpd/0.1.0rn"
#define STDIN 0
#define STDOUT 1
#define STDERR 2
void accept_request(void *arg);
void bad_request(int);
void cat(int, FILE *);
void cannot_execute(int);
void execute_cgi(int, const char *, const char *, const char *);
void headers(int, const char *);
int startup(u_short *);
int get_line(int, char *, int);
void unimplemented(int );
void error_die(const char *);
void not_found(int );
void serve_file(int , const char *);
// Http请求的信息
// GET请求
// GET / HTTP/1.1
// Host: 192.168.0.23:47310
// Connection: keep-alive
// Upgrade-Insecure-Requests: 1
// User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
// Accept: text/html,application/xhtml xml,application/xml;q=0.9,image/webp,*/*; q = 0.8
// Accept - Encoding: gzip, deflate, sdch
// Accept - Language : zh - CN, zh; q = 0.8
// Cookie: __guid = 179317988.1576506943281708800.1510107225903.8862; monitor_count = 5
//
//
// POST请求
// POST / color1.cgi HTTP / 1.1
// Host: 192.168.0.23 : 47310
// Connection : keep - alive
// Content - Length : 10
// Cache - Control : max - age = 0
// Origin : http ://192.168.0.23:40786
// Upgrade - Insecure - Requests : 1
// User - Agent : Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 55.0.2883.87 Safari / 537.36
// Content - Type : application / x - www - form - urlencoded
// Accept : text / html, application / xhtml xml, application / xml; q = 0.9, image / webp, */*;q=0.8
// Referer: http://192.168.0.23:47310/
// Accept-Encoding: gzip, deflate
// Accept-Language: zh-CN,zh;q=0.8
// Cookie: __guid=179317988.1576506943281708800.1510107225903.8862; monitor_count=281
// Form Data
// color=gray
void accept_request(void *arg){
int client = (intptr_t)arg;
char buf[1024]; //读取客户端发送的内容
char method[255]; //保存请求方法
char url[255]; //保存请求的url
char path[512]; //请求路径
size_t i,j;
struct stat st; //查询文件的数据结构
int cgi = 0; //是否调用cgi程序
char *query_string = NULL; //
int numchars = 1;
//读取http请求的第一行数据(request line),然后把请求方法存进method
//请求方法 URL 协议版本rn
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] = '