C语言开发Linux下web服务器(支持GET/POST,SSL,目录显示等)

来源:互联网 发布:wind数据库 华东师大 编辑:程序博客网 时间:2024/06/05 09:23

http://blog.csdn.net/yueguanghaidao/article/details/8450938

这个主要是在CSAPP基础上做的,添加了POST,SSL,目录显示等功能。

一、实现功能:
1.支持GET/POST方法
2.支持SSL安全连接即HTTPS
3.支持CGI
4.基于IP地址和掩码的认证
5.目录显示
6.日志功能

7. 错误提示页面


github地址:https://github.com/Skycrab/Linux-C-Web-Server


源代码下载地址:点击打开链接

二、设计原理

首先介绍一些HTTP协议基本知识。
#1.GET/POST
本实现支持GET/POST方法,都是HTTP协议需要支持的标准方法。
GET方法主要是通过URL发送请求和传送数据,而POST方法在请求头空一格之后传送数据,所以POST方法比GET方法安全性高,因为GET方法可以直接看到传送的数据。另外一个区别就是GET方法传输的数据较小,而POST方法很大。所以一般表单,登陆页面等都是通过POST方法。

#2.MIME类型
   当服务器获取客户端的请求的文件名,将分析文件的MIME类型,然后告诉浏览器改文件的MIME类型,浏览器通过MIME类型解析传送过来的数据。具体来说,浏览器请求一个主页面,该页面是一个HTML文件,那么服务器将”text/html”类型发给浏览器,浏览器通过HTML解析器识别发送过来的内容并显示。

下面将描述一个具体情景。
   客户端使用浏览器通过URL发送请求,服务器获取请求。
如浏览器URL为:127.0.0.1/postAuth.html,
那么服务器获取到的请求为:GET  /postAuth.html  HTTP/1.1
意思是需要根目录下postAuth.html文件的内容,通过GET方法,使用HTTP/1.1协议(1.1是HTTP的版本号)。这是服务器将分析文件名,得知postAuth.html是一个HTML文件,所以将”text/html”发送给浏览器,然后读取postAuth.html内容发给浏览器。

实现简单的MIME类型识别代码如下:
主要就是通过文件后缀获取文件类型。

[cpp] view plaincopy
  1. static void get_filetype(const char *filename, char *filetype)   
  2. {  
  3.     if (strstr(filename, ".html"))  
  4.         strcpy(filetype, "text/html");  
  5.     else if (strstr(filename, ".gif"))  
  6.         strcpy(filetype, "image/gif");  
  7.     else if (strstr(filename, ".jpg"))  
  8.         strcpy(filetype, "image/jpeg");  
  9.     else if (strstr(filename, ".png"))  
  10.         strcpy(filetype, "image/png");  
  11.     else  
  12.     strcpy(filetype, "text/plain");  
  13. }    

如果支持HTTPS的话,那么我们就#define HTTPS,这主要通过gcc 的D选项实现的,具体细节可参考man手册。

静态内容显示实现如下:

[cpp] view plaincopy
  1. static void serve_static(int fd, char *filename, int filesize)   
  2. {  
  3.     int srcfd;  
  4.     char *srcp, filetype[MAXLINE], buf[MAXBUF];  
  5.    
  6.     /* Send response headers to client */  
  7.     get_filetype(filename, filetype);  
  8.     sprintf(buf, "HTTP/1.0 200 OK\r\n");  
  9.     sprintf(buf, "%sServer: Tiny Web Server\r\n", buf);  
  10.     sprintf(buf, "%sContent-length: %d\r\n", buf, filesize);  
  11.     sprintf(buf, "%sContent-type: %s\r\n\r\n", buf, filetype);  
  12.   
  13.     /* Send response body to client */  
  14.     srcfd = Open(filename, O_RDONLY, 0);  
  15.     srcp = Mmap(0, filesize, PROT_READ, MAP_PRIVATE, srcfd, 0);  
  16.     Close(srcfd);  
  17.   
  18.     #ifdef HTTPS   
  19.     if(ishttps)  
  20.     {  
  21.         SSL_write(ssl, buf, strlen(buf));  
  22.     SSL_write(ssl, srcp, filesize);  
  23.     }  
  24.     else  
  25.     #endif  
  26.     {  
  27.     Rio_writen(fd, buf, strlen(buf));  
  28.     Rio_writen(fd, srcp, filesize);  
  29.     }  
  30.     Munmap(srcp, filesize);  
  31. }  

#3.CGI规范
   如果只能显示页面那么无疑缺少动态交互能力,于是CGI产生了。CGI是公共网关接口(Common Gateway Interface),是在CGI程序和Web服务器之间传递信息的规则。CGI允许Web服务器执行外部程序,并将它们的输出发送给浏览器。这样就提供了动态交互能力。 

那么服务器是如何分开处理静态页面和动态CGI程序的呢?这主要是通过解析URL的方式。我们可以定义CGI程序的目录,如cgi-bin,那么如果URL包含”cgi-bin”字符串则这是动态程序,且将URL的参数给cgiargs。如果是静态页面,parse_uri返回1,反正返回0。所以我们可以通过返回值区别不同的服务类型。
具体解析URL方式如下:

[cpp] view plaincopy
  1. static int parse_uri(char *uri, char *filename, char *cgiargs)   
  2. {  
  3.     char *ptr;  
  4.     char tmpcwd[MAXLINE];  
  5.     strcpy(tmpcwd,cwd);  
  6.     strcat(tmpcwd,"/");  
  7.   
  8.     if (!strstr(uri, "cgi-bin"))   
  9.     {  /* Static content */  
  10.     strcpy(cgiargs, "");  
  11.     strcpy(filename, strcat(tmpcwd,Getconfig("root")));  
  12.     strcat(filename, uri);  
  13.     if (uri[strlen(uri)-1] == '/')  
  14.         strcat(filename, "home.html");  
  15.     return 1;  
  16.     }  
  17.     else   
  18.     {  /* Dynamic content */  
  19.     ptr = index(uri, '?');  
  20.     if (ptr)   
  21.     {  
  22.         strcpy(cgiargs, ptr+1);  
  23.         *ptr = '\0';  
  24.     }  
  25.     else   
  26.         strcpy(cgiargs, "");  
  27.     strcpy(filename, cwd);  
  28.     strcat(filename, uri);  
  29.     return 0;  
  30.     }  
  31. }  

GET方式的CGI规范实现原理:
   服务器通过URL获取传给CGI程序的参数,设置环境变量QUERY_STRING,并将标准输出重定向到文件描述符,然后通过EXEC函数簇执行外部CGI程序。外部CGI程序获取QUERY_STRING并处理,处理完后输出结果。由于此时标准输出已重定向到文件描述符,即发送给了浏览器。
实现细节如下:由于涉及到HTTPS,所以稍微有点复杂。

[cpp] view plaincopy
  1. void get_dynamic(int fd, char *filename, char *cgiargs)   
  2. {  
  3.     char buf[MAXLINE], *emptylist[] = { NULL },httpsbuf[MAXLINE];  
  4.     int p[2];  
  5.   
  6.     /* Return first part of HTTP response */  
  7.     sprintf(buf, "HTTP/1.0 200 OK\r\n");  
  8.     sprintf(buf, "%sServer: Web Server\r\n",buf);  
  9.     #ifdef HTTPS   
  10.     if(ishttps)  
  11.         SSL_write(ssl,buf,strlen(buf));  
  12.     else  
  13.     #endif  
  14.         Rio_writen(fd, buf, strlen(buf));  
  15.       
  16.     #ifdef HTTPS   
  17.     if(ishttps)  
  18.     {  
  19.         Pipe(p);  
  20.         if (Fork() == 0)  
  21.     {  /* child  */   
  22.         Close(p[0]);  
  23.         setenv("QUERY_STRING", cgiargs, 1);   
  24.         Dup2(p[1], STDOUT_FILENO);         /* Redirect stdout to p[1] */  
  25.         Execve(filename, emptylist, environ); /* Run CGI program */   
  26.     }  
  27.     Close(p[1]);  
  28.     Read(p[0],httpsbuf,MAXLINE);   /* parent read from p[0] */  
  29.     SSL_write(ssl,httpsbuf,strlen(httpsbuf));  
  30.     }  
  31.     else  
  32.     #endif  
  33.     {  
  34.     if (Fork() == 0)   
  35.     { /* child */  
  36.         /* Real server would set all CGI vars here */  
  37.         setenv("QUERY_STRING", cgiargs, 1);   
  38.         Dup2(fd, STDOUT_FILENO);         /* Redirect stdout to client */  
  39.         Execve(filename, emptylist, environ); /* Run CGI program */  
  40.     }  
  41. }  
  42. }  

POST方式的CGI规范实现原理:
   由于POST方式不是通过URL传递参数,所以实现方式与GET方式不一样。
POST方式获取浏览器发送过来的参数长度设置为环境变量CONTENT-LENGTH。并将参数重定向到CGI的标准输入,这主要通过pipe管道实现的。CGI程序从标准输入读取CONTENT-LENGTH个字符就获取了浏览器传送的参数,并将处理结果输出到标准输出,同理标准输出已重定向到文件描述符,所以浏览器就能收到处理的响应。
具体实现细节如下:

[cpp] view plaincopy
  1. static void post_dynamic(int fd, char *filename, int contentLength,rio_t *rp)  
  2. {  
  3.     char buf[MAXLINE],length[32], *emptylist[] = { NULL },data[MAXLINE];  
  4.     int p[2];  
  5.   
  6.   
  7.     #ifdef HTTPS   
  8.     int httpsp[2];  
  9.     #endif  
  10.   
  11.   
  12.     sprintf(length,"%d",contentLength);  
  13.     memset(data,0,MAXLINE);  
  14.   
  15.   
  16.     Pipe(p);  
  17.   
  18.   
  19.     /*       The post data is sended by client,we need to redirct the data to cgi stdin. 
  20.     *    so, child read contentLength bytes data from fp,and write to p[1]; 
  21.     *    parent should redirct p[0] to stdin. As a result, the cgi script can 
  22.     *    read the post data from the stdin.  
  23.     */  
  24.   
  25.   
  26.     /* https already read all data ,include post data  by SSL_read() */  
  27.      
  28.         if (Fork() == 0)  
  29.     {                     /* child  */   
  30.         Close(p[0]);  
  31.         #ifdef HTTPS   
  32.         if(ishttps)  
  33.         {  
  34.             Write(p[1],httpspostdata,contentLength);      
  35.         }  
  36.         else  
  37.         #endif  
  38.         {  
  39.             Rio_readnb(rp,data,contentLength);  
  40.             Rio_writen(p[1],data,contentLength);  
  41.         }  
  42.         exit(0) ;  
  43.     }  
  44.       
  45.     /* Send response headers to client */  
  46.     sprintf(buf, "HTTP/1.0 200 OK\r\n");  
  47.     sprintf(buf, "%sServer: Tiny Web Server\r\n",buf);  
  48.   
  49.   
  50.     #ifdef HTTPS   
  51.     if(ishttps)  
  52.         SSL_write(ssl,buf,strlen(buf));  
  53.     else  
  54.     #endif  
  55.         Rio_writen(fd, buf, strlen(buf));  
  56.   
  57.   
  58.     Dup2(p[0],STDIN_FILENO);  /* Redirct p[0] to stdin */  
  59.     Close(p[0]);  
  60.     Close(p[1]);  
  61.     setenv("CONTENT-LENGTH",length , 1);   
  62.   
  63.   
  64.     #ifdef HTTPS   
  65.     if(ishttps)  /* if ishttps,we couldnot redirct stdout to client,we must use SSL_write */  
  66.     {  
  67.         Pipe(httpsp);  
  68.        if(Fork()==0)  
  69.       {  
  70.         Dup2(httpsp[1],STDOUT_FILENO);        /* Redirct stdout to https[1] */   
  71.         Execve(filename, emptylist, environ);   
  72.     }  
  73.     Read(httpsp[0],data,MAXLINE);  
  74.     SSL_write(ssl,data,strlen(data));  
  75.     }  
  76.     else  
  77.     #endif  
  78.     {  
  79.         Dup2(fd,STDOUT_FILENO);        /* Redirct stdout to client */   
  80.         Execve(filename, emptylist, environ);   
  81.     }  
  82. }  

目录显示功能原理:
   主要是通过URL获取所需目录,然后获取该目录下所有文件,并发送相应信息,包括文件格式对应图片,文件名,文件大小,最后修改时间等。由于我们发送的文件名是通过超链接的形式,所以我们可以点击文件名继续浏览信息。
具体实现细节如下:

[cpp] view plaincopy
  1. static void serve_dir(int fd,char *filename)  
  2. {  
  3.     DIR *dp;  
  4.     struct dirent *dirp;  
  5.         struct stat sbuf;  
  6.     struct passwd *filepasswd;  
  7.     int num=1;  
  8.     char files[MAXLINE],buf[MAXLINE],name[MAXLINE],img[MAXLINE],modifyTime[MAXLINE],dir[MAXLINE];  
  9.     char *p;  
  10.   
  11.     /* 
  12.     * Start get the dir    
  13.     * for example: /home/yihaibo/kerner/web/doc/dir -> dir[]="dir/"; 
  14.     */  
  15.     p=strrchr(filename,'/');  
  16.     ++p;  
  17.     strcpy(dir,p);  
  18.     strcat(dir,"/");  
  19.     /* End get the dir */  
  20.   
  21.     if((dp=opendir(filename))==NULL)  
  22.         syslog(LOG_ERR,"cannot open dir:%s",filename);  
  23.   
  24.         sprintf(files, "<html><title>Dir Browser</title>");  
  25.     sprintf(files,"%s<style type=""text/css""> a:link{text-decoration:none;} </style>",files);  
  26.     sprintf(files, "%s<body bgcolor=""ffffff"" font-family=Arial color=#fff font-size=14px>\r\n", files);  
  27.   
  28.     while((dirp=readdir(dp))!=NULL)  
  29.     {  
  30.         if(strcmp(dirp->d_name,".")==0||strcmp(dirp->d_name,"..")==0)  
  31.             continue;  
  32.         sprintf(name,"%s/%s",filename,dirp->d_name);  
  33.         Stat(name,&sbuf);  
  34.         filepasswd=getpwuid(sbuf.st_uid);  
  35.   
  36.         if(S_ISDIR(sbuf.st_mode))  
  37.         {  
  38.             sprintf(img,"<img src=""dir.png"" width=""24px"" height=""24px"">");  
  39.         }  
  40.         else if(S_ISFIFO(sbuf.st_mode))  
  41.         {  
  42.             sprintf(img,"<img src=""fifo.png"" width=""24px"" height=""24px"">");  
  43.         }  
  44.         else if(S_ISLNK(sbuf.st_mode))  
  45.         {  
  46.             sprintf(img,"<img src=""link.png"" width=""24px"" height=""24px"">");  
  47.         }  
  48.         else if(S_ISSOCK(sbuf.st_mode))  
  49.         {  
  50.             sprintf(img,"<img src=""sock.png"" width=""24px"" height=""24px"">");  
  51.         }  
  52.         else  
  53.             sprintf(img,"<img src=""file.png"" width=""24px"" height=""24px"">");  
  54.   
  55.   
  56.     sprintf(files,"%s<p><pre>%-2d%s""<a href=%s%s"">%-15s</a>%-10s%10d %24s</pre></p>\r\n",files,num++,img,dir,dirp->d_name,dirp->d_name,filepasswd->pw_name,(int)sbuf.st_size,timeModify(sbuf.st_mtime,modifyTime));  
  57.     }  
  58.     closedir(dp);  
  59.     sprintf(files,"%s</body></html>",files);  
  60.   
  61.     /* Send response headers to client */  
  62.     sprintf(buf, "HTTP/1.0 200 OK\r\n");  
  63.     sprintf(buf, "%sServer: Tiny Web Server\r\n", buf);  
  64.     sprintf(buf, "%sContent-length: %d\r\n", buf, strlen(files));  
  65.     sprintf(buf, "%sContent-type: %s\r\n\r\n", buf, "text/html");  
  66.   
  67.     #ifdef HTTPS  
  68.     if(ishttps)  
  69.     {  
  70.         SSL_write(ssl,buf,strlen(buf));  
  71.         SSL_write(ssl,files,strlen(files));  
  72.     }  
  73.     else  
  74.     #endif  
  75.     {  
  76.         Rio_writen(fd, buf, strlen(buf));  
  77.         Rio_writen(fd, files, strlen(files));  
  78.     }  
  79.     exit(0);  
  80.   
  81. }  

HTTPS的实现:
   HTTPS主要基于openssl的开源库实现。如果没有安装,那么我们就不#define HTTPS。
HTTPS的功能主要就是提供安全的连接,服务器和浏览器之间传送的数据是通过加密的,加密方式可以自己选定。
   开始连接时,服务器需要发送CA,由于我们的CA是自己签发的,所以需要我们自己添加为可信。


访问控制功能:
主要是通过获取客户端IP地址,并转换为整数,与上配置文件中定义的掩码,如果符合配置文件中允许的网段,那么可以访问,否则不可以。
具体实现如下。

[cpp] view plaincopy
  1. static long long ipadd_to_longlong(const char *ip)  
  2. {  
  3.     const char *p=ip;  
  4.     int ge,shi,bai,qian;  
  5.     qian=atoi(p);  
  6.   
  7.     p=strchr(p,'.')+1;  
  8.     bai=atoi(p);  
  9.   
  10.     p=strchr(p,'.')+1;  
  11.     shi=atoi(p);  
  12.   
  13.     p=strchr(p,'.')+1;  
  14.     ge=atoi(p);  
  15.   
  16.     return (qian<<24)+(bai<<16)+(shi<<8)+ge;  
  17. }  
  18.   
  19.   
  20. int access_ornot(const char *destip) // 0 -> not 1 -> ok  
  21. {  
  22.     //192.168.1/255.255.255.0  
  23.     char ipinfo[16],maskinfo[16];  
  24.     char *p,*ip=ipinfo,*mask=maskinfo;  
  25.     char count=0;  
  26.     char *maskget=Getconfig("mask");  
  27.     const char *destipconst,*ipinfoconst,*maskinfoconst;  
  28.     if(maskget=="")  
  29.     {  
  30.         printf("ok:%s\n",maskget);  
  31.         return 1;  
  32.     }     
  33.     p=maskget;  
  34. /* get ipinfo[] start */  
  35.     while(*p!='/')  
  36.     {  
  37.         if(*p=='.')  
  38.             ++count;  
  39.         *ip++=*p++;  
  40.     }  
  41.     while(count<3)  
  42.     {  
  43.         *ip++='.';  
  44.         *ip++='0';  
  45.         ++count;  
  46.     }  
  47.     *ip='\0';  
  48. /* get ipinfo[] end */  
  49. /* get maskinfo[] start */  
  50.     ++p;  
  51.     while(*p!='\0')  
  52.     {  
  53.         if(*p=='.')  
  54.             ++count;  
  55.         *mask++=*p++;  
  56.     }  
  57.     while(count<3)  
  58.     {  
  59.         *mask++='.';  
  60.         *mask++='0';  
  61.         ++count;  
  62.     }  
  63.     *mask='\0';  
  64.   
  65. /* get maskinfo[] end */  
  66.     destipconst=destip;  
  67.     ipinfoconst=ipinfo;  
  68.     maskinfoconst=maskinfo;  
  69.     return ipadd_to_longlong(ipinfoconst)==(ipadd_to_longlong(maskinfoconst)&ipadd_to_longlong(destipconst));  
  70. }  

配置文件的读取:
主要选项信息都定义与配置文件中。
格式举例如下;
#HTTP PORT
PORT = 8888
所以读取配置文件函数具体如下:

[cpp] view plaincopy
  1. static char* getconfig(char* name)  
  2. {  
  3. /* 
  4. pointer meaning: 
  5.  
  6. ...port...=...8000... 
  7.    |  |   |   |  | 
  8.   *fs |   |   |  *be    f->forward  b-> back 
  9.       *fe |   *bs       s->start    e-> end 
  10.           *equal 
  11. */  
  12.     static char info[64];  
  13.     int find=0;  
  14.     char tmp[256],fore[64],back[64],tmpcwd[MAXLINE];  
  15.     char *fs,*fe,*equal,*bs,*be,*start;  
  16.   
  17.     strcpy(tmpcwd,cwd);  
  18.     strcat(tmpcwd,"/");  
  19.     FILE *fp=getfp(strcat(tmpcwd,"config.ini"));  
  20.     while(fgets(tmp,255,fp)!=NULL)  
  21.     {  
  22.         start=tmp;  
  23.         equal=strchr(tmp,'=');  
  24.   
  25.         while(isblank(*start))  
  26.             ++start;  
  27.         fs=start;  
  28.   
  29.         if(*fs=='#')  
  30.             continue;  
  31.         while(isalpha(*start))  
  32.             ++start;  
  33.         fe=start-1;  
  34.   
  35.         strncpy(fore,fs,fe-fs+1);  
  36.         fore[fe-fs+1]='\0';  
  37.         if(strcmp(fore,name)!=0)  
  38.             continue;  
  39.         find=1;  
  40.   
  41.         start=equal+1;  
  42.         while(isblank(*start))  
  43.             ++start;  
  44.         bs=start;  
  45.   
  46.         while(!isblank(*start)&&*start!='\n')  
  47.             ++start;  
  48.         be=start-1;  
  49.   
  50.         strncpy(back,bs,be-bs+1);  
  51.         back[be-bs+1]='\0';  
  52.         strcpy(info,back);  
  53.         break;  
  54.     }  
  55.     if(find)  
  56.         return info;  
  57.     else  
  58.         return NULL;  
  59. }  


二、测试
本次测试使用了两台机器。一台Ubuntu的浏览器作为客户端,一台Redhat作为服务器端,其中Redhat是Ubuntu上基于VirtualBox的一台虚拟机。

IP地址信息如下:

Ubuntu的vboxnet0:



RedHateth0:



RedHat主机编译项目:


由于我们同事监听了8000和4444,所以有两个进程启动。


HTTP的首页:



目录显示功能:



HTTP GET页面:



HTTPGET响应:


从HTTP GET响应中我们观察URL,参数的确是通过URL传送过去的。

其中getAuth.c如下:

[cpp] view plaincopy
  1. #include "wrap.h"  
  2. #include "parse.h"  
  3.   
  4. int main(void) {  
  5.     char *buf, *p;  
  6.     char name[MAXLINE], passwd[MAXLINE],content[MAXLINE];  
  7.   
  8.     /* Extract the two arguments */  
  9.     if ((buf = getenv("QUERY_STRING")) != NULL) {  
  10.     p = strchr(buf, '&');  
  11.     *p = '\0';  
  12.     strcpy(name, buf);  
  13.     strcpy(passwd, p+1);  
  14.     }  
  15.   
  16.   
  17.     /* Make the response body */  
  18.     sprintf(content, "Welcome to auth.com:%s and %s\r\n<p>",name,passwd);  
  19.     sprintf(content, "%s\r\n", content);  
  20.   
  21.     sprintf(content, "%sThanks for visiting!\r\n", content);  
  22.     
  23.     /* Generate the HTTP response */  
  24.     printf("Content-length: %d\r\n", strlen(content));  
  25.     printf("Content-type: text/html\r\n\r\n");  
  26.     printf("%s", content);  
  27.     fflush(stdout);  
  28.     exit(0);  
  29. }  

HTTPS的首页:由于我们的CA不可信,所以需要我们认可



认可后HTTPS首页:



HTTPS POST页面:



HTTPS POST响应:


从上我们可以看出,POST提交的参数的确不是通过URL传送的。


0 0
原创粉丝点击