# HTTP Server **Repository Path**: linkvi/HTTP-Server ## Basic Information - **Project Name**: HTTP Server - **Description**: The multi-process server of this version use signal function avoid zombie process. - **Primary Language**: C - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2017-11-13 - **Last Updated**: 2023-04-20 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # HTTP Server The multi-process server of this version use signal function avoid zombie process. 1、is_http_protocol函数 函数原型:int is_http_protocol(char *msg_from_client) 函数作用:判断收到的请求报文是否是http协议的请求。 msg_from_client:从已连接套接口读到的数据。 函数逻辑: (1)读取服务器端收到的数据第一行。 (2)定义一个索引,用while语句把索引定位到第一行最后。 (3)因为每个请求报文第一行最后都是”http/1.x\r\n”,用strncmp比较http/和原字符串中倒数第十开始五个字符。 (4)如果返回0,则是http协议;函数返回1。 2、get_uri函数 原型:char *get_uri(char *req_header, char *uri_buf) 函数作用:从请求报文中获取URI(Uniform Resource Identifier) 函数逻辑: (1)定义索引,用while循环把索引定位到请求行第一个”/”;用一个变量记住此时位置。 (2)从上一个索引位置开始,用while循环,把索引定位到接下来的第一个空格“ ”处。 (3)这里判断URI是否过长和URI是否是“/”。 (4)URI是“/”,把"index.html"用strcpy拷贝到uri_buf中。 (5)否则,把对应req_header中的URI用strncpy拷贝到uri_buf中。 3、get_uri_status函数 原型:int get_uri_status(char *uri) 函数作用:获取URI的状态 Uri:uri_buf中的URI串。 函数逻辑: (1)用access函数判断URI中文件是否具有存取权限。 (2)用F_OK来判断文件是否存在,不存在返回-1。 (3)用R_OK来判断文件是否可以读取,不可读返回-1。 4、get_mime_type函数 函数原型:char *get_mime_type(char *uri) 作用:获取请求报文中MIME的类型。 Uri:uri_buf中的字符串。 函数逻辑: (1)定义索引,用while语句把索引定位到“.”的位置。 (2)计算URI总长度,用总长度减去索引,得到“.”之后后缀的长度;如果没有URI中没有“.”,说明是“/”。 (3)以上面的到的值作为switch语句的case,初步判断是什么MIME类型。 (4)在每个case中用strcmp比较从“.”开始的字符串的典型的MIME。 (5)得出具体MIME类型。(注意大小写和简写) 5、get_file_disk函数 函数原型:int get_file_disk(char *uri, unsigned char *file_buf) 函数作用是读取URI中的文件,把读到的文件拷贝到entity_buf中,如果成功返回读到字节数,失败返回-1 Uri:客户端连接中URI。 File_buf:读取文件并保存到这个buf中。 函数逻辑: (1)用open函数打开对应的文件,返回文件描述符。 (2)定义struct stat st,然后调用fstat函数用文件描述符获取文件的状态(主要是st_size)。 (3)判断文件大小是否会大于预定义最大文件大小,文件太大返回错误。 (4)用read函数通过open返回文件描述符读取文件到file_buf中。 6、set_error_information函数 函数原型:int set_error_information(unsigned char *send_buf, int errorno) 函数主要是应对处理错误,把相应的出错信息发送回客户端。 Send_buf:响应报文内容buf。 Errorno:相应的错误号。 函数逻辑: (1)通过传入errorno用Switch语句判断是哪种错误。 (2)此处只设置了一个FILE_NOT_FOUND错误,其他错误可以类似设置,后期可以补充完整。 (3)把响应报文状态行("HTTP/1.1 404 File Not Found\r\n")用memcpy到send_buf中。 (4)把服务器名和版本号等响应报文首部用memcpy到send_buf中。(用一个对send_buf的索引来控制copy) (5)把简单的html拷贝到send_buf中。( "\r\n\r\n
404 File not found