Tinyhttpd1. 概要(Abstract)2. 实例(Example)3. 源码剖析(Source Code)
mainstartupaccept_requestexecute_cgicolor.cgiserver_fileget_linecatheaderscannot_executeunimplementednot_foundbad_requesterror_die 4. Makefile总结
Tinyhttpd1. 概要(Abstract)Tinyhttpd是J. David Blackstone在1999年写的微型Web服务器,实现了一个简单的Http服务器的功能。其源码来自SourceForge。本文是笔者在Github上找到的一个版本的学习笔记,Github仓库地址为https://github.com/EZLippi/Tinyhttpd。借助该源码,笔者复习一下C++的网络编程的知识。笔者的学习思路也是根据该仓库提供的思路来的,感谢该作者的分享。
Tinyhttpd实现了一个简易Web Server,可以在Linux上作为一个简单的网页服务器。该服务器脚本在运行之后,客户端可以借助浏览器远程访问该脚本文件夹下的资源。
含有的函数及其作用如下:
main:main函数,代码执行的入口(当然,全局变量的构造函数以及其它函数会先执行);accept_request:服务端处理客户的函数,用于发送请求资源给客户端(此处通过创建一个线程得到);bad_request:客户端请求出错的处理函数,返回"HTTP/1.0 400 BAD REQUEST";cat:发送文件函数,读取文件信息,并将其发送至客户端;cannot_execute:无法执行cgi文件的处理函数,返回"HTTP/1.0 500 Internal Server Error";error_die:服务端打印错误信息;execute_cgi:执行cgi文件的函数,并将输出信息发送至客户端;get_line:一行地读取报文的函数;headers:添加http报文的头部;not_found:资源不存在的处理函数,返回"HTTP/1.0 404 NOT FOUND";server_file:如果请求的资源不是cgi文件,则直接发送给客户端;startup:服务端套接字创建函数,创建套接字,绑定端口号,监听套接字;unimplemented:服务端未实现方法的返回信息;
TinyHttpd的流程图如下:
上图来自博客,感谢博主。从上图可以很容易地看出整个文件执行过程,下面先给出该源码的运行实例。
2. 实例(Example)(在执行下面操作之间,需要先编译文本文件生成可执行文件,输入make即可)
首先在服务器端运行httpd文件,这里我在源码中指定了端口号为12345。
然后在浏览器输入IP地址加上端口号即可访问到"/htdocs/index.html"文件。
并在输入框输入颜色的英文,如"red",即可在服务器端执行"/htdocs/color.cgi"脚本:
此时服务端的输出日志为:
运行过程中卡了一个bug,连接的时候,保持客户端连接,在服务器端输入Ctrl + C后出现下图bug,这个bug把客户端关了就好了:
3. 源码剖析(Source Code)本文的源码解释顺序与Github博主推荐的一样:main -> startup -> accept_request -> execute_cgi。在了解了大体框架之后再仔细把每个函数的源码看一看。
mainint main(void)
{
int server_sock = -1;
u_short port = 12345;
int client_sock = -1;
struct sockaddr_in client_name;
socklen_t client_name_len = sizeof(client_name);
pthread_t newthread;
server_sock = startup(&port);
printf("httpd running on port %dn", port);
while (1)
{
//接受请求,函数原型
//int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
client_sock = accept(server_sock,
(struct sockaddr *)&client_name,
&client_name_len);
if (client_sock == -1)
error_die("accept");
printf("Client's ip address is: %sn", inet_ntoa(client_name.sin_addr));
//每次收到请求,创建一个线程来处理接受到的请求
//把client_sock转成地址作为参数传入pthread_create
if (pthread_create(&newthread, NULL, (void *)accept_request, (void *)(intptr_t)client_sock) != 0)
perror("pthread_create");
}
close(server_sock);
return (0);
}
startup
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;
name.sin_port = htons(*port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
// 绑定socket
if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
error_die("bind");
// 如果端口没有设置,提供个随机端口
if (*port == 0)
{
socklen_t 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);
}
accept_request
// HTTP 请求报文,来自Github
// 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,*
void accept_request(void *arg)
{
// socket
int client = (intptr_t)arg;
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;
//根据上面的Get请求,可以看到这边就是取第一行
//这边都是在处理第一条http信息
//"GET / HTTP/1.1n"
numchars = get_line(client, buf, sizeof(buf)); // get_line读取一行,并以' '结尾
i = 0;
j = 0;
//第一行字符串提取Get
//判断是否是空格 #define ISspace(x) isspace((int)(x))
while (!ISspace(buf[j]) && (i < sizeof(method) - 1))
{
method[i] = buf[j];
i++;
j++;
}
//结束
method[i] = ' ';
//判断是Get还是Post
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
{
unimplemented(client); // 如果不是GET或者POST
return;
}
//如果是POST,cgi置为1
if (strcasecmp(method, "POST") == 0)
cgi = 1;
i = 0;
//跳过空格
while (ISspace(buf[j]) && (j < sizeof(buf)))
j++;
//得到 "/" 注意:如果你的http的网址为http://192.168.0.23:47310/index.html
// 那么你得到的第一条http信息为GET /index.html HTTP/1.1,那么
// 解析得到的就是/index.html
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))
{
url[i] = buf[j];
i++;
j++;
}
url[i] = ' ';
//判断Get请求
if (strcasecmp(method, "GET") == 0)
{
query_string = url;
while ((*query_string != '?') && (*query_string != ' '))
query_string++;
if (*query_string == '?') // cgi文件的URL是以这个为开头的吗
{
cgi = 1;
*query_string = ' ';
query_string++;
}
}
//路径
sprintf(path, "htdocs%s", url);
//默认地址,解析到的路径如果为/,则自动加上index.html
if (path[strlen(path) - 1] == '/')
strcat(path, "index.html");
printf("Method is : %sn", method);
printf("URL is : %sn", url);
printf("Path is : %sn", path);
//获得文件信息
if (stat(path, &st) == -1)
{
//把所有http信息读出然后丢弃
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");
//如果你的文件默认是有执行权限的,自动解析成cgi程序,如果有执行权限但是不能执行,会接受到报错信号
if ((st.st_mode & S_IXUSR) ||
(st.st_mode & S_IXGRP) ||
(st.st_mode & S_IXOTH))
cgi = 1;
if (!cgi)
//接读取文件返回给请求的http客户端
serve_file(client, path);
else
//执行cgi文件
execute_cgi(client, path, method, query_string);
}
//执行完毕关闭socket
close(client);
}
上述函数仅处理了Http报文头部的第一行,即仅读取请求方式,URL,就连版本号都略过了。Http报文的剩下内容,如果是cgi文件,那么会进入到execute_cgi函数中,否则进入server_file函数中。
execute_cgi// 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, *
void execute_cgi(int client, const char *path,
const char *method, const char *query_string)
{
//缓冲区
char buf[1024];
//2根管道
int cgi_output[2];
int cgi_input[2];
//进程pid和状态
pid_t pid;
int status;
int i;
char c;
//读取的字符数
int numchars = 1;
//http的content_length
int content_length = -1;
//默认字符
buf[0] = 'A';
buf[1] = ' ';
//忽略大小写比较字符串
if (strcasecmp(method, "GET") == 0)
//读取数据,把整个header都读掉,以为Get写死了直接读取index.html,没有必要分析余下的http信息了
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))
{
//根据HTTP报文可以看出来,如果请求方式是POST,那么报文中含有Content-Length
//如果是POST请求,就需要得到Content-Length,Content-Length:这个字符串一共长为15位,所以
//取出头部一句后,将第16位设置结束符,进行比较
//第16位置为结束
buf[15] = ' ';
if (strcasecmp(buf, "Content-Length:") == 0)
//内存从第17位开始就是长度,将17位开始的所有字符串转成整数就是content_length
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 OKrn");
send(client, buf, strlen(buf), 0);
//建立output管道
if (pipe(cgi_output) < 0)
{
cannot_execute(client);
return;
}
//建立input管道
if (pipe(cgi_input) < 0)
{
cannot_execute(client);
return;
}
// 管道的1端为写入,0端为读取
// fork后管道都复制了一份,都是一样的
// 子进程关闭2个无用的端口,避免浪费
// ×<------------------------->1 output
// 0<-------------------------->× input
// 父进程关闭2个无用的端口,避免浪费
// 0<-------------------------->× output
// ×<------------------------->1 input
// 此时父子进程已经可以通信
//fork进程,子进程用于执行CGI
//父进程用于收数据以及发送子进程处理的回复数据
if ((pid = fork()) < 0)
{
cannot_execute(client);
return;
}
if (pid == 0)
{
char meth_env[255];
char query_env[255];
char length_env[255];
//子进程输出重定向到output管道的1端
dup2(cgi_output[1], 1);
//子进程输入重定向到input管道的0端
dup2(cgi_input[0], 0);
//关闭无用管道口
close(cgi_output[0]);
close(cgi_input[1]);
//CGI环境变量
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);
}
//替换执行path
execl(path, path, NULL);
//int m = execl(path, path, NULL);
//如果path有问题,例如将html网页改成可执行的,但是执行后m为-1
//退出子进程,管道被破坏,但是父进程还在往里面写东西,触发Program received signal SIGPIPE, Broken pipe.
exit(0);
}
else
{
//关闭无用管道口
close(cgi_output[1]);
close(cgi_input[0]);
if (strcasecmp(method, "POST") == 0)
for (i = 0; i < content_length; i++)
{
//得到post请求数据,写到input管道中,供子进程使用
recv(client, &c, 1, 0);
write(cgi_input[1], &c, 1);
}
//从output管道读到子进程处理后的信息,然后send出去
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);
}
}
该函数包含了两个进程,子进程先设置cgi文件的运行环境(参数),然后执行color.cgi文件,并将脚本输出内容通过管道发送给父进程,然后父进程将输入内容发送给客户。
color.cgi#!/usr/bin/perl -Tw
use strict;
use CGI;
my($cgi) = new CGI;
print $cgi->header('text/html');
print $cgi->start_html(-title => "Example CGI script",
-BGCOLOR => 'red');
print $cgi->h1("CGI Example");
print $cgi->p, "This is an example of CGIn";
print $cgi->p, "Parameters given to this script:n";
print "- n";
foreach my $param ($cgi->param)
{
print "
- ", "$param ", $cgi->param($param), "n"; } print "
void serve_file(int client, const char *filename)
{
FILE *resource = NULL;
int numchars = 1;
char buf[1024];
//默认字符
buf[0] = 'A';
buf[1] = ' ';
while ((numchars > 0) && strcmp("n", buf))
numchars = get_line(client, buf, sizeof(buf)); // clear client buf
resource = fopen(filename, "r");
if (resource == NULL)
not_found(client);
else
{
headers(client, filename);
cat(client, resource);
}
fclose(resource);
}
如果不是CGI文件,该函数直接读取文件返回给请求的http客户端。
以上是整个流程的主要函数,这些函数中还调用了一些其它的子函数,这些子函数包括错误反馈,字符读取等功能。下面简单介绍一些这些子函数。
get_line
//得到一行数据,只要发现c为n,就认为是一行结束,如果读到r,再用MSG_PEEK的方式读入一个字符,如果是n,从socket用读出
//如果是下个字符则不处理,将c置为n,结束。如果读到的数据为0中断,或者小于0,也视为结束,c置为n
int get_line(int sock, char *buf, int size)
{
int i = 0;
char c = ' ';
int n;
while ((i < size - 1) && (c != 'n'))
{
n = recv(sock, &c, 1, 0);
if (n > 0)
{
if (c == 'r')
{
//偷窥一个字节,如果是n就读走,否则就直接在字符数组后面加换行
n = recv(sock, &c, 1, MSG_PEEK);
if ((n > 0) && (c == 'n'))
recv(sock, &c, 1, 0);
else
//不是n(读到下一行的字符)或者没读到,置c为n 跳出循环,完成一行读取
c = 'n';
}
buf[i] = c;
i++;
}
else
c = 'n';
}
buf[i] = ' ';
return (i);
}
cat
//得到文件内容,发送
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);
}
}
headers
//加入http的headers
void headers(int client, const char *filename)
{
char buf[1024];
(void)filename;
strcpy(buf, "HTTP/1.0 200 OKrn");
send(client, buf, strlen(buf), 0);
// #define SERVER_STRING "Server: jdbhttpd/0.1.0rn"
strcpy(buf, SERVER_STRING);
send(client, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: text/htmlrn");
send(client, buf, strlen(buf), 0);
strcpy(buf, "rn");
send(client, buf, strlen(buf), 0);
}
cannot_execute
void cannot_execute(int client)
{
char buf[1024];
sprintf(buf, "HTTP/1.0 500 Internal Server Errorrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "Content-type: text/htmlrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "rn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "Error prohibited CGI execution.rn");
send(client, buf, strlen(buf), 0);
}
unimplemented
//如果方法没有实现,就返回此信息
void unimplemented(int client)
{
char buf[1024];
sprintf(buf, "HTTP/1.0 501 Method Not Implementedrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, SERVER_STRING);
send(client, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: text/htmlrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "rn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "Method Not Implementedrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, " rn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "HTTP request method not supported.rn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "rn");
send(client, buf, strlen(buf), 0);
}
not_found
//如果资源没有找到得返回给客户端下面的信息
void not_found(int client)
{
char buf[1024];
sprintf(buf, "HTTP/1.0 404 NOT FOUNDrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, SERVER_STRING);
send(client, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: text/htmlrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "rn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "Not Found rn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "The server could not fulfillrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "your request because the resource specifiedrn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "is unavailable or nonexistent.rn");
send(client, buf, strlen(buf), 0);
sprintf(buf, "rn");
send(client, buf, strlen(buf), 0);
}
bad_request
void bad_request(int client)
{
char buf[1024];
sprintf(buf, "HTTP/1.0 400 BAD REQUESTrn");
send(client, buf, sizeof(buf), 0);
sprintf(buf, "Content-type: text/htmlrn");
send(client, buf, sizeof(buf), 0);
sprintf(buf, "rn");
send(client, buf, sizeof(buf), 0);
sprintf(buf, "Your browser sent a bad request, ");
send(client, buf, sizeof(buf), 0);
sprintf(buf, "such as a POST without a Content-Length.rn");
send(client, buf, sizeof(buf), 0);
}
error_die
void error_die(const char *sc)
{
perror(sc);
exit(1);
}
将错误信息输出到服务端窗口。
4. MakefileLinux下C/C++的编译当然需要使用到Makefile。但之前笔者一直耽搁了这方面的学习,所以现在重新又拿起来。
all: httpd client LIBS = -pthread # -lsocket httpd: httpd.c # $(LIBS) 取LIBS对应的值 # $@ 表示目标文件 # $^ 所有的依赖文件 # $< 第一个依赖文件 gcc -g -W -Wall $(LIBS) -o $@ $< client: simpleclient.c gcc -W -Wall -o $@ $< clean: rm httpd
Makefile的语法主要如下:
# target 目标文件 # prerequisties 生成target所需要的文件或者目标 # command make需要执行的命令 target: prerequisties command
这里简单介绍Makefile到这,因为里面内容太多,所以下次专门写一篇文章,或者一系列文章介绍。
总结TinyHttpd是一个非常简易的Web Server,实现了Http报文的发送接收与处理的功能,其内部使用了网络编程,多进程的技术。本例子是网络编程中一个非常简单的例子。



