CGI program design in C Language

Source: Internet
Author: User


I just finished the first product development related to embedded in the company. I am born from Java Web and have a legendary job-seeking experience (Don't boast about it, please don't be confused about it). I am confused from a Java Web, turn to be an embedded person that I dream! Too much nonsense is not good. Let's summarize the problems encountered during product development for future reference.
As a transformation company, the company has been focusing on R & D in recent years. In addition to my Java Web Background, I developed C for other technologies. The new Yali is quite large, although I have a certain C and C ++ basics.
When I first came in, I was familiar with the company's products. I read the source code (basically C in linux), and it was a hard time, the boss asked me to rebuild the configuration interface of a product in the company. This requires direct flash. The maximum project capacity is 1 MB! Since I did not conduct any in-depth research at the beginning, I have been adhering to the thinking of java web. I think that the project size is indifferent. It is stored on a computer, and I just need to resize the hard disk if it is not enough. But later I found that embedded products are very sensitive to this. When designing, we should consider how to slim down programs and improve code quality.
It took about two months to complete the preliminary product transformation, followed by some minor repairs and supplements, the boss handed over the rest to the person who has been working with me, so that I began to invest in research and development related to the company's PBX.
The company's PBX is a core product. The first thing I need to do is to unify the style of the original configuration interface with a previous product (cgi (c implementation in linux) + jquery ). Another blow: linux development, non-stop vi, and have to understand the familiar communication principles and deep-level applications of lighttpd and cgi (c implementation. Previously, I was roughly distracted by this product. It is estimated that it would take a very painful development...
However, IT is doomed to require continuous learning. Below I will write down some of my knowledge about cgi, and welcome to be able to shoot bricks.

[Color = olive] 1. CGI Overview
CGI (Public Gateway Interface) specifies the interface protocol standard for Web servers to call other executable programs (CGI. The Web server calls the CGI program to interact with the Web browser, that is, the CGI program receives the information sent from the Web browser to the Web server for processing, and sends the corresponding results to the Web server and Web browser. CGI programs generally process form data on Web pages, query databases, and integrate with traditional application systems. CGI programs can be written in any programming language, such as shell, Perl, Fortran, Pascal, and C. However, CGI programs written in C language have the features of fast execution and high security (because C language programs are compiled and executed and cannot be modified.

The CGI interface standard consists of three parts: standard input, environment variable, and standard output.
1. Standard Input

CGI programs, like other executable programs, can get input information from the Web server through standard input (stdin), such as data in Form, this is the shrinking POST method that transmits data to CGI programs. This means that the CGI program can be executed and debugged in the command line status of the operating system. (Starting from getting started with embedded systems, you should adapt to environments that frequently deal with operating systems, especially unix and linux ). The POST method is a common method. I will take this method as an example to analyze the methods, processes, and skills of CGI program design.

2. Environment Variables

The operating system provides many environment variables that define the execution environment of the program and the application can access them. The Web server and CGI interface also set some environment variables to pass some important parameters to the CGI program. The cgi get method also transmits the data in Form to the CGI program through the Environment Variable QUERY-STRING.

3. standard output

The standard output (stdout) of the CGI program sends the output information to the Web server. The information sent to the Web server can be in various formats, usually in plain text or html text, so that we can debug CGI programs in the command line status and get their output.

The following is a simple CGI program implemented by C. It outputs the form information in html directly to the Web browser.


C code
# Include <stdin. h>
# Include <stdlib. h>
Main ()
{
Int I, n;
Printf ("Contenttype: text/plain \ n ");
N = 0;
If (getenv ("CONTENT-LENGTH "))
N = atoi (getenv ("CONTENT-LENGTH "));
For (I = 0; I <n; I ++)
Putchar (getchar ());
Putchar ("\ n ");
Fflush (stdout );
}


The following is a brief analysis of the program.
Printf ("Contenttype: text/plain \ n ");
This line transmits the string Contenttype: text/plain \ n to the Web server through standard output. It is a MINE header that tells the Web server that subsequent output is in plain ASCII text format. Note: There are two line breaks in the header, because the Web server needs to see a blank line before the actual text information starts.
If (getenv ("CONTENT-LENGTH") n = atoi (getenv ("CONTENT-LENGTH "));
This line first checks whether the CONTENT-LENGTH environment variable exists. The Web server sets this environment variable when calling a CGI program using the POST method. Its text value indicates the number of characters that the Web server sends to the CGI program, so it uses atoi () the function converts the value of this environment variable to an integer and assigns the value to n. Note that the Web server does not terminate its output with the file Terminator. Therefore, if the CONTENT-LENGTH environment variable is not checked, the CGI program cannot know when the input is complete.
For (I = 0; I <n; I ++) putchar (getchar ());
This line is from 0 cycles to CONTENT-LENGTH-1 times, and each character read in the standard input is directly copied to the standard output, that is, all input is sent back to the Web server in ASCII form.

In this example, the general working process of the CGI program can be summarized as follows:
1. Check the CONTENT-LENGTH environment variable to determine the number of inputs.
2. cyclically use getchar () or other file read functions to get all input
3. process the input in a corresponding way
4. Use the Contenttype header to tell the Web server the format of the output information.
5. Write functions using printf (), putchar (), or other files to send the output to the Web server.

2. Environment Variables

The environment variable is a text string (name/Value Pair), which can be set by OS Shell or other programs or accessed by other programs. They are simple means for Web servers to pass data to CGI programs. They are called environment variables because they are global variables and can be accessed by any program.
 
The following are some environment variables that are frequently used in CGI programming:
HTTP-REFERER: the URL of the web page that calls the CGI program
REMOTE-HOST: The machine name and domain name of the Web browser that calls the CGI program
REQUEST-METHOD: the METHOD used when the Web server transmits data to the CGI program, which can be GET or POST. The GET method only transmits data to CGI programs through environment variables (such as QUERY-STRING), while the POST method transmits data to CGI programs through environment variables and standard input, therefore, the POST method can easily transmit data to CGI programs.
SCRIPT-NAME: the CGI program NAME.
QUERY-STRING: When the POST method is used, the data in Form is placed in QUERY-STRING and passed to the CGI program.
CONTENT-TYPE: mime type passed to CGI program data, usually "application/x-www-form-url-encoded ", it is the data encoding type that the POST method transmits to the CGI program in html form and becomes the URL encoding type.
CONTENT-LENGTH: the number of data characters passed to the CGI program (bytes)

3. Analysis and decoding of input in Form

1. Analyze name/value pairs

When a user submits an html form, the Web browser first encodes the data in form in the form of name/value pairs, sends the data to the Web server, and then passes the data to the CGI program by the Web server. The format is as follows:
Name1 = value1 & name2 = value2 & name3 = value3 & name4 = value4...
The name is the name of the input, select, textarea, and other tags defined in form. The value is the user input or selected value. This format is URL encoding, which needs to be analyzed and decoded in the program. To analyze this type of data stream, the CGI program must first break down the data stream into a group of name/value pairs, which can be done by finding the following two characters in the input stream.
Every time the character = is found, it indicates the end of a form variable name; every time the character & is found, it indicates the end of a form variable value. Note that the last variable value of the input data does not end.
After the name/value pair is decomposed, some special characters in the input must be converted into ASCII characters. These special characters are:
+: Convert + to a space character.
% Xx: a special character expressed by its hexadecimal ASCII value. Converts a Value xx to an ASCII character.
Perform this conversion for the form variable name and variable value. The following is a CGI program that analyzes form data and sends the result back to the Web server.


C code
# Include <stdio. h>
# Include <stdlib. h>
# Include <strings. h>
 
Int htoi (char *);
 
Main ()
{
Int I, n;
Char c;
Printf ("Contenttype: text/plain \ n ");
N = 0;
If (getenv ("CONTENT-LENGTH "))
N = atoi ("CONTENT-LENGTH ");
For (I = 0; I <n; I ++)
{
Int is-eq = 0;
C = getchar ();
Switch (c)
{
Case '&':
C = '\ n ';
Break;
Case '+ ':
C = '';
Break;
Case '% ':
{
Char s [3];
S [0] = getchar ();
S [1] = getchar ();
S [2] = 0;
C = htoi (s );
I + = 2;
}
Break;
Case '= ':
C = ':';
Is-eq = 1;
Break;
};
Putchar (c );
If (is-eq)
Putchar ('');
}
Putchar ('\ n ');
Fflush (stdout );
}

/** Convert hex string to int **/
Int htoi (char * s)
{
Char * digits = "0123456789 ABCDEF ";
If (islower (s [0]) s [0] = toupper (s [0]);
If (islower (s [1]) s [1] = toupper (s [1]);
Return 16 * (strchar (digits, s [0])-strchar (digits, '0') + (strchar (digits, s [1]-strchar (digits, '0 ')));

}

The above program first outputs a MIME header information to the Web server, checks the number of characters in the input, and cyclically checks each character.

3. Generate HTML output

CGI output consists of the MIME header information and actual information. The two parts are separated by a blank line. You can use the MIME header information "Contenttype: text/html \ n" to output the html source code to the Web server. The following is a simple example:


C code
# Include <stdio. h>
# Include <string. h>
Main ()
{
Printf ("Contenttype: text/html \ n ");
Printf (" 
Printf (" 
Printf (" 
Printf (" 
Printf ("<a href =" ../output.html # two "> <B> Go back to out put.html page <
/B> </a> \ n ");
 
Printf ("</body> \ n ");
 
Printf (" 
Fflush (stdout );
}

Author "telyy123"
 

Related Article

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.