Tiny Web server Code Analysis

Source: Internet
Author: User

Tiny Web server Code Analysis

"In-depth understanding computer system" developed a small but full-featured Web server called Tiny, here is the tiny server source code parsing.

1.Tiny's main program

Tiny is an iterative server that passes a port value through the command line, calls the OPEN_LISTENFD () function to open a listening socket, and then tiny performs an infinite loop: The server blocks on accept, waits for a connection request on the listener descriptor LISTENFD, When the server returns CONNFD from Accept, it indicates that it has established a connection with the client, executes the transaction, and closes the end of the connection to it, making the next loop.

#include "csapp.h"voidDoitintFD);voidRead_requesthdrs (rio_t *RP);intParse_uri (Char*uri,Char*filename,Char*cgiargs);voidServe_static (intFdChar*filename,intFileSize);voidGet_filetype (Char*filename,Char*filetype);voidServe_dynamic (intFdChar*filename,Char*cgiargs);voidClienterror (intFdChar*cause,Char*errnum,Char*shorting,Char*LONGMSG);intMainintargcChar*argv[]) {intListenfd,connfd,port,clientlen;structSockaddr_in clientaddr;if(ARGC! =2)    {fprintf(stderr,"Usage:%s <port>\n", argv[0]);Exit(0); } port = atoi (argv[1]); LISTENFD = OPEN_LISTENFD (port); while(1) {Clientlen =sizeof(CLIENTADDR);        CONNFD = Accept (LISTENFD, (SA *) &clientaddr, &clientlen);        Doit (CONNFD);    Close (CONNFD); }}
2.doit () Handling HTTP transactions

First look at the composition of the HTTP request. An HTTP request consists of a request line followed by 0 or more request headers followed by an empty line of text to terminate the list of headers.
The format of the HTTP request line is as follows.

<method><uri><version>

HTTP supports many methods, including GET, POST, OPTIONS, HEAD, PUT, delete, and trace. Currently tiny only supports the Get method, and the Get method instructs the server to generate and return the contents of the URI identity. The URI is the suffix of the URL, including the file name and parameters. The Version field indicates the HTTP version that the request follows, with http/1.0 and http/1.1.
Doit () Handles HTTP transactions.
  The request line is read and parsed , and the code uses RIO_READLINEB () to read a row of data from FD to BUF, and then write the variable Method,uri and version respectively.
Tiny does not use any of the information in the request header, the Read_requesthdrs () function ignores the message of the header.
  extract the URI information from the request , use Parse_uri () to extract the file name and request parameters from the URI, and return the value to identify the static content or dynamic content. Using stat () to get the state of the file and save the state to Sbuf, the execution returns 0 successfully, or 1 if execution fails, indicating that the file does not exist on disk.
If you are requesting static content , you need to verify that the file is a generic file (St_mode = = S_isreg) and that we have Read permissions. If so, we provide static content to the client. Similarly, if you are requesting dynamic content , you need to verify that the file is an executable file, and if so, provide dynamic content to the client.

voidDoitintFD) {intis_static;structStat sbuf;CharBuf[maxline], Method[maxline],uri[maxline],version[MAXLINE];CharFilename[maxline],cgiargs[maxline]; rio_t Rio;/*read request Line and headers*/RIO_READINITB (&rio, FD);    Rio_readlineb (&rio, buf, MAXLINE); SSCANF (BUF,'%s%s '%s ', method, Uri,version);if(strcasecmp (method,"GET") {Clienterror (fd, method,"501","Not implemented","Tiny does not implement this method");return; } Read_requesthdrs (&rio);/*prase URI from GET request*/is_static = Parse_uri (URI, filename, Cgiargs);if(Stat (filename, &sbuf) <0) {clienterror (fd, filename,"404","Not Found","Tiny couldn ' t find this file");return; }if(is_static)//server Static Content{if(! (S_isreg (sbuf.st_mode) | |!        (S_irusr & Sbuf.st_mode))) {clienterror (fd, filename,"403","Forbidden","Tiny couldn ' t read the file");return;    } serve_static (fd, filename, sbuf.st_size); }Else//server Dynamic Content{if(! (S_isreg (sbuf.st_mode) | |!        (S_ixusr & Sbuf.st_mode))) {clienterror (fd, filename,"403","Forbidden","Tiny couldn ' t run the CGI program");return;       } serve_dynamic (fd, filename, Cgiargs); }}
3.clienterror () to check for some errors

First look at the composition of the HTTP response line. HTTP responses are similar to HTTP requests. An HTTP response consists of a response line followed by 0 or more response headers followed by a blank line terminating the header followed by the response body. The format of the response line is:

<version><status Code><status message>

The Version field describes the HTTP version that the response follows. The status code is a three-bit positive integer that indicates the processing of the request. The status message gives an English description equivalent to the error code.
Clienterror () sends an HTTP response message to the client, including a status code and status message in the response line, and the response body contains an HTML file to explain the error to the user.

void Clienterror (intFD, Char*cause, Char*errnum, Char*shortmsg, Char*longmsg) {char buf[maxline], body[maxbuf];/*build The HTTP response body*/    sprintf(Body,");sprintf(Body,"%s<body bgcolor=""FFFFFF"">\r\n", body);sprintf(Body,'%s%s: %s\ r \ n ', body,errnum,shortmsg);sprintf(Body,"%s<p>%s: %s\ r \ n", body, longmsg, cause);sprintf(Body,"%s, body);/*print the HTTP response*/    sprintf(BUF,"http/1.0 %s %s\ r \ n", Errnum, shortmsg); Rio_writen (FD, buf, strlen (BUF));sprintf(BUF,"content-type:text/html\r\n"); Rio_writen (FD, buf, strlen (BUF));sprintf(BUF,"Content-length: %d\r\n\r\n",(int) strlen (body));    Rio_writen (FD, buf, strlen (BUF)); Rio_writen (FD, Body, strlen (body));}
4.read_requesthdrs () skips the request header information until it encounters an empty line that represents the end of the header.
read_requesthdrs(rio_t *rp){    char buf[MAXLINE];    Rio_readlineb(rp, buf, MAXLINE);    while(strcmp(buf, "\r\n"))    {        Rio_readlineb(rp, buf, MAXLINE);        printf("%s", buf);    }    return;}
5.parse_uri () parsing URI parameters

parse_uri () resolves the URI to a file name and an optional CGI parameter string. In the case of static content, we will clear the CGI argument string (which will cgiargs empty) and then convert the URI to a relative Unix pathname, such as./home.html. If the URI is in/end, add the default file name home.html later. In the case of dynamic content, the file name and CGI parameters in the URI are split so that the CGI parameter and file name can be extracted.

intParse_uri (Char*uri,Char*filename,Char*cgiargs) {Char*ptr;if(!strstr(URI,"Cgi-bin"))//static Content{strcpy(Cgiargs,"");strcpy(FileName,".");strcat(filename, URI);if(uri[strlen(URI)-1] =='/')strcat(URI,"home.html");return 1; }Else{ptr = index (URI,'? ');if(PTR) {strcpy(Cgiargs, ptr+1); *ptr =' + '; }Else            strcpy(Cgiargs,"");strcpy(FileName,".");strcat(filename, URI);return 0; }}
6.serve_static () Handling static content

Tiny provides four different static content: HTML files, unformatted text files, images encoded in GIF and JPEG format.
The serve_static () function sends an HTTP response in which the body of the response includes the contents of a local file. First, we check the filename suffix to determine the file type and display it in the Content-type field of the response header. We then send a response line and a response header to the client, terminating the header with a blank line.
We then open the requested file in a read-only way to get the file handle SRCFD, and use the MMAP function to map the file to the virtual memory space, which maps the first filesize bytes of the file pointed to by SRCFD to a read-only private virtual memory area where the address starts at SRCP. Once the mapping is successful we can manipulate the file through SRCP and no longer need the file handle, so we close the SRCFD. We then use Rio_writen () to transfer the files to the client. At this point the processing of the static content has been completed, we release the SRCP virtual memory mapping.

voidServe_static (intFdChar*filename,intFileSize) {intSRCFD;Char*SRCP, Filetype[maxline], buf[maxbuf];/*send Response headers to client*/Get_filetype (Filename,filetype);sprintf(BUF,"http/1.0 ok\r\n");sprintf(BUF,"%sserver:tiny Web server\r\n", buf);sprintf(BUF,"%scontent-lenght:%d\r\n", buf, filesize);sprintf(BUF,"%scontent-type:%s\r\n\r\n", buf, filetype); Rio_writen (FD, BUF,strlen(BUF));/*send response body to client*/SRCFD = Open (filename, o_rdonly,0); SRCP = Mmap (0, FileSize, Prot_read, MAP_PRIVATE,SRCFD,0);    Close (SRCFD);    Rio_writen (FD, SRCP, filesize); Munmap (SRCP, filesize);}voidGet_filetype (Char*filename,Char*filetype) {if(strstr(FileName,". html"))strcpy(FileType,"Text/html");Else if(strstr(FileName,". gif"))strcpy(FileType,"Image/gif");Else if(strstr(FileName,". jpg"))strcpy(FileType,"Image/jpeg");Else         strcpy(FileType,"Text/plain");}
7.serve_dynamic () Handling dynamic content

Tiny provides various types of dynamic content by deriving a child process and running a CGI program in a child process.
The program first sends a response line that indicates success, and also includes the server header with information to the client. The CGI program is responsible for sending the remaining parts of the response.
Then we derive a child process, which initializes the QUERY_STRING environment variable with the CGI parameter from the request URI, which the CGI program uses to get the CGI parameter values. Next, the child process redirects the standard output to the connected file descriptor, and then loads and runs the CGI program. Because a CGI program runs in the context of a child process, it has access to all open files and environment variables that existed before the EXECVE function was called. So the CGI program writes the data on the standard output directly to the client process, without interference from the parent process. The flagship parent process is blocked in a call to wait (), and when the child process terminates, the resource that the operating system allocates to the child process is recycled.

voidServe_dynamic (intFdChar*filename,Char*cgiargs) {CharBuf[maxline], *emptylist[]={null};/*return first part of HTTP response*/    sprintf(BUF,"http/1.0 ok\r\n"); Rio_writen (FD, BUF,strlen(BUF));sprintf(BUF,"Server:tiny Web server\r\n"); Rio_writen (FD, BUF,strlen(BUF));if(Fork () = =0) {setenv ("Query_string", Cgiargs,1);        Dup2 (FD, Stdout_fileno);    Execve (filename, emptylist,environ); } Wait (NULL);}

Tiny Web server Code Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.