今天学一下很早之前在github看到的一个httpd项目,一直打算看一下拖到了现在。立刻开学

项目地址https://github.com/EZLippi/Tinyhttpd

socket相关

  • struct sockaddr_in,in_addr
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #include <netinet/in.h>

    struct sockaddr_in {
    short sin_family; // e.g. AF_INET
    unsigned short sin_port; // e.g. htons(3490)
    struct in_addr sin_addr; // see struct in_addr, below
    char sin_zero[8]; // zero this if you want to
    };

    struct in_addr {
    unsigned long s_addr; // load with inet_aton()
    };
    这些是所有处理网络地址的系统调用和函数的基本结构。在内存中,struct sockaddr_instruct sockaddr的size是一样的,可以自由地在二者间转换指针(cast the pointer),且不造成任何损失,除非碰上可能的宇宙终结(except the possible end of the universe)

    老外这么逗吗

关于sin_zero有的人说要设置为0,有的人没什么说法(linux文档甚至没有提及这件事),设置为0似乎不是必须的,所以随意就好。

应该只使用s_addr这个字段,因为很多系统只实现这个。

对于IPv4,struct s_addr是一个四字节的数字,每个字节代表IP地址中的一个数字,不大于255。

  • bind
    1
    2
    3
    4
    #include <sys/types.h>
    #include <sys/socket.h>

    int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);
    首先可以调用socket()获得一个套接字描述符(socket descriptor),然后用IP和端口装载struct sockaddr_in,然后将二者传给bind(),则IP和端口就会被绑定到socket了

如果不知道自己的IP或者在机器上只有一个IP,或者不关心机器的哪一个IP地址被使用,可以直接设置s_addr字段为INADDR_ANY,会自动填充IP地址。

最后addr_len应该被设置为sozeof(my_addr)

返回值:成功返回0,error返回-1

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct sockaddr_in myaddr;
int s;

myaddr.sin_family = AF_INET;
myaddr.sin_port = htons(3490);

// you can specify an IP address:
inet_aton("63.161.169.137", &myaddr.sin_addr.s_addr);

// or you can let it automatically select one:
myaddr.sin_addr.s_addr = INADDR_ANY;

s = socket(PF_INET, SOCK_STREAM, 0);
bind(s, (struct sockaddr*)myaddr, sizeof(myaddr));
  • getsockopt、setsockopt

get and set option on sockets

1
2
3
4
5
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
int getsockopt(int sockfd, int level, int optname, void *optval,
socklen_t *optlen);int setsockopt(int sockfd, int level, int optname,
const void *optval, socklen_t optlen);

setsockopt()用来设置参数s 所指定的socket 状态. 参数level 代表欲设置的网络层, 一般设成SOL_SOCKET 以存取socket 层. 参数optname 代表欲设置的选项, 有下列几种数值:
SO_DEBUG 打开或关闭排错模式
SO_REUSEADDR 允许在bind ()过程中本地地址可重复使用
SO_TYPE 返回socket 形态.
SO_ERROR 返回socket 已发生的错误原因
SO_DONTROUTE 送出的数据包不要利用路由设备来传输.
SO_BROADCAST 使用广播方式传送
SO_SNDBUF 设置送出的暂存区大小
SO_RCVBUF 设置接收的暂存区大小
SO_KEEPALIVE 定期确定连线是否已终止.
SO_OOBINLINE 当接收到OOB 数据时会马上送至标准输入设备
SO_LINGER 确保数据安全且可靠的传送出去.

optval代表欲设置的值,optlenoptval的长度

返回值:成功返回0,错误返回-1

  • socklen_t

该数据类型和int有相同的长度

  • listen

监听socket的连接

1
2
#include <sys/socket.h>
int listen(int sockfd, int backlog);

参数sockfd是一个引用socket的文件描述符,类型为SOCK_STREAMSOCK_SEQPACKET

backlog指定最大长度,sockfd的挂起连接队列可能会增长,如果一个请求达到时队列已满,客户端可能收到一个指示ECONNREFUSED的错误,或者如果底层协议支持重传,请求可以忽略一遍之后重新尝试连接成功

返回值:成功返回0,出错返回-1

  • accept, accpet4
1
2
3
4
5
6
7
8
9
10
#include <sys/socket.h>

int accept(int sockfd, struct sockaddr *restrict addr,
socklen_t *restrict addrlen);

#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <sys/socket.h>

int accept4(int sockfd, struct sockaddr *restrict addr,
socklen_t *restrict addrlen, int flags);

提取挂起的连接队列上的第一个连接请求,创建一个新的连接socket,返回一个新的文件描述符引用该socket。新创建的socket不处于监听状态,最初的sockfd不受此调用影响

  • htonl

htonl <=> host to network unsigned long

即将本机字节顺序转化为网络字节顺序(大端序)

  • ntohs

network to host short

网络字节顺序转化为本机字节顺序

stat相关

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <sys/stat.h>

int stat(const char *restrict pathname,
struct stat *restrict statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *restrict pathname,
struct stat *restrict statbuf);

#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>

int fstatat(int dirfd, const char *restrict pathname,
struct stat *restrict statbuf, int flags);

这些函数在指向statbuf的缓冲区里返回一个文件的信息,对于文件本身没有权限要求,但对于函数stat()fstatat()lstat()执行中所有目录都需要(搜索)权限指向文件名的路径名

stat结构体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* Inode number */
mode_t st_mode; /* File type and mode */
nlink_t st_nlink; /* Number of hard links */
uid_t st_uid; /* User ID of owner */
gid_t st_gid; /* Group ID of owner */
dev_t st_rdev; /* Device ID (if special file) */
off_t st_size; /* Total size, in bytes */
blksize_t st_blksize; /* Block size for filesystem I/O */
blkcnt_t st_blocks; /* Number of 512B blocks allocated */

/* Since Linux 2.6, the kernel supports nanosecond
precision for the following timestamp fields.
For the details before Linux 2.6, see NOTES. */

struct timespec st_atim; /* Time of last access */
struct timespec st_mtim; /* Time of last modification */
struct timespec st_ctim; /* Time of last status change */

#define st_atime st_atim.tv_sec /* Backward compatibility */
#define st_mtime st_mtim.tv_sec
#define st_ctime st_ctim.tv_sec
};

st_dev:描述文件所在的设备驻留
st_ino:包含文件的inode号
st_mode:包含文件类型和模式
st_nlink:包含指向该文件的硬链接的数量
st_uid:包含文件所有者的用户ID
st_gid:包含文件的组所有者的ID
st_rdev:描述这个文件(inode)对应的设备
st_size:以字节给出文件的大小(如果是一个普通文件或符号链接)。符号链接的大小是它包含的路径名称的长度,不包括null终结字节
st_blksize:给出“首选”块大小,以提高效率
st_blocks:表示分配给文件的块的数量,512字节单位
st_atime:最后一次访问文件数据的时间
st_mtime:最后一次修改文件数据的时间
st_ctime:文件最后一次状态更改时间戳(时间为对inode的最后更改)

现代linux操作系统上文件类型分为7种分别是普通文件(regular file)、目录(directory)、字符设备(character device)、块设备(block device)、管道(FIFO\、符号链接文件(symbolic link)、套接字文件(socket)。所以File type属性只需要3bit即可

一些宏定义。注意下面使用的是八进制
linux/include/uapi/linux/stat.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#define S_IFMT  00170000
#define S_IFSOCK 0140000
#define S_IFLNK 0120000
#define S_IFREG 0100000
#define S_IFBLK 0060000
#define S_IFDIR 0040000
#define S_IFCHR 0020000
#define S_IFIFO 0010000
#define S_ISUID 0004000
#define S_ISGID 0002000
#define S_ISVTX 0001000

#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
#define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
#define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
#define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)

#define S_IRWXU 00700 /* mask for file owner permissions */
#define S_IRUSR 00400 /* owner has read permission */
#define S_IWUSR 00200 /* owner has write permission */
#define S_IXUSR 00100 /* owner has execute permission */

#define S_IRWXG 00070 /* mask for group permissions */
#define S_IRGRP 00040 /* group has read permission */
#define S_IWGRP 00020 /* group has write permission */
#define S_IXGRP 00010 /* group has execute permission */

#define S_IRWXO 00007 /* mask for permissions for others (not in group) */
#define S_IROTH 00004 /* others have read permission */
#define S_IWOTH 00002 /* others have write permission */
#define S_IXOTH 00001 /* others have execute permission */

作用:例如判断一个文件是不是目录

1
2
if ((info.st_mode & S_IFMT) == S_IFDIR)
printf("directory");

或者直接利用写好的宏定义
1
2
3

if (S_ISDIR(info.st_mode))
printf("directory");

再下面一些定义是关于文件权限的

pipe相关

从概念上讲,管道是两个进程之间的连接,以便一个进程的标准输出成为另一个进程的标准输入。在UNIX操作系统中,管道用于相关进程之间的通信(进程间通信)(inter-process communication)

  • 管道是单向通信,可以使用这样的管道:一个进程写入管道,另一个进程从管道读取。打开一个管道,这个管道是一个主存区域,则它被视为虚拟文件(virtual file)
  • 创建进程及其子进程可以用管道来读写。一个进程被写入到此“虚拟文件”或管道,而另一个相关进程可以从中读取
  • 如果一个进程尝试在向管道写入的之前进行读取,则该进程被挂起直到写入完成
  • 管道系统调用找到进程打开文件表(open file’s table)中前两个可用位置并将它们分配给管道的读写端
1
2
3
4
5
6
7
8
int pipe(int fds[2]);

Parameters :
fd[0] will be the fd(file descriptor) for the
read end of pipe.
fd[1] will be the fd for the write end of pipe.
Returns : 0 on Success.
-1 on error.

管道表现为先进先出,表现为队列数据结构。读取和写入的大小在这里不必匹配。可以一次写入512字节但每次在管道中只读出1字节。

使用pipe进行父子进程间通信

当在任意进程中使用fork时,文件描述符在父进程和子进程中都是打开的,如果在创建pipe之后调用fork,就可以通过管道进行父子进程间的通信

  • 如果管道为空,我们调用read系统调用,如果没有进程打开写端,那么管道上的read就会返回EOF(返回值0)
  • 如果其他进程打开了写入的端口,则么read就会因为等待新数据而阻塞。

代码解读

总览

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* 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>
#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* 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);

main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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, accept_request, (void*)&client_sock) != 0)
// perror("pthread_create");
}

close(server_sock);

return(0);
}

设置端口为监听为4000,startup函数在下面有详解。
之后进入死循环监听端口,监听到了就把返回的socket传给accept_request,处理请求。

startup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**********************************************************************/
/* 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;
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);
}

建立socket连接,将IP和端口绑定。这里IP的绑定使用的是INADDR_ANY意思就是自动分配IP。
setsockoptSO_REUSEADDR指定在bind ()过程中本地地址可重复使用
listen开始监听,设置队列最大容量为5

accept_request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**********************************************************************/
/* 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];
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);
}

传入的参数为&client_sock即accpet到返回的socket描述符

numchars = get_line(client, buf, sizeof(buf));是通过socket接收发过来的内容(即报文信息)存到buf里,接收的字节数赋值给numchars

接下来一个循环遍历buf每一个字节,逐字节存进method字符数组直到碰到空白符。这里就会把HTTP方法存到method

然后判断method如果不是GET或POST,调用unimplemented表示没有实现这个方法

如果是POST则令cgi=1

接着遍历buf,跳过空白符
然后逐字节存url

如果method是GET,操作url字串,当当前字符不是?\0时指针一直向前指
如果开头是?,则cgi=1,然后问号清除,指针前移一位,接在htdocs后面写入path变量

如果path最后一个字符是/则拼接上index.html

接下来使用stat判断path指向的文件是否存在,若不存在则读取并丢弃headers。最后调用not_found,该函数会返回给客户端404对应界面

如果页面存在,则接着通过if ((st.st_mode & S_IFMT) == S_IFDIR)判断是不是目录。如果路径是目录就在最后拼接上/index.html

如果拥有者可执行或组可执行或其他用户可执行则cgi赋1

接着cgi若为0进serve_file;cgi为1进execute_cgi

函数最后close(client)关闭socket

get_line

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**********************************************************************/
/* 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) */
/**********************************************************************/
int get_line(int sock, char *buf, int size)
{
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)
{
if (c == '\r')
{
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);
}

not_found

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**********************************************************************/
/* 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);
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);
}

server_file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**********************************************************************/
/* 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));

resource = fopen(filename, "r");
if (resource == NULL)
not_found(client);
else
{
headers(client, filename);
cat(client, resource);
}
fclose(resource);
}

读取并丢弃报头,以只读打开文件,若为空返回not_found;否则返回一个关于该文件的包。header用来生成报文头,cat用来读取并发送该文件的内容

最后关闭文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**********************************************************************/
/* Return the informational HTTP headers about a file. */
/* Parameters: the socket to print the headers on
* the name of the file */
/**********************************************************************/
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");
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);
}

cat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**********************************************************************/
/* 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(client, buf, strlen(buf), 0);
fgets(buf, sizeof(buf), resource);
}
}

execute_cgi

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**********************************************************************/
/* 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 if (strcasecmp(method, "POST") == 0) /*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;
}
}
else/*HEAD or other*/
{
}


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;
}
sprintf(buf, "HTTP/1.0 200 OK\r\n");
send(client, buf, strlen(buf), 0);
if (pid == 0) /* child: CGI script */
{
char meth_env[255];
char query_env[255];
char length_env[255];

dup2(cgi_output[1], STDOUT);
dup2(cgi_input[0], STDIN);
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, 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);
}
}

执行cgi了

首先判断方法如果是GET则读取并丢弃报文
如果是POST就逐行读取直到读出content_length

如果读不到则调用bad_request返回一个出错的报文

接着利用pipe创建两个管道cgi_input和cgi_output,然后创建子进程

先把200状态码报文头发回去

  • 子进程

然后使用dup2复制文件描述符,把标准输出复制(重定向)到cgi_output写端,把标准输入复制(重定向)到cgi_input写端,然后把cgi_input读端,然后关闭cgi_input的读端和cgi_output的写端。

根据方法如果是GET赋值query_env,如果是POST赋值length_env。这些是环境变量为了给cgi脚本调用

perl CGI程序环境变量如下

变量名 描述
CONTENT_TYPE 这个环境变量的值指示所传递来的信息的MIME类型。目前,环境变量CONTENT_TYPE一般都是:application/x-www-form-urlencoded,他表示数据来自于HTML表单。
CONTENT_LENGTH 如果服务器与CGI程序信息的传递方式是POST,这个环境变量即使从标准输入STDIN中可以读到的有效数据的字节数。这个环境变量在读取所输入的数据时必须使用。
HTTP_COOKIE 客户机内的 COOKIE 内容。
HTTP_USER_AGENT 提供包含了版本数或其他专有数据的客户浏览器信息。
PATH_INFO 这个环境变量的值表示紧接在CGI程序名之后的其他路径信息。它常常作为CGI程序的参数出现。
QUERY_STRING 如果服务器与CGI程序信息的传递方式是GET,这个环境变量的值即使所传递的信息。这个信息经跟在CGI程序名的后面,两者中间用一个问号’?’分隔。
REMOTE_ADDR 这个环境变量的值是发送请求的客户机的IP地址,例如上面的192.168.1.67。这个值总是存在的。而且它是Web客户机需要提供给Web服务器的唯一标识,可以在CGI程序中用它来区分不同的Web客户机。
REMOTE_HOST 这个环境变量的值包含发送CGI请求的客户机的主机名。如果不支持你想查询,则无需定义此环境变量。
REQUEST_METHOD 提供脚本被调用的方法。对于使用 HTTP/1.0 协议的脚本,仅 GET 和 POST 有意义。
SCRIPT_FILENAME CGI脚本的完整路径
SCRIPT_NAME CGI脚本的的名称
SERVER_NAME 这是你的 WEB 服务器的主机名、别名或IP地址。
SERVER_SOFTWARE 这个环境变量的值包含了调用CGI程序的HTTP服务器的名称和版本号。例如,上面的值为Apache/2.2.14(Unix)

然后执行脚本
最后exit退出

  • 父进程

关闭cgi_output的写端,关闭cgi_input的读端,如果方法是POST则把POST对应的方法通过cgi_input写端写入。然后逐字节从cgi_output读端读出,并发送给client

最后关闭cgi_output的读端和cgi_input的写端
然后waitpid等待子进程结束

上面其实就是父进程把POST传过来的数据通过管道发给子进程,然后子进程调用cgi程序,cgi程序使用perl脚本编写。根据perl的性质方法为POST时,content_length指明从标准输入STDIN可以读到的有效数据的字节数,所以子进程中设置好了content_length的值,父进程把收到的数据通过管道发到子进程,就能传进perl编写的cgi中。
color.cgi内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/perl -Tw

use strict;
use CGI;

my($cgi) = new CGI;

print $cgi->header;
my($color) = "blue";
$color = $cgi->param('color') if defined $cgi->param('color');

print $cgi->start_html(-title => uc($color),
-BGCOLOR => $color);
print $cgi->h1("This is $color");
print $cgi->end_html;

意思就是根据color参数设置$color,默认blue。-BGCOLOR直接设置背景颜色
实际上传入的数据为color=RED

error_die

1
2
3
4
5
6
7
8
9
10
/**********************************************************************/
/* 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);
}

cannot_execute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**********************************************************************/
/* 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);
}

unimplemented

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**********************************************************************/
/* 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);
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);
}

总结

通过阅读学习Tinyhttpd,看到了一个简单的httpd工作流程,学习了socket、stat、pipe相关知识,尤其是在执行cgi中通过pipe进行父子进程间的通信是非常常见的一种进程间通信方式。另外也稍微了解了一下perl语言。