點擊鏈接看github repo蚪腐。
Forked from cbsheng/tinyhttpd
tinyhttpd是一個500行的極簡HTTP服務器,持CGI胎食。代碼量少逗宜,非常容易閱讀,十分適合網(wǎng)絡編程初學者學習的項目剃诅。麻雀雖小巷送,五臟俱全。在tinyhttpd中可以學到 linux 上進程的創(chuàng)建矛辕,管道的使用笑跛。linux 下 socket 編程基本方法和http 協(xié)議的最基本結(jié)構(gòu)。
在cbsheng的基礎上聊品,添加了一些注釋飞蹂,幫助閱讀源碼,針對The Linux Programming Interface翻屈,使用了章節(jié)索引替代了原來的頁碼索引陈哑。
代碼非常簡單,和你一樣我也是初學者可以多關注一下以下兩個方面:
- Unix Socket Stream Server的通常流程
- 使用pipe做父子進程通信
tinyhttpd流程
流程圖包含了一個典型的Unix socket stream server的流程伸眶,可詳見:TLPI 56.5.
使用pipe做相關進程通信
Pipe是Unix like系統(tǒng)上最古老的IPC方法惊窖。它為一個常見需求提供了一個優(yōu)雅的解決方案:給定兩個運行不同程序的進程,如何讓一個進程的輸出作為另一個進程的輸入赚抡?管道可以用于在相關進程之間傳遞數(shù)據(jù)爬坑。
tinyhttpd中創(chuàng)建子進程來執(zhí)行cgi腳本的函數(shù)可以很好地用來學習pipe梧奢。
先來看代碼珊拼。
/**********************************************************************/
/* 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;
//省略若干行不相關代碼
//下面這里創(chuàng)建兩個管道,用于兩個進程間通信脊髓,參考《TLPI》44.2
/*
#include <unistd.h>
int pipe(int fields); //return 0 on succ, -1 on err.
成功的pipe()調(diào)用會在fields中返回兩個打開的文件描述符:一個表示管道的讀取端(fields[0]),另一個表示寫入端(fields[1])署辉。
父子進程都通過一個pipe讀寫信息是可以的族铆,但是很不常見,創(chuàng)建pipe,fork()創(chuàng)建子進程之前:
[ parent process ]
- [fields[1] fields[0]]<-
| |
-> [-------pipe------>]-
| |
- [fields[1] fields[0]]<-
[ sub process ]
通常fork()后哭尝,其中一個進程需要立即關閉管道寫入端描述符哥攘,另一個關閉讀取描述符。關閉未使用描述符之后:
[ parent process ]
- [fields[1] ]
|
-> [-------pipe------>]-
|
[ fields[0]]<-
[ sub process ]
*/
if (pipe(cgi_output) < 0) {
cannot_execute(client);
return;
}
if (pipe(cgi_input) < 0) {
cannot_execute(client);
return;
}
/*
cgi_output是子進程(執(zhí)行cgi的進程)的輸出管道材鹦,子進程寫逝淹,父進程讀;
cgi_input是子進程(執(zhí)行cgi的進程)的輸入管道桶唐,父進程寫栅葡,子進程讀。
*/
//創(chuàng)建一個子進程 參考《TLPI》 24.2
/*
#include <unistd.h>
pid_t fork(void); //in parent, return processID of child on success or -1 on error; in successfully created child: always return 0
*/
if ( (pid = fork()) < 0 ) {
cannot_execute(client);
return;
}
//子進程用來執(zhí)行 cgi 腳本
if (pid == 0) /* child: CGI script */
{
char meth_env[255];
char query_env[255];
char length_env[255];
//dup2()包含<unistd.h>中尤泽,參讀《TLPI》5.5
//將子進程的輸出由標準輸出重定向到 cgi_ouput 的管道寫端上
/*
#include <unistd.h>
int dup2(int oldfd, int newfd); //return (new) file descritor on succ, -1 on err
為oldfd指定文件描述符創(chuàng)建副本欣簇,其編號由newfd指定。
*/
dup2(cgi_output[1], 1);
//將子進程的輸出由標準輸入重定向到 cgi_ouput 的管道讀端上
dup2(cgi_input[0], 0);
//關閉 cgi_ouput 管道的讀端與cgi_input 管道的寫端
close(cgi_output[0]);
close(cgi_input[1]);
//構(gòu)造一個環(huán)境變量
sprintf(meth_env, "REQUEST_METHOD=%s", method);
//putenv()包含于<stdlib.h>中坯约,參讀《TLPI》6.7
//將這個環(huán)境變量加進子進程的運行環(huán)境中
/*
#include <stdlib.h>
int putenv(char *string); //return 0 on succ, nonzero on err.
*/
putenv(meth_env);
//根據(jù)http 請求的不同方法熊咽,構(gòu)造并存儲不同的環(huán)境變量
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()包含于<unistd.h>中,參讀《TLPI》P567
//最后將子進程替換成另一個進程并執(zhí)行 cgi 腳本
/*
#include <unistd.h>
int execl(const char* pathname, const char *arg, ...); //not return on succ;return -1 on error.
*/
execl(path, path, NULL);
exit(0);
} else { /* parent */
//父進程則關閉了 cgi_output管道的寫端和 cgi_input 管道的讀端
close(cgi_output[1]);
close(cgi_input[0]);
//如果是 POST 方法的話就繼續(xù)讀 body 的內(nèi)容闹丐,并寫到 cgi_input 管道里讓子進程去讀
if (strcasecmp(method, "POST") == 0)
for (i = 0; i < content_length; i++) {
recv(client, &c, 1, 0);
write(cgi_input[1], &c, 1);
}
//然后從 cgi_output 管道中讀子進程的輸出横殴,并發(fā)送到客戶端去
while (read(cgi_output[0], &c, 1) > 0)
send(client, &c, 1, 0);
//關閉管道
close(cgi_output[0]);
close(cgi_input[1]);
//等待子進程的退出 《TLPI》26.1.2
/*
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options); //return process ID of child, 0, or -1 on err.
*/
waitpid(pid, &status, 0);
}
}
這段代碼很簡單,創(chuàng)建了一個子進程用于執(zhí)行CGI腳本妇智。子進程將標準輸入重定向到管道cgi_input的輸入滥玷,接受來自父進程的寫入;將標準輸出重定向到cgi_output的輸入巍棱,將信息發(fā)給父進程。子進程通過execl執(zhí)行cgi腳本替換當前子進程蛋欣。如下圖:
注意代碼中航徙,一個管道在兩個通信進程會將一個管道不需要的一端關閉掉。子進程關閉了cgi_input1和cgi_output0,父進程關閉了cgi_output1和cgi_input[0](讀端)陷虎。
通常都會使用一個管道的一個管道到踏,創(chuàng)建了管道并fork進程后,管道讀寫都是雙向開放的尚猿,但通常會去關閉不使用的文件描述符窝稿,如下圖,父進程給子進程發(fā)送信息凿掂,就對應兩個進程對管道做了相應關閉處理伴榔。
附錄
附上tinyhttpd注釋版代碼:
/* 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.
*/
/*
代碼中除了用到 C 語言標準庫的一些函數(shù)纹蝴,也用到了一些與環(huán)境有關的函數(shù)(例如POSIX標準)
具體可以參讀《The Linux Programming Interface》,以下簡稱《TLPI》踪少,頁碼指示均為英文版
注釋者: github: cbsheng & github: conndots
*/
#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(int);
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(int client)
{
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;
//讀http 請求的第一行數(shù)據(jù)(request line)塘安,把請求方法存進 method 中
numchars = get_line(client, buf, sizeof(buf));
i = 0; j = 0;
while (!ISspace(buf[j]) && (i < sizeof(method) - 1))
{
method[i] = buf[j];
i++; j++;
}
method[i] = '\0';
//如果請求的方法不是 GET 或 POST 任意一個的話就直接發(fā)送 response 告訴客戶端沒實現(xiàn)該方法
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
{
unimplemented(client);
return;
}
//如果是 POST 方法就將 cgi 標志變量置一(true)
if (strcasecmp(method, "POST") == 0)
cgi = 1;
i = 0;
//跳過所有的空白字符(空格)
while (ISspace(buf[j]) && (j < sizeof(buf)))
j++;
//然后把 URL 讀出來放到 url 數(shù)組中
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))
{
url[i] = buf[j];
i++; j++;
}
url[i] = '\0';
//如果這個請求是一個 GET 方法的話
if (strcasecmp(method, "GET") == 0)
{
//用一個指針指向 url
query_string = url;
//去遍歷這個 url,跳過字符 援奢?前面的所有字符兼犯,如果遍歷完畢也沒找到字符 ?則退出循環(huán)
while ((*query_string != '?') && (*query_string != '\0'))
query_string++;
//退出循環(huán)后檢查當前的字符是 集漾?還是字符串(url)的結(jié)尾
if (*query_string == '?')
{
//如果是 切黔? 的話,證明這個請求需要調(diào)用 cgi具篇,將 cgi 標志變量置一(true)
cgi = 1;
//從字符 纬霞? 處把字符串 url 給分隔會兩份
*query_string = '\0';
//使指針指向字符 ?后面的那個字符
query_string++;
}
}
//將前面分隔兩份的前面那份字符串栽连,拼接在字符串htdocs的后面之后就輸出存儲到數(shù)組 path 中险领。相當于現(xiàn)在 path 中存儲著一個字符串
sprintf(path, "htdocs%s", url);
//如果 path 數(shù)組中的這個字符串的最后一個字符是以字符 / 結(jié)尾的話,就拼接上一個"index.html"的字符串秒紧。首頁的意思
if (path[strlen(path) - 1] == '/')
strcat(path, "index.html");
//在系統(tǒng)上去查詢該文件是否存在, 《TLPI》15.1
/*
#include <sys/stat.h>
int stat(const char *pathname, struct stat *statbuf); //return 0 on succ, or -1 on err.
*/
if (stat(path, &st) == -1) {
//如果不存在绢陌,那把這次 http 的請求后續(xù)的內(nèi)容(head 和 body)全部讀完并忽略
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));
//然后返回一個找不到文件的 response 給客戶端
not_found(client);
}
else
{
//文件存在,那去跟常量S_IFMT相與熔恢,相與之后的值可以用來判斷該文件是什么類型的
//st_mode: file type & file permission
//S_IFMT參讀《TLPI》15.1脐湾,與下面的三個常量一樣是包含在<sys/stat.h>
//stat。st_mode與S_IFMT?相與可從該字段析取文件類型
/*
| _ _ _ _ | U G T | R W X | R W X | R W X |
| | |<- user ->|<-group->|<-others->|
|<-filetype->|<- permission ->|
*/
if ((st.st_mode & S_IFMT) == S_IFDIR)
//如果這個文件是個目錄叙淌,那就需要再在 path 后面拼接一個"/index.html"的字符串
strcat(path, "/index.html");
//S_IXUSR, S_IXGRP, S_IXOTH三者可以參讀《TLPI》
if ((st.st_mode & S_IXUSR) ||
(st.st_mode & S_IXGRP) ||
(st.st_mode & S_IXOTH) )
//如果這個文件是一個可執(zhí)行文件秤掌,不論是屬于用戶/組/其他這三者類型的,就將 cgi 標志變量置一
cgi = 1;
if (!cgi)
//如果不需要 cgi 機制的話鹰霍,
serve_file(client, path);
else
//如果需要則調(diào)用
execute_cgi(client, path, method, query_string);
}
close(client);
}
/**********************************************************************/
/* 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];
//從文件文件描述符中讀取指定內(nèi)容
fgets(buf, sizeof(buf), resource);
while (!feof(resource))
{
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)
{
//包含于<stdio.h>,基于當前的 errno 值闻鉴,在標準錯誤上產(chǎn)生一條錯誤消息。參考《TLPI》P49
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 中填東西以保證能進入下面的 while
buf[0] = 'A'; buf[1] = '\0';
//如果是 http 請求是 GET 方法的話讀取并忽略請求剩下的內(nèi)容
if (strcasecmp(method, "GET") == 0)
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));
else /* POST */
{
//只有 POST 方法才繼續(xù)讀內(nèi)容
numchars = get_line(client, buf, sizeof(buf));
//這個循環(huán)的目的是讀出指示 body 長度大小的參數(shù)茂洒,并記錄 body 的長度大小孟岛。其余的 header 里面的參數(shù)一律忽略
//注意這里只讀完 header 的內(nèi)容,body 的內(nèi)容沒有讀
while ((numchars > 0) && strcmp("\n", buf))
{
buf[15] = '\0';
if (strcasecmp(buf, "Content-Length:") == 0)
content_length = atoi(&(buf[16])); //記錄 body 的長度大小
numchars = get_line(client, buf, sizeof(buf));
}
//如果 http 請求的 header 沒有指示 body 長度大小的參數(shù)督勺,則報錯返回
if (content_length == -1) {
bad_request(client);
return;
}
}
sprintf(buf, "HTTP/1.0 200 OK\r\n");
send(client, buf, strlen(buf), 0);
//下面這里創(chuàng)建兩個管道渠羞,用于兩個進程間通信,參考《TLPI》44.2
/*
#include <unistd.h>
int pipe(int fields); //return 0 on succ, -1 on err.
成功的pipe()調(diào)用會在fields中返回兩個打開的文件描述符:一個表示管道的讀取端(fields[0])智哀,另一個表示寫入端(fields[1])次询。
父子進程都通過一個pipe讀寫信息是可以的,但是很不常見,創(chuàng)建pipe瓷叫,fork()創(chuàng)建子進程之前:
[ parent process ]
- [fields[1] fields[0]]<-
| |
-> [-------pipe------>]-
| |
- [fields[1] fields[0]]<-
[ sub process ]
通常fork()后屯吊,其中一個進程需要立即關閉管道寫入端描述符送巡,另一個關閉讀取描述符。關閉未使用描述符之后:
[ parent process ]
- [fields[1] ]
|
-> [-------pipe------>]-
|
[ fields[0]]<-
[ sub process ]
*/
if (pipe(cgi_output) < 0) {
cannot_execute(client);
return;
}
if (pipe(cgi_input) < 0) {
cannot_execute(client);
return;
}
/*
cgi_output是子進程(執(zhí)行cgi的進程)的輸出管道雌芽,子進程寫授艰,父進程讀;
cgi_input是子進程(執(zhí)行cgi的進程)的輸入管道世落,父進程寫淮腾,子進程讀。
*/
//創(chuàng)建一個子進程 參考《TLPI》 24.2
/*
#include <unistd.h>
pid_t fork(void); //in parent, return processID of child on success or -1 on error; in successfully created child: always return 0
*/
if ( (pid = fork()) < 0 ) {
cannot_execute(client);
return;
}
//子進程用來執(zhí)行 cgi 腳本
if (pid == 0) /* child: CGI script */
{
char meth_env[255];
char query_env[255];
char length_env[255];
//dup2()包含<unistd.h>中屉佳,參讀《TLPI》5.5
//將子進程的輸出由標準輸出重定向到 cgi_ouput 的管道寫端上
/*
#include <unistd.h>
int dup2(int oldfd, int newfd); //return (new) file descritor on succ, -1 on err
為oldfd指定文件描述符創(chuàng)建副本谷朝,其編號由newfd指定。
*/
dup2(cgi_output[1], 1);
//將子進程的輸出由標準輸入重定向到 cgi_ouput 的管道讀端上
dup2(cgi_input[0], 0);
//關閉 cgi_ouput 管道的讀端與cgi_input 管道的寫端
close(cgi_output[0]);
close(cgi_input[1]);
//構(gòu)造一個環(huán)境變量
sprintf(meth_env, "REQUEST_METHOD=%s", method);
//putenv()包含于<stdlib.h>中武花,參讀《TLPI》6.7
//將這個環(huán)境變量加進子進程的運行環(huán)境中
/*
#include <stdlib.h>
int putenv(char *string); //return 0 on succ, nonzero on err.
*/
putenv(meth_env);
//根據(jù)http 請求的不同方法圆凰,構(gòu)造并存儲不同的環(huán)境變量
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()包含于<unistd.h>中,參讀《TLPI》P567
//最后將子進程替換成另一個進程并執(zhí)行 cgi 腳本
/*
#include <unistd.h>
int execl(const char* pathname, const char *arg, ...); //not return on succ;return -1 on error.
*/
execl(path, path, NULL);
exit(0);
} else { /* parent */
//父進程則關閉了 cgi_output管道的寫端和 cgi_input 管道的讀端
close(cgi_output[1]);
close(cgi_input[0]);
//如果是 POST 方法的話就繼續(xù)讀 body 的內(nèi)容体箕,并寫到 cgi_input 管道里讓子進程去讀
if (strcasecmp(method, "POST") == 0)
for (i = 0; i < content_length; i++) {
recv(client, &c, 1, 0);
write(cgi_input[1], &c, 1);
}
//然后從 cgi_output 管道中讀子進程的輸出专钉,并發(fā)送到客戶端去
while (read(cgi_output[0], &c, 1) > 0)
send(client, &c, 1, 0);
//關閉管道
close(cgi_output[0]);
close(cgi_input[1]);
//等待子進程的退出 《TLPI》26.1.2
/*
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options); //return process ID of child, 0, or -1 on err.
*/
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) */
/**********************************************************************/
int get_line(int sock, char *buf, int size)
{
int i = 0;
char c = '\0';
int n;
while ((i < size - 1) && (c != '\n'))
{
//recv()包含于<sys/socket.h>,參讀《TLPI》61.3,
//讀一個字節(jié)的數(shù)據(jù)存放在 c 中
/*
#include<sys/socket.h>
ssize_t recv(int sockfd, void *buffer, size_t length, int flags); //return num of bytes received, 0 on EOF, -1 on err.
*/
n = recv(sock, &c, 1, 0);
/* DEBUG printf("%02X\n", c); */
if (n > 0)
{
if (c == '\r')
{
//MSG_PEEK, 從套接字緩沖區(qū)獲取一份請求字節(jié)副本,但不會將請求的字節(jié)從緩沖區(qū)中實際移除累铅。
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 */
/**********************************************************************/
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);
}
/**********************************************************************/
/* 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);
}
/**********************************************************************/
/* 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 里面有東西跃须,能進入下面的 while 循環(huán)
buf[0] = 'A'; buf[1] = '\0';
//循環(huán)作用是讀取并忽略掉這個 http 請求后面的所有內(nèi)容
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
{
//打開成功后,將這個文件的基本信息封裝成 response 的頭部(header)并返回
headers(client, filename);
//接著把這個文件的內(nèi)容讀出來作為 response 的 body 發(fā)送到客戶端
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;
//sockaddr_in 是 IPV4的套接字地址結(jié)構(gòu)娃兽。定義在<netinet/in.h>,參讀《TLPI》P59.4
struct sockaddr_in name;
//socket()用于創(chuàng)建一個用于 socket 的描述符菇民,函數(shù)包含于<sys/socket.h>。參讀《TLPI》56.2
//這里的PF_INET其實是與 AF_INET同義投储,具體可以參讀《TLPI》P946
/*
int socket(int domain, int type, int protocol); //return file descriptor on success,-1 on error
type = SOCK_STREAM -> 流socket 一般使用TCP協(xié)議傳輸
type = SOCK_DGRAM -> 數(shù)據(jù)報socket 使用UDP協(xié)議傳輸
*/
httpd = socket(PF_INET, SOCK_STREAM, 0);
if (httpd == -1)
error_die("socket");
memset(&name, 0, sizeof(name));
name.sin_family = AF_INET;
//htons()第练,ntohs() 和 htonl()包含于<arpa/inet.h>, 參讀《TLPI》P59.2
//將*port 轉(zhuǎn)換成以網(wǎng)絡字節(jié)序表示的16位整數(shù)
name.sin_port = htons(*port);
//INADDR_ANY是一個 IPV4通配地址的常量,包含于<netinet/in.h>
//大多實現(xiàn)都將其定義成了0.0.0.0 參讀《TLPI》P1187
name.sin_addr.s_addr = htonl(INADDR_ANY);
//bind()用于綁定地址與 socket玛荞。參讀《TLPI》56.3
//如果傳進去的sockaddr結(jié)構(gòu)中的 sin_port 指定為0娇掏,這時系統(tǒng)會選擇一個臨時的端口號
/*
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); //return 0 on succ, -1 on err.
sockfd: sock函數(shù)返回的文件描述符
?
struct sockaddr {
sa_family_t sa_family; //address family(AF_* constant)
char sa_data[14]; //socket address(size varies according to socket domain)
}
struct sockaddr_in {
so_family_t sin_family; //address family(AF_INET)
in_port_t sin_port; //port 16 bytes
struct in_addr sin_addr; //IVv4 address 32 bytes
unsigned char __pad[X]; //pad to size of 'sockaddr' structure(16 bytes)
}
sin_port + sin_addr -> sa_data[14]
每種socket domain都使用了不同的地址格式。Unix domain socket使用路徑名勋眯;Internet domain socket使用ip地址和端口號驹碍。bind適用于所有的socket domain,必須能夠接受任意類型地址結(jié)構(gòu)凡恍。sockaddr是通用的地址結(jié)構(gòu)。需要將特定domain socket轉(zhuǎn)換為sockaddr怔球。
*/
if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
error_die("bind");
//如果調(diào)用 bind 后端口號仍然是0嚼酝,則手動調(diào)用getsockname()獲取端口號
if (*port == 0) /* if dynamically allocating a port */
{
int namelen = sizeof(name);
//getsockname()包含于<sys/socker.h>中,參讀《TLPI》61.5
//調(diào)用getsockname()獲取系統(tǒng)給 httpd 這個 socket 隨機分配的端口號
/*
int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen); //return 0 on succ, -1 on err.
*/
if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
error_die("getsockname");
*port = ntohs(name.sin_port);
}
//最初的 BSD socket 實現(xiàn)中竟坛,backlog 的上限是5.參讀《TLPI》56.5.1
/*
#include<sys/socket.h>
int listen(int sockfd, int backlog); //return 0 on success, -1 on err.
將文件描述符sockfd引用的流socket標記為被動闽巩,這個socket后面會被用來接受來自其它(主動的)socket連接钧舌。
如何理解backlog參數(shù)?
未決連接請求:
被動socket連接:
socket() -> bind() -> listen() -> accept() -><-
主動socket連接:
socket() -> connect() //可能阻塞涎跨,取決于后臺登錄的連接請求數(shù)量
聯(lián)系:
C: connect() --> S: accept()
當服務器忙于處理其他客戶端時洼冻,會先client調(diào)用connect(),然后server再accept。內(nèi)核需要記錄這些未決連接請求的相關信息隅很,這樣后續(xù)accept()才能處理這些請求撞牢。backlog為允許這種未決連接的數(shù)量。這個限制以內(nèi)的請求會立即成功叔营。之外的連接請求會阻塞到一個未決的連接被接受(通過accept())屋彪。linux中被定義成了128,可以通過/proc/sys/net/core/somaxconn配置绒尊。
*/
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);
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 = 0;
int client_sock = -1;
//sockaddr_in 是 IPV4的套接字地址結(jié)構(gòu)畜挥。定義在<netinet/in.h>,《TLPI》59.4
/*
struct in_addr {
in_addr_t s_addr; //unsigned 32-bit int
}
struct sockaddr_in {
so_family_t sin_family; //address family(AF_INET)
in_port_t sin_port; //port 16 bytes
struct in_addr sin_addr; //IVv4 address 32 bytes
unsigned char __pad[X]; //pad to size of 'sockaddr' structure(16 bytes)
}
*/
struct sockaddr_in client_name;
int client_name_len = sizeof(client_name);
//pthread_t newthread;
server_sock = startup(&port);
printf("httpd running on port %d\n", port);
while (1)
{
//阻塞等待客戶端的連接,如果沒有未決連接的話婴谱,參讀《TLPI》56.5.2
/*
#include<sys/socket.h>
int accept(int sockfd, struct sockaddr *addr, socklen_t addrlen); //return file descriptor on succ, -1 on err.
它會創(chuàng)建一個新的socket蟹但,正是這個socket與執(zhí)行connect()的對等socket進行連接。
socket(sockfd)會保持打開狀態(tài)谭羔,并可用于接受后續(xù)的連接华糖。
accept4(): 新添參數(shù)flags, SOCK_CLOSEEXEC-內(nèi)核在調(diào)用返回的新文件描述符上啟用close-on-exec標記 SOCK_NONBLOCK-內(nèi)核在底層打開著的文件描述上啟用O_NONBLOCK標記,后續(xù)I/O操作變成非阻塞,無需調(diào)用fcntl()獲得同樣效果口糕。
*/
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, client_sock) != 0)
perror("pthread_create");*/
}
/*
如果多個文件描述符引用了一個socket缅阳,那么當所有文件描述符被關閉后連接就會被終止。
*/
close(server_sock);
return(0);
}
simple client:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int sockfd;
int len;
struct sockaddr_in address;
int result;
char ch = 'A';
//申請一個流 socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
//填充地址結(jié)構(gòu)景描,指定服務器的 IP 和 端口
address.sin_family = AF_INET;
//inet_addr 可以參考 man inet_addr
//可以用現(xiàn)代的inet_pton()替代inet_addr(), example 中有參考例子
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(9734);
len = sizeof(address);
//下面的語句可以輸出連接的 IP 地址
//但是inet_ntoa()是過時的方法十办,應該改用 inet_ntop(可參考 example)。但很多代碼仍然遺留著inet_ntoa.
//printf("%s\n", inet_ntoa( address.sin_addr));
result = connect(sockfd, (struct sockaddr *)&address, len);
if (result == -1)
{
perror("oops: client1");
exit(1);
}
//往服務端寫一個字節(jié)
write(sockfd, &ch, 1);
//從服務端讀一個字符
read(sockfd, &ch, 1);
printf("char from server = %c\n", ch);
close(sockfd);
exit(0);
}