FastCGI protocol analysis and FastCGI implementation in PHP before discussing FastCGI, I have to talk about the working principle of traditional CGI. at the same time, I should understand the CGI 1.1 protocol.
Analysis on the working principle of traditional CGI
After the client accesses a URL address, it submits data through GET, POST, PUT, and other methods, and sends a request to the Web server through the HTTP protocol. The HTTP Daemon (Daemon process) of the server) pass the information described in the HTTP request to the CGI program specified on the home page through the standard input stdin and environment variable (environment variable, start the application for processing (including database processing). the processing result is returned to the HTTP Daemon through stdout, and then returned to the client by the HTTP Daemon process.
The above section may be abstract. the following uses a GET request as an example.
Web server code
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Define SERV_PORT 9003char * str_join (char * str1, char * str2); char * html_response (char * res, char * buf); int main (void) {int lfd, cfd; struct sockaddr_in serv_addr, clin_addr; socklen_t clin_len; char buf [1024], web_result [1024]; int len; FILE * cin; if (lfd = socket (AF_INET, SOCK_STREAM, 0) =-1) {perror ("create socket failed"); exit (1);} memset (& serv_addr, 0, sizeof (serv_addr); serv_addr.sin_family = AF_INET; inline = htonl (INADDR_ANY); serv_addr.sin_port = htons (SERV_PORT); if (bind (lfd, (struct sockaddr *) & serv_addr, sizeof (serv_addr )) =-1) {perror ("bind error"); exit (1);} if (listen (lfd, 128) =-1) {perror ("listen error"); exit (1);} signal (SIGCLD, SIG_IGN); while (1) {clin_len = sizeof (clin_addr ); if (cfd = accept (lfd, (struct sockaddr *) & clin_addr, & clin_len) = -1) {perror ("receive error \ n"); continue;} cin = fdopen (cfd, "r"); setbuf (cin, (char *) 0 ); fgets (buf, 1024, cin); // read the first row printf ("\ n % s", buf ); // ============================== cgi environment variable setting demo ======== ==========================================/// for example, "GET/user. cgi? Id = 1 HTTP/1.1 "; char * delim =" "; char * p; char * method, * filename, * query_string; char * query_string_pre =" QUERY_STRING = "; method = strtok (buf, delim); // GET p = strtok (NULL, delim); // user. cgi? Id = 1 filename = strtok (p ,"? "); // User. cgi if (strcmp (filename,"/favicon. ico ") = 0) {continue;} query_string = strtok (NULL ,"? "); // Id = 1 putenv (str_join (query_string_pre, query_string )); // ============================== cgi environment variable setting demo ======== ==================================== int pid = fork (); if (pid> 0) {close (cfd);} else if (pid = 0) {close (lfd); FILE * stream = popen (str_join (". ", filename)," r "); fread (buf, sizeof (char), sizeof (buf), stream); html_response (web_result, buf); write (cfd, web_result, sizeof (web_result); pclose (stream); close (cfd); exit (0);} else {perror ("fork error"); exit (1 );}} close (lfd); return 0;} char * str_join (char * str1, char * str2) {char * result = malloc (strlen (str1) + strlen (str2) + 1); if (result = NULL) exit (1); strcpy (result, str1); strcat (result, str2); return result ;} char * html_response (char * res, char * buf) {char * html_response_template = "HTTP/1.1 200 OK \ r \ nContent-Type: text/html \ r \ nContent-Length: % d \ r \ nServer: mengkang \ r \ n % s "; sprintf (res, html_response_template, strlen (buf), buf); return res ;}
CGI program (user. c)
# Include
# Include
// Query the user information through the obtained id int main (void) {// ============================================ simulation database ======== ================================= typedef struct {int id; char * username; int age;} user; user users [] ={{}, {1, "mengkang. zhou ", 18 }}; // ================================================================= ============================== char * query_string; int id; query_string = getenv ("QUERY_STRING"); if (query_string = NULL) {printf ("no input data");} else if (sscanf (query_string, "id = % D ", & id )! = 1) {printf ("no input id");} else {printf ("user information query
Student ID: % d
Name: % s
Age: % d ", id, users [id]. username, users [id]. age);} return 0 ;}
Compile the above CGI program into gcc user. c-o user. cgi and place it in the same directory of the web program above.
FastCGI working principle analysis
In contrast to the CGI/1.1 specification, a local fork sub-process on the Web server executes the CGI program, fills in the predefined CGI environment variables, and puts them into the system environment variables, pass the content of the HTTP body to the sub-process through standard input. after processing, the content is returned to the Web server through standard output. The core of FastCGI is to ban the traditional fork-and-execute method to reduce the huge overhead of each startup (PHP is used as an example later) and process requests in a resident manner.
The difference between FastCGI and the traditional CGI mode is that the Web server does not directly execute CGI programs, but interacts with FastCGI responder (FastCGI Process Manager) through socket, the Web server needs to encapsulate CGI interface data in the FastCGI protocol package and send it to the FastCGI responder program. Because FastCGI Process Manager is socket-based, it is also distributed. the Web server and CGI responder server are deployed separately.
FastCGI message process
Some examples of http://www.fastcgi.com/devkit/doc/fcgi-spec.html#SB are listed in the official introduction document
The following describes a simple process, as shown in
For example
{FCGI_BEGIN_REQUEST, 1, {FCGI_RESPONDER, 0}}{FCGI_PARAMS, 1, "\013\002SERVER_PORT80\013\016SERVER_ADDR199.170.183.42 ... "}{FCGI_STDIN, 1, "quantity=100&item=3047936"}{FCGI_STDOUT, 1, "Content-type: text/html\r\n\r\n\n ... "}{FCGI_END_REQUEST, 1, {0, FCGI_REQUEST_COMPLETE}}
Definition of each stage of a FastCGI request in PHP
typedef enum _fcgi_request_type {FCGI_BEGIN_REQUEST= 1, /* [in] */FCGI_ABORT_REQUEST= 2, /* [in] (not supported) */FCGI_END_REQUEST= 3, /* [out] */FCGI_PARAMS= 4, /* [in] environment variables */FCGI_STDIN= 5, /* [in] post data */FCGI_STDOUT= 6, /* [out] response */FCGI_STDERR= 7, /* [out] errors */FCGI_DATA= 8, /* [in] filter data (not supported) */FCGI_GET_VALUES= 9, /* [in] */FCGI_GET_VALUES_RESULT= 10 /* [out] */} fcgi_request_type;Definition of FastCGI header in PHP
typedef struct _fcgi_header {unsigned char version;unsigned char type;unsigned char requestIdB1;unsigned char requestIdB0;unsigned char contentLengthB1;unsigned char contentLengthB0;unsigned char paddingLength;unsigned char reserved;} fcgi_header;Field description
Version identifies the FastCGI protocol version.
Type identifies the FastCGI record type, that is, the general function of record execution.
The requestId identifies the FastCGI request to which the record belongs.
The number of bytes of the contentData component recorded by contentLength.
The preceding protocols for xxB1 and xxB0 indicate that when two adjacent structural components have the same name except the suffix "B1" and "B0, it indicates that the two components can be considered as a single number valued at B1 <8 + B0. The name of a single digit is the name of the component minus the suffix. This convention summarizes a processing method of numbers represented by more than two bytes.
For example, the maximum value of requestId and contentLength in the protocol header is 65535
#include
#include
#include
int main(){ unsigned char requestIdB1 = UCHAR_MAX; unsigned char requestIdB0 = UCHAR_MAX; printf("%d\n", (requestIdB1 << 8) + requestIdB0); // 65535}
Definition of FCGI_BEGIN_REQUEST in PHP
typedef struct _fcgi_begin_request {unsigned char roleB1;unsigned char roleB0;unsigned char flags;unsigned char reserved[5];} fcgi_begin_request;
The Web server sends a FCGI_BEGIN_REQUEST record to start a request.
Field description
Role indicates the role that the Web server expects the application to play. Three roles are also defined in PHP.
typedef enum _fcgi_role {FCGI_RESPONDER= 1,FCGI_AUTHORIZER= 2,FCGI_FILTER= 3} fcgi_role;
The flags component contains a bit of flags & FCGI_KEEP_CONN: if it is 0, the application closes the line after responding to this request. If the value is not 0, the application does not close the line after responding to this request. the Web server maintains responsiveness for the line.
Definition of FCGI_END_REQUEST in PHP
typedef struct _fcgi_end_request { unsigned char appStatusB3; unsigned char appStatusB2; unsigned char appStatusB1; unsigned char appStatusB0; unsigned char protocolStatus; unsigned char reserved[3];} fcgi_end_request;
The appStatus component is an application-level status code.
The protocolStatus component is a protocol-level status code. The value of protocolStatus may be:
FCGI_REQUEST_COMPLETE: The request ends normally.
FCGI_CANT_MPX_CONN: reject new requests. This occurs when the Web server sends concurrent requests to the application over a line, and the latter is designed to process one request each line at a time.
FCGI_OVERLOADED: reject new requests. This occurs when the application has used up some resources, such as database connections.
FCGI_UNKNOWN_ROLE: reject new requests. This occurs when the Web server specifies a role that cannot be recognized by the application.
The definition of protocolStatus in PHP is as follows:
typedef enum _fcgi_protocol_status {FCGI_REQUEST_COMPLETE= 0,FCGI_CANT_MPX_CONN= 1,FCGI_OVERLOADED= 2,FCGI_UNKNOWN_ROLE= 3} dcgi_protocol_status;
Note that the values of each element of dcgi_protocol_status and fcgi_role are defined in the FastCGI protocol, rather than PHP.