Tinyhttpd源碼解析

簡介

Tinyhttpd是一輕量級的web服務器,它由美國學生J. David Blackstone於1999年在學習網絡課程時編寫。源碼不到500行,非常適合學習Web編程和Linux/Unix編程接口。

其源碼見Tinyhttpd

分析

Tinyhttpd執行流程如下圖:
主線程完成socket的創建、綁定、端口監聽、創建子線程處理每一個請求。代碼如下:
int main(void)
{
	int server_sock = -1;
	u_short port = 8000;
	int client_sock = -1;
	struct sockaddr_in client_name;
	int client_name_len = sizeof(client_name);
	pthread_t newthread;

	/* 在指定端口上建立http服務 */
	server_sock = startup(&port);
	printf("httpd-socket:%d\n", server_sock);
	printf("httpd running on port %d\n", port);

	int count = 0;
	while (1) {
		/* accpet成功後,可獲得客戶端socket和sockaddr */
		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");
		//printf("\b%d", ++count); fflush(stdout); //統計連接請求數
	}

	close(server_sock);
	return(0);
}
其中startup()函數完成socket的bind/listen。代碼實現如下:
/**********************************************************************/
/* 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;

	/* 建立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);

	/* 綁定socket */
	if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
		error_die("bind");
	if (*port == 0) {  /* if dynamically allocating a port */
		int namelen = sizeof(name);
		if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
			error_die("getsockname");
		*port = ntohs(name.sin_port);
	}
	/* 監聽socket */
	if (listen(httpd, 5) < 0)
		error_die("listen");

	return(httpd);
}
子線程accep_request()處理連接請求,請求處理完成後關閉連接。當然這種多線程方式,不可能做到高併發。每來一個請求都會創建一個子線程來處理,處理完成後結束子線程,這必然會導致服務器有不少性能開銷,一般用線程池技術。當然Web服務也可以使用多進程如nginx。多線程共享父進程的數據空間,可能導致問題蔓延。多進程有很好的隔離性。accep_request()代碼如下:
/**********************************************************************/
/* 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]; //URL
	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));
	printf("Request-line:%s\n", buf); //debug
	i = 0; j = 0;
	/* 讀取請求行中的請求方法至method */
	while (!ISspace(buf[j]) && (i < sizeof(method) - 1)) {
		method[i] = buf[j];
		i++; j++;
	}
	method[i] = '\0';
	printf("Method:%s ", method);

	/* 僅支持GET和POST請求方法 */
	if (strcasecmp(method, "GET") && strcasecmp(method, "POST")) {
		unimplemented(client); //通知客戶客,該請求方法未實現
		return;
	}

	/* POST時開啓CGI */
	if (strcasecmp(method, "POST") == 0)
		cgi = 1;

	/* 讀取請求行中URL */
	i = 0;
	while (ISspace(buf[j]) && (j < sizeof(buf)))
		j++;
	while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf))) {
		url[i] = buf[j];
		i++; j++;
	}
	url[i] = '\0';
	printf("URL:%s \n", url);

	/* 處理GET方法 */
	if (strcasecmp(method, "GET") == 0) { 
		query_string = url;
		while ((*query_string != '?') && (*query_string != '\0'))
			query_string++;
		/* GET方法的特點,? 後面爲參數 */
		if (*query_string == '?') {
			/* 開啓CGI */
			cgi = 1;
			*query_string = '\0';
			query_string++;
		}
	}

	/* 格式化URL到path數組, html在htdocs中,從客戶端發過來的URL至少是/ */
	sprintf(path, "htdocs%s", url);
	if (path[strlen(path) - 1] == '/')
		/* 默認情況爲index.html */
		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);
	}
	/* 關閉連接,假定不是keepalive */
	close(client);
}
瀏覽器是按照http協議請求的格式給服務器發送請求的,這個函數完成了http協議請求解析。目前只支持GET和POST請求。其中get_line()函數並且不管原來是以\n還是\r\n結束,均轉化爲以\n再加\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;

	/*把終止條件統一爲\n換行符,標準化buf數組*/
	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); */
				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);
}
get_line完後,就是開始解析第一行,判斷是GET方法還是POST方法,目前只支持這兩種。如果是POST,還是把cgi置1,表明要運行CGI程序;如果是GET方法且附帶以?開頭的參數時,也認爲是執行CGI程序。
獲取URL得到文件在服務上的訪問路徑,獲取訪問文件的屬性,並判斷文件是否具有可執行權限。如果有可執行權限,則認爲是要執行CGI程序。否則訪問靜態文件,訪問方法爲serve_file(),其實現如下:
 /**********************************************************************/
/* 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];

	/* 讀取並丟棄headers */
	buf[0] = 'A'; buf[1] = '\0';
	while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */
		numchars = get_line(client, buf, sizeof(buf));

	/* 打開serve的文件 */
	resource = fopen(filename, "r");
	if (resource == NULL)
		not_found(client);
	else {
		/* 寫http頭 */
		headers(client, filename);
		/* 複製文件 */
		cat(client, resource);
	}
	fclose(resource);
}
其中在服務上讀取要訪問的文件,並構造http響應格式,以響應客戶端。其中,headers()完成響應頭的構造,並把響應頭信息發送給客戶端。cat()函數則負責把訪問的文件發送給客戶端。
headers()代碼如下:
/**********************************************************************/
/* 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()代碼如下:
/**********************************************************************/
/* 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);
	}
}

執行CGI程序的代碼如下:
/**********************************************************************/
/* 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) /* GET */
		/* 讀取並丟棄請求headers */
		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;
		}
	}

	/* 正確,HTTP狀態碼200 */
	sprintf(buf, "HTTP/1.0 200 OK\r\n");
	send(client, buf, strlen(buf), 0);

	/* 創建兩個管道,管道半雙工, cig_output[0]讀, cig_output[1]寫 */
	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];

		/* 把STDOUT重定向到cgi_output的寫入端 */ 
		dup2(cgi_output[1], 1);
		/* 把STDIN重定向到cgi_input的讀取端 */
		dup2(cgi_input[0], 0);

		/* 關閉cgi_input的寫入端和cgi_output的讀取端, 把半雙工變單工通信 */
		close(cgi_output[0]);
		close(cgi_input[1]);

		/* 設置request_method的環境變量 */
		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 */
			/* 設置content_length的環境變量 */ 
			sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
			putenv(length_env);
		}
		/* 用execl運行cgi程序 */
		execl(path, path, NULL);
		exit(0);
	}
	else {    /* parent */
		/* 關閉cgi_input的讀取端和cgi_output的寫入端 */
		close(cgi_output[1]);
		close(cgi_input[0]);
		/* 接收POST方法過來的數據 */
		if (strcasecmp(method, "POST") == 0)
			for (i = 0; i < content_length; i++) {
				recv(client, &c, 1, 0);
				/*把POST數據寫入cgi_input,現在重定向到STDIN */ 
				write(cgi_input[1], &c, 1);
			}
		/* 讀取cgi_output的管道輸出到客戶端,該管道輸入是STDOUT */
		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);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章