ubuntu下编译运行tinyhttpd方法及源码解析

来源:互联网 发布:志鸿优化系列丛书2017 编辑:程序博客网 时间:2024/06/08 03:15

提要

之前在读unp的时候就很疑惑这些socket API究竟是怎么用的,感觉跟日常的web好像关系不是很大。在一次调试flask源码的时候,当我进到httpserver和werkzeug工具集的源码里时,看到了很多形似unix下socket API的函数,至此我对unp就有了进一步的了解了。在应用层中,最底层的服务器其实就是靠这些API所开发并运行的,往往担负着接受请求,分发请求,解读请求的作用。

tinyhttpd

tinyhttpd应该是最简单的一个C语言的服务器开源项目了,总长就500行左右。很建议unp的初学者(比如我这样一开始连unp怎么用都搞不清楚的)去了解,读完相信会对网络编程有了更深的理解。

编译运行

可以到官网去下载到它的源码:tinyhttpd
下载后得到一个tar.gz结尾的压缩包,解压缩就可以看到如下的文件和目录了:
这里写图片描述
没有config之类的文件,只有一个Makefile,在终端打开,直接make就可以生成可执行文件了。不过make之前有些地方需要修改,因为tinyhttpd的作者是在Solaris下开发的,并不适合linux下直接编译。
需要改动的地方有以下几项:

  • 33行的函数声明改为void accept_request(void ); 所以下面的函数定义也要跟着修改。
  • 将accept_request函数77行的return改为return NULL; 在128行close(client);后面添加return NULL;
  • 439行和484行的变量类型改为socklen_t。
  • 498行改为if (pthread_create(&newthread , NULL, accept_request, (void*)&client_sock) != 0)

行数不一定准确,但一般就在附近。
这时就可以make生成httpd可执行文件了。
在终端输入 ./httpd 就可以运行服务器了,并且可以得到当前的运行端口号
这里写图片描述
在浏览器输入localhost:45962就可以得到页面了
这里写图片描述
页面上提示说是一个CGI demo。CGI本意是通用网关接口,实际上是一个生成响应内容的脚本程序。
比如服务器接收到来自服务器的请求,它可以选择把请求传递给一个CGI程序,由它来根据请求生成内容,CGI程序把生成的内容返回给服务器,服务器再把这个内容返回给客户端。服务器程序只负责处理请求,不负责处理内容。
它其实算是一种web开发的思路,现在也仍有使用,不过使用范围还是相对较小。因此你会有时看到某些网页(据我观察数字尾巴就是这样)的地址明明是访问某个php或者py的文件,它弹出来的却不是代码,还是正儿八经的网页,就是网页的内容在这些php文件或者python文件里动态生成了,然后返回到浏览器。

那么更好玩的来了,我们可以自己找一个纯html文件,没有js代码那种,或者文本文件,重命名为index.html,放到htdocs文件夹里,这时候再访问,浏览器显示的就是我们自定义的内容了~

http请求

为了更好地理解源码,这里先简单介绍一点http请求的知识。
告知服务器意图的 HTTP 方法
体现在TinyHTTPd中的为 GET 和 POST method。

GET:获取资源
GET 方法用来请求访问已被 URI 识别的资源。指定的资源进服务器端解析后返回响应内容。换言之,如果请求的资源是文本(静态页面请求),那就保持原样返回;如果是像CGI 那样的程序(动态页面请求),则返回经过执行后的输出结果。
这里写图片描述

POST:传输实体主体
POST 的主要目的是用来传输实体的主体,不是获取响应的主体内容
这里写图片描述

当使用浏览器访问服务器时,浏览器会向服务器发起一个http请求。请求类似上两张图的里的请求,以请求类型(GET或者POST)开头,紧接着的请求的资源路径。因此,请求类型和请求路径可以从请求的第一行获取。


函数功能介绍

先简单地解释每个函数的作用:

accept_request: 处理从套接字上监听到的一个 HTTP 请求,在这里可以很大一部分地体现服务器处理请求流程。
bad_request: 返回给客户端这是个错误请求,HTTP 状态吗 400 BAD REQUEST.
cat: 读取服务器上某个文件写到 socket 套接字。
cannot_execute: 主要处理发生在执行 cgi 程序时出现的错误。
error_die: 把错误信息写到 perror 并退出。
execute_cgi: 运行 cgi 程序的处理,也是个主要函数。
get_line: 读取套接字的一行,把回车换行等情况都统一为换行符结束。
headers: 把 HTTP 响应的头部写到套接字。
not_found: 主要处理找不到请求的文件时的情况。
sever_file: 调用 cat 把服务器文件返回给浏览器。
startup: 初始化 httpd 服务,包括建立套接字,绑定端口,进行监听等。

建议源码阅读顺序: main -> startup -> accept_request -> execute_cgi, 通晓主要工作流程后再仔细把每个函数的源码看一看。

工作流程

(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    管道初始状态
图 1 管道初始状态
图 2  管道最终状态
图 2 管道最终状态
(10) 关闭与浏览器的连接,完成了一次 HTTP 请求与回应,因为 HTTP 是无连接的。

源码注释

这里附上我自己注释过的源码,希望能对阅读有帮助。

/* 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(void * tclient);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(void * tclient){ int client = *(int *) tclient; char buf[1024]; int numchars; char method[255]; char url[255]; char path[512]; size_t i, j; struct stat st; int cgi = 0;      /* becomes true if server decides this is a CGI                    * program */ char *query_string = NULL;//get_line是读取一行的意思。读取http请求,每行以\r\n结尾//buf里的内容是http请求里的第一行 numchars = get_line(client, buf, sizeof(buf)); i = 0; j = 0; //ISspace检查参数是否为空格。即最多读取255个字符,直到空格为止 //根据http请求的格式,method里的内容是http请求的请求类型,GET或POST while (!ISspace(buf[j]) && (i < sizeof(method) - 1)) {  method[i] = buf[j];  i++; j++; } method[i] = '\0';//strcasecmp是忽略大小写的比较 if (strcasecmp(method, "GET") && strcasecmp(method, "POST")) {  unimplemented(client);  return NULL; } if (strcasecmp(method, "POST") == 0)  cgi = 1; 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'; if (strcasecmp(method, "GET") == 0) {  query_string = url;  while ((*query_string != '?') && (*query_string != '\0'))   query_string++;  if (*query_string == '?')  {   cgi = 1;   *query_string = '\0';   query_string++;  } } sprintf(path, "htdocs%s", url); if (path[strlen(path) - 1] == '/')  strcat(path, "index.html");  //在服务器本地打开资源失败的情况下,给客户端发送notfound if (stat(path, &st) == -1) {  while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */   numchars = get_line(client, buf, sizeof(buf));  not_found(client); } else { //如果是目录,继续拼接  if ((st.st_mode & S_IFMT) == S_IFDIR)   strcat(path, "/index.html"); //如果是可执行文件,将cgi置1   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); return NULL;}/**********************************************************************//* Inform the client that a request it has made has a problem. * Parameters: client socket *//**********************************************************************/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);}/**********************************************************************//* 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[1024]; fgets(buf, sizeof(buf), resource); while (!feof(resource)) { //send是write的高级版本  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. *//**********************************************************************/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);}/**********************************************************************//* 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 *//**********************************************************************/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'; 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';   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); if (pipe(cgi_output) < 0) {  cannot_execute(client);  return; } if (pipe(cgi_input) < 0) {  cannot_execute(client);  return; } 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);  dup2(cgi_input[0], 0);  close(cgi_output[0]);  close(cgi_input[1]);  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 {   /* POST */   sprintf(length_env, "CONTENT_LENGTH=%d", content_length);   putenv(length_env);  }  execl(path, path, NULL);  exit(0); } else {    /* parent */  close(cgi_output[1]);  close(cgi_input[0]);  if (strcasecmp(method, "POST") == 0)   for (i = 0; i < content_length; i++) {    recv(client, &c, 1, 0);    write(cgi_input[1], &c, 1);   }  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); }}/**********************************************************************//* 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) *//**********************************************************************///从sock读取一行内容int get_line(int sock, char *buf, int size){ int i = 0; char c = '\0'; int n; while ((i < size - 1) && (c != '\n')) { //recv是高级IO里的一个函数,flag参数为0,则实际效果等同于read  n = recv(sock, &c, 1, 0);  /* DEBUG printf("%02X\n", c); */  if (n > 0)  {   if (c == '\r')   {   //MSG_PEEK表示查看读取,读完不丢弃    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);}/**********************************************************************//* Return the informational HTTP headers about a file. *//* Parameters: the socket to print the headers on *             the name of the file *//**********************************************************************///response的headersvoid 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");  //以下开始是body send(client, buf, strlen(buf), 0);}/**********************************************************************//* Give a client a 404 not found status message. *//**********************************************************************///无法找到资源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);  //以下开始是body 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 *//**********************************************************************///向客户点套接字传输文件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));//fopen是打开一个标准I/O流 resource = fopen(filename, "r"); if (resource == NULL)  not_found(client); else { //先发送response header  headers(client, filename); //再发送response 主体  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 = 0; struct sockaddr_in name;//PF_INET和AF_INET含义一样 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); if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)  error_die("bind"); if (*port == 0)  /* if dynamically allocating a port */ {  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);}/**********************************************************************//* 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);  //以下开始是body 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){ int server_sock = -1; //port赋值为0,则让内核选择ip地址和端口 u_short port = 0; int client_sock = -1; struct sockaddr_in client_name; socklen_t client_name_len = sizeof(client_name); //保存线程ID pthread_t newthread; 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, (void *)&client_sock) != 0)   perror("pthread_create"); } close(server_sock); return(0);}

参考文章:
【源码剖析】tinyhttpd —— C 语言实现最简单的 HTTP 服务器
TinyHTTPd 编译及 HTTP 浅析