Tinyhttpd源码分析——超轻量级的HTTP服务器

前言

Tinyhttpd是一个不到500行的超轻量级的 Http Server,通过阅读这里面的源码,可以帮助大家理解服务器程序的本质。这个项目比较适合刚学习Linux服务器开发或刚学网络编程的人,因为整个项目所涉及到的知识并不多。这里面的知识点不多,但是有几个小知识若是要细究的话,还是可以发现很多问题的。

下载地址:

http://sourceforge.net/projects/tinyhttpd/

https://github.com/EZLippi/Tinyhttpd

 

源码阅读顺序: 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。接着关闭所有管道,等待子进程结束。

(10)关闭与浏览器的连接,完成了一次HTTP请求与回应,因为HTTP是无连接的。

 

源代码如下:

#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.0\r\n"
#define STDIN   0
#define STDOUT  1
#define STDERR  2

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




// Http请求,后续主要是处理这个头
//
// GET /su?wd=&action=opensearch&ie=UTF-8 HTTP/1.1
// Host: suggestion.baidu.com
// Connection: keep-alive
// Upgrade-Insecure-Requests: 1
// User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 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
// 
//

// POST / color1.cgi HTTP / 1.1
// Host: 
// Connection : keep - alive
// Content - Length : 10
// Cache - Control : max - age = 0
// Origin : 
// Upgrade - Insecure - Requests : 1
// User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 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: 
// Accept-Encoding: gzip, deflate
// Accept-Language: zh-CN,zh;q=0.8
// Form Data
// color=gray




/**********************************************************************/
/* 请求导致服务器端口上的accept()调用返回。适当地处理请求。
 * 参数:连接到客户端的套接字 */
/**********************************************************************/
void accept_request(void *arg)
{
    int client = (intptr_t)arg;
    char buf[1024];
    size_t numchars;
    char method[255];
    char url[255];
    char path[512];
    size_t i, j;
    struct stat st;
    int cgi = 0;      /* 如果服务器认为这是一个CGI程序,则为真 */
    char *query_string = NULL;
	
	//根据上面的Get请求,可以看到这边就是取第一行
    //这边都是在处理第一条http信息
    numchars = get_line(client, buf, sizeof(buf));
    i = 0; j = 0;
	
	//第一行字符串提取请求方法,即把客户端的请求方法存到 method 数组
    while (!ISspace(buf[i]) && (i < sizeof(method) - 1))
    {
        method[i] = buf[i];
        i++;
    }
    j=i;
    method[i] = '\0';
	
	
	//如果既不是 GET 又不是 POST 则无法处理
    if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
    {
        unimplemented(client);
        return;
    }
	
	//如果是POST,cgi置为1
    if (strcasecmp(method, "POST") == 0)
        cgi = 1;

    i = 0;
	//跳过空格
    while (ISspace(buf[j]) && (j < numchars))
        j++;
	
	
	//得到 "/"   注意:如果你的http的网址为http://IP:端口/index.html
    //                 那么你得到的第一条http信息为GET /index.html HTTP/1.1,那么
    //                 解析得到的就是/index.html
    while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < numchars))
    {
        url[i] = buf[j];
        i++; j++;
    }
    url[i] = '\0';
	
	
	//处理 GET 方法
    if (strcasecmp(method, "GET") == 0)
    {	//待处理请求为 url
        query_string = url;
        while ((*query_string != '?') && (*query_string != '\0'))
            query_string++;
		//GET 方法特点,? 后面为参数
        if (*query_string == '?')
        {
            cgi = 1;   //开启 cgi
            *query_string = '\0';
            query_string++;
        }
    }
	
	//格式化 url 到 path 数组,html 文件都在 htdocs 中
    sprintf(path, "htdocs%s", url);
	
	//默认地址,解析到的路径如果为/,则自动加上index.html
    if (path[strlen(path) - 1] == '/')
        strcat(path, "index.html");
	
	//获得文件信息
    if (stat(path, &st) == -1) {
        while ((numchars > 0) && strcmp("\n", buf))  //把所有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程序,如果有执行权限但是不能执行,会接受到报错信号
        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
            execute_cgi(client, path, method, query_string);//执行cgi文件
    }

    close(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);
}

/**********************************************************************/
/* 将文件的全部内容放到套接字中。这个函数是以UNIX的"cat"命令命名的,
 * 因为只执行诸如pipe、fork和exec(“cat”)之类的操作可能更简单。
 * 参数:客户端套接字描述符
 *      指向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);
    }
}

/**********************************************************************/
/* 通知客户端CGI脚本无法执行。
 * 参数:客户端套接字描述符。 */
/**********************************************************************/
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);
}

/**********************************************************************/
/* 使用perror()打印错误消息(用于系统错误;根据errno的值,
 * 该值指示系统调用错误)退出指示错误的程序。*/
/**********************************************************************/
void error_die(const char *sc)
{
    perror(sc);
    exit(1);
}

/**********************************************************************/
/* 执行CGI脚本。将需要设置适当的环境变量。
 * 参数:客户端套接字描述符
 *      到CGI脚本的路径 */
/**********************************************************************/
void execute_cgi(int client, const char *path,
        const char *method, const char *query_string)
{
    char buf[1024];        //缓冲区
    int cgi_output[2];     //2根管道
    int cgi_input[2];
    
	pid_t pid;             //进程pid和状态
    int status;
    
	int i;
    char c;
    int numchars = 1;      //读取的字符数
    int content_length = -1;   //http的content_length

    buf[0] = 'A'; buf[1] = '\0';  //默认字符
    if (strcasecmp(method, "GET") == 0)
		//读取数据,把整个header都读掉,因为Get写死了直接读取index.html,没有必要分析余下的http信息了
        while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */
            numchars = get_line(client, buf, sizeof(buf));
    else if (strcasecmp(method, "POST") == 0) /*POST*/
    {
        numchars = get_line(client, buf, sizeof(buf));
        while ((numchars > 0) && strcmp("\n", buf))
        {
			//如果是POST请求,就需要得到Content-Length,Content-Length:这个字符串一共长为15位,所以
            //取出头部一句后,将第16位设置结束符,进行比较
            //第16位置为结束
            buf[15] = '\0';
            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;
        }
    }
    else/*HEAD or other*/
    {
    }

	//建立output管道
    if (pipe(cgi_output) < 0) {
        cannot_execute(client);
        return;
    }
	
	//建立input管道
    if (pipe(cgi_input) < 0) {
        cannot_execute(client);
        return;
    }

	//fork进程,子进程用于执行CGI
    //父进程用于收数据以及发送子进程处理的回复数据
    if ( (pid = fork()) < 0 ) {
        cannot_execute(client);
        return;
    }
    sprintf(buf, "HTTP/1.0 200 OK\r\n");
    send(client, buf, strlen(buf), 0);
    if (pid == 0)  /* 子进程: CGI script */
    {
        char meth_env[255];
        char query_env[255];
        char length_env[255];

        dup2(cgi_output[1], STDOUT);//子进程输出重定向到output管道的1端
        dup2(cgi_input[0], STDIN);  //子进程输入重定向到input管道的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 {   /* POST */
            sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
            putenv(length_env);
        }
		//替换执行path
        execl(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);  //等待子进程返回
    }
}

/**********************************************************************/
/* 从套接字中获取一行,无论该行以换行、回车或CRLF组合结束。使用空字符终止读取的字符串。
 * 如果在缓冲区结束之前没有找到换行符,则字符串将以null结束。如果读取了上面三个行终止
 * 符中的任何一个,则该字符串的最后一个字符将是换行符,该字符串将以空字符结束。
 * 参数:套接字描述符
 *      保存数据的缓冲区
 *      缓冲区的大小
 * 返回:存储的字节数(不包括null)
 */
/**********************************************************************/
int get_line(int sock, char *buf, int size)
{
	//得到一行数据,只要发现c为\n,就认为是一行结束,如果读到\r,再用MSG_PEEK的方式读入一个字符,如果是\n,从socket用读出
    //如果是下个字符则不处理,将c置为\n,结束。如果读到的数据为0中断,或者小于0,也视为结束,c置为\n
    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)
        {	//收到 \r 则继续接收下个字节,因为换行符可能是 \r\n 
            if (c == '\r')
            {	//使用 MSG_PEEK 标志使下一次读取依然可以得到这次读取的内容,可认为接收窗口不滑动
                n = recv(sock, &c, 1, MSG_PEEK);
                /* DEBUG printf("%02X\n", c); */
				//如果是换行符则把它接收,这里可以理解成跳过'\n'
                if ((n > 0) && (c == '\n'))
                    recv(sock, &c, 1, 0);
                else
                    c = '\n';      //不是\n(读到下一行的字符)或者没读到,置c为\n 跳出循环,完成一行读取
            }
            buf[i] = c;
            i++;
        }
        else
            c = '\n';
    }
    buf[i] = '\0';

    return(i);
}

/**********************************************************************/
/* 返回关于文件的HTTP头信息。 */
/* 参数:套接字
 *      文件名 */
/**********************************************************************/
void 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"); //正常的 HTTP header
    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);
}

/**********************************************************************/
/* 给客户端一个404 not found状态消息。 */
/**********************************************************************/
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)
{   //如果不是CGI文件,直接读取文件返回给请求的http客户端
    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));
	
	//打开 sever 的文件
    resource = fopen(filename, "r");
    if (resource == NULL)
        not_found(client);
    else
    {
        headers(client, filename);   //写 HTTP header 
        cat(client, resource);       //复制文件
    }
    fclose(resource);
}

/**********************************************************************/
/* 该函数启动监听指定端口上的web连接的过程。如果端口为0,
 * 则动态分配端口并修改原始端口变量以反映实际端口。
 * 参数:指向包含要连接的端口的变量的指针
 * 返回:socket */
/**********************************************************************/
int startup(u_short *port)
{
    int httpd = 0;
    int on = 1;
    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);
    if ((setsockopt(httpd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) < 0)  
    {  
        error_die("setsockopt failed");
    }
	//绑定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);
}

/**********************************************************************/
/* 通知客户端所请求的web方法尚未实现。
 * 参数:客户端套接字 */
/**********************************************************************/
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)
{
    int server_sock = -1;
    u_short port = 4000;
    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 %d\n", 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");
        /* accept_request(&client_sock); */
		//每次收到请求,创建一个线程来处理接受到的请求
        if (pthread_create(&newthread , NULL, (void *)accept_request, (void *)(intptr_t)client_sock) != 0)
            perror("pthread_create");
    }

    close(server_sock);

    return(0);
}

 

参考:https://blog.csdn.net/jcjc918/article/details/42129311

 

发布了77 篇原创文章 · 获赞 178 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/qq_38289815/article/details/103773722
今日推荐