//webserver.c
//============================================================= // 语法格式: void deal_with(int connfd, char *buf) // 实现功能: 处理客户端的请求 // 入口参数: conndf,buf // 出口参数: 无 //=============================================================
#include "main.h" #include <fcntl.h> #include <sys/stat.h>
void deal_with(int connfd, char *buf) { char *resp_head = "HTTP/1.1 200 OK\r\n" \ "Content-Type: text/html\r\n" \ "Content-Length:%ld\r\n" \ "\r\n"; char *not_found = "HTTP/1.1 404 Not Found\r\n" \ "Content-Type: text/html\r\n" \ "Content-Length: 40\r\n" \ "\r\n" \ "File not found
"; char *bad_request = "HTTP/1.1 400 Bad Request\r\n" \ "Content-Type: text/html\r\n" \ "Content-Length: 39\r\n" \ "\r\n" \ "Bad Request (Invalid Hostname)"; /* char *moved_permanently = "HTTP/1.1 301 Moved Permanently\r\n"\ "Content-Length: 147\r\n" \ "Content-Type: text/html\r\n" \ "Location: %s\r\n" \ "\r\n" \ "Document MovedObject MovedThis document may be found here"; */ char tmp_buf[SEND_SIZE] = {""}; char *tmp_bak[10]; char *first_line[5]; int fd; FILE *fp; struct stat file_buf; int file_len = 0;
fp = fdopen(connfd, "w+"); //
cut_list(tmp_bak, buf, "\r\n"); cut_list(first_line, tmp_bak[0], " ");
if((first_line[0] != NULL) && (strcmp(first_line[0], "GET") == 0)) { if(first_line[1] != NULL) { if(strcmp(first_line[1], "/") == 0) { strcat(first_line[1], "bai.htm"); } first_line[1] = ++first_line[1]; if((fd = open(first_line[1], O_RDONLY)) == -1) { write(connfd, not_found, strlen(not_found)); perror("open index.html err!"); return ; } stat(first_line[1], &file_buf); file_len = file_buf.st_size; fprintf(fp, resp_head, file_len); fflush(fp); int len; while((len = read(fd, tmp_buf, SEND_SIZE)) > 0) { write(connfd, tmp_buf, len); memset(tmp_buf, 0, SEND_SIZE); } close(fd); } else { write(connfd, bad_request, strlen(bad_request)); } } return ; } /*************************************************************
*自己封装的字符串切割函数
*功 能:切割字符串
*************************************************************/
int cut_list(char *bak[], char *buf, char *str) { int i = 0; int size = 0; bak[i] = strtok(buf, str); while((bak[++i] = strtok(NULL, str))); size = i; return size; }
|