小微http服务器Tinyhttpd源码分析

2019/6/17 posted in  源码分析

完整源代码参考:https://github.com/EZLippi/Tinyhttpd/blob/master/httpd.c

这个项目的调用关系图如下

库文件

#include <stdio.h> 提供perror函数
#include <sys/socket.h> 提供 accept等socket函数
#include <sys/types.h> 提供 u_short 类型
#include <netinet/in.h> 提供sockaddr_in结构体
#include <arpa/inet.h> 提供htons函数
#include <unistd.h> 提供close, dup, dup2等函数
#include <ctype.h> 提供isspace函数
#include <strings.h> 提供strcasecmp函数
#include <string.h> 提供strcat函数
#include <sys/stat.h> 提供检查文件是否存在的stat函数
#include <pthread.h> 提供pthread_create函数
#include <sys/wait.h> 提供wait函数
#include <stdlib.h> 提供printf函数
#include <stdint.h> 提供intptr_t类型

main函数

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)
    {
        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);
}

结合上面代码和调用图,main函数中直接调用的函数如下:

  1. accept_request
  2. close
  3. error_die
  4. startup
  5. printf
  6. accept
  7. pthread_create

其中close来自函数库
printf来自函数库
accept来自函数库
pthread_create来自函数库

main函数中主要调用了startup函数,并启动了一个死循环,使用socket的accept接受客户端的连接后,使用pthread_create函数启动了一个新的线程使用accept_request函数处理这个客户端的请求

这个accept因为会同步阻塞,所以使用这个accept处理客户端连接的方式又称为BIO,如果这里使用select选出就绪的客户端就称为NIO了

error_die函数

void error_die(const char *sc)
{
    perror(sc);
    exit(1);
}

这个error_die函数比较简单,只是调用了perror函数后就退出了程序,所以调用error_die的地方都会退出程序

perror函数参考:https://pubs.opengroup.org/onlinepubs/009695399/functions/perror.html

startup函数

int startup(u_short *port)
{
    int httpd = 0;
    int on = 1;
    struct sockaddr_in name;

    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");
    }
    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);
}

startup函数直接调用了

  1. error_die
  2. setsockopt
  3. bind
  4. socket
  5. getsockname
  6. listen

这个startup直接调用的所有函数都是来自socket.h函数库,参考:https://pubs.opengroup.org/onlinepubs/009695399/functions/socket.html

这个函数主要是创建了一个socket服务器并在4000端口进行监听,如果有客户端连接这个4000端口,使用socket的accept函数可以和这个客户端进行通信

accept_request函数

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;      /* becomes true if server decides this is a CGI
                       * program */
    char *query_string = NULL;

    numchars = get_line(client, buf, sizeof(buf));
    i = 0; j = 0;
    while (!ISspace(buf[i]) && (i < sizeof(method) - 1))
    {
        method[i] = buf[i];
        i++;
    }
    j=i;
    method[i] = '\0';

    if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
    {
        unimplemented(client);
        return;
    }

    if (strcasecmp(method, "POST") == 0)
        cgi = 1;

    i = 0;
    while (ISspace(buf[j]) && (j < numchars))
        j++;
    while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < numchars))
    {
        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");
    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");
        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);
}

这个accept_request函数代码接近100行,这个函数中对客户端的请求进行了处理
主要职责如下:

  1. 解析http请求中的method,比如get, post,put,delete等, 一个http请求示例如下 GET /onlinepubs/009695399/functions/socket.html HTTP/1.1
    Host: pubs.opengroup.org
  2. 如果是get请求,获取请求的uri,比如上面的示例对应的uri就是/onlinepubs/009695399/functions/socket.html
  3. 不允许GET, POST以外的所有请求

参考资料

  1. close函数参考:https://pubs.opengroup.org/onlinepubs/009695399/functions/close.html
  2. isspace函数参考:https://pubs.opengroup.org/onlinepubs/009695399/functions/isspace.html
  3. stat函数参考:https://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html
  4. ctype.h参考:https://www.tutorialspoint.com/c_standard_library/ctype_h.htm
  5. string.h参考:https://www.tutorialspoint.com/c_standard_library/string_h.htm
  6. strings.h参考:https://pubs.opengroup.org/onlinepubs/7908799/xsh/strings.h.html
  7. wait.h参考:https://pubs.opengroup.org/onlinepubs/7908799/xsh/syswait.h.html
  8. netinet/in.h参考:http://pubs.opengroup.org/onlinepubs/009695399/basedefs/netinet/in.h.html
  9. arpa/inet.h参考:http://pubs.opengroup.org/onlinepubs/007908799/xns/arpainet.h.html
  10. stdint.h参考:https://pubs.opengroup.org/onlinepubs/009695399/basedefs/stdint.h.html

持续更新...