Sinlinx A33 development board boa and CGI transplantation[Copy link]
In the management and interaction of embedded devices, Web-based applications have become the mainstream. This program structure is the familiar B/S structure, that is, a Web server that supports scripts or CGI functions is run on the embedded device, which can generate dynamic pages. The user only needs to use a Web browser to manage and monitor the embedded device, which is very convenient and practical. This section mainly introduces the development and migration of this application. Users first need to successfully migrate a Web server that supports scripts or CGI functions on the embedded device before they can develop the application. 1. Embedded Web server transplantation Since the resources of embedded devices are generally limited, and they do not need to handle many user requests at the same time, the most commonly used servers under Linux, such as Apache, cannot be used. Instead, some Web servers specially designed for embedded devices need to be used. These Web servers are very suitable for embedded applications in terms of storage space and memory space occupied during runtime. Typical embedded Web servers include Boa (http://www.boa.org/www.boa.org) and thttpd (http://www.acme.com/software/thttpd/), etc. The main difference between them and high-performance Web servers such as Apache is that they are generally single-process servers, and can only respond to another user's request after completing a user request, and cannot respond concurrently, but this is enough for the application of embedded devices. We introduce the transplantation of the more commonly used Boa server. Boa is a very small Web server with only about 60KB of executable code. It is a single-task web server that can only complete user requests one by one, and will not fork a new process to handle concurrent connection requests. But Boa supports CGI and can fork a process for CGI programs to execute. The design goals of Boa are speed and security. In the performance tests published on its website, Boa's performance is better than that of the Apache server. The first step is to complete the porting of the Boa program. Download Boa source code from www.boa.org. The latest version is 0.94.13. Unzip it and enter the src subdirectory of the source code directory # tar xzf boa-0.94.13.tar.gz # cd boa-0.94.13/src Generate Makefile file # ./configure Modify the Makefile file, find CC=gcc, change it to CC = arm-none-linux-gnueabi-gcc, then find CPP = gcc ¨CE, change it to CPP = arm-none-linux-gnueabi-gcc ¨CE, save and exit. Then run make to compile, the executable program obtained is boa, strip the debugging information, and the final program is only about 60KB in size. # make # arm-none-linux-gnueabi-strip boa The second step completes the configuration of Boa so that it can support the execution of CGI programs. Boa needs to create a boa directory in the /etc directory, and put the main Boa configuration file boa.conf in it. There is already an example boa in the Boa source directory.conf, which can be modified on this basis. The following explains the meaning of the file:#Listen port number, the default is 80, generally no need to modify Port 80 # The IP address called by bind is generally commented out, indicating that it is bound to INADDR_ANY, which is wildcard for all IP addresses of the server #Listen 192.68.0.5 #Which user does it run as? That is, it has the permissions of that user. Usually, it is nobody. It needs to have the nogroup group in /etc/passwd. #nobody user User nobody #Which user group does it run as? That is, it has the permissions of that user group. Usually, it is nogroup. It needs to have the nogroup group in /etc/group file. Group nogroup#The email address to send alarms when a problem occurs on the server. Currently unused, comment out#ServerAdmin root@localhost#Error log file. If it does not start with /, it means starting from the root path of the server. If error logs are not needed, use #/dev/null. When setting up the following, be sure to create the /var/log/boa directory. ErrorLog /var/log/boa/error_log#Access log file. If it does not start with /, it means starting from the root path of the server. If you do not need an error log, use #/dev/null or comment it out directly. When setting up the following, be sure to create the /var/log/boa directory. #AccessLog /var/log/boa/access_log #Whether to use local time. If not commented out, use local time. If commented out, use UTC time #UseLocaltime #Whether to record CGI running information, if not commented out, record, if commented out, do not record #VerboseCGILogs #Server name ServerName www.hyesco.com #Whether to enable the virtual host function, that is, the device can have multiple network interfaces, each interface can have a virtual Web server #Server. Generally commented out, that is, no need to start #VirtualHost #Very important, the main directory of the HTML document. If it does not start with /, it means starting from the root path of the server. DocumentRoot /var/www #If a user request is received, the directory name added after the user's home directory UserDir public_html #The file name of the HTML directory index, which is also the file name returned when only the directory is accessed without the user specifying it DirectoryIndex index.html #DirectoryMaker /usr/lib/boa/boa_indexer #If DirectoryIndex does not exist and DirectoryMaker is commented out, use Boa's own index # Generate a program to generate a directory index file and output it to the following directory. The directory must be readable and writable by Boa. # DirectoryCache /var/spool/boa/dircache. # The maximum number of HTTP persistence requests allowed for a connection. Commenting or setting it to 0 will turn off HTTP persistence. # KeepAliveMax 1000. # KeepAliveMax 1000. #The time the server waits between two requests during HTTP persistence, in seconds. A timeout will close the connection KeepAliveTimeout 10 #Specify the location of the mime.types file. If it does not start with /, it means starting from the root path of the server. Can be commented out #Avoid using mime.types files. In this case, you need to use AddType to specify it in this file MimeTypes /etc/mime.types #If the file extension is not present or unknown, the default MIME type is used DefaultType text/plain #Provide the PATH environment variable value for CGI programs CGIPath /bin:/usr/bin:/usr/local/bin #Associate file extensions with MIME types, which has the same function as the mime.types file. If you use the mime.types file, comment it out. If you do not use the mime.types file, you must use it. #AddType application/x-httpd-cgi cgi #Specify the document redirection path #Redirect /bar http://elsewhere/feh/bar #Add an alias to the path Alias /doc /usr/doc #Very important, specifies the actual path corresponding to the virtual path of the CGI script. Generally, all CGI scripts should be placed in the actual path#. When users visit and execute, they enter the site + virtual path + CGI script name ScriptAlias /cgi-bin/ /var/www/cgi-bin/ Users can modify boa.conf according to their needs, but they must ensure that other auxiliary files and settings must be consistent with boa.conf, otherwise Boa will not work properly. /size/font/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/color/ External extension applications written in accordance with the CGI standard can process data input by the client browser, thereby completing the interactive operation between the client and the server. The CGI specification defines how the Web server sends messages to the extension application and how to process the information received from the extension application. CGI can provide many functions that static HTML pages cannot achieve, such as search engines, Web-based database access, etc. The main functions of CGI: A. Analyze data and automatically correct data sent by some defective browsers B. Transparently receive From data sent by GET or POST method C. Accept uploaded files D. Can set and receive cookies E. Handle carriage returns in From elements in a consistent manner F. Provide string, integer, floating point, single or multiple selection functions to receive data G. Provide boundary checking for numeric fields H. Be able to convert CGI environment variables into non-empty strings in C I. Provide debugging methods for CGI programs and be able to replay the CGI status when the CGI program is executed 2. Working Mechanism of BOA and CGI Working Mechanism of BOA and CGI: HTTP protocol is the foundation of WWW. Based on the client/server model, the server can provide services to clients distributed in the network. HTTP is a "connectionless" protocol built on TCP/IP protocol. Each connection only processes one request. On the BOA server, a daemon process is running to listen to the port and wait for requests from clients. When a request comes, a child process will be created to serve the user's connection. Depending on the request, the server returns an HTML file or calls an external application through CGI and returns the processing result. The server interacts with external programs and scripts through CGI. According to the method adopted by the client when making a request, the server will collect the information provided by the client and send the information to the specified CGI extension program. The CGI extension program processes the information and returns the results to the server, and then the server analyzes the information and sends the results back to the client. The external CGI program communicates with the BOA server and passes relevant parameters and processing results through environment variables, command line parameters and standard input. The server provides a channel for information exchange between the client (browser) and the CGI extension program. The standard input of CGI is the standard output of the server, and the standard output of CGI is the standard input of the server. The client's request is transmitted to the standard input of CGI through the standard output of the server. After CGI processes the information, it sends the results to its standard input, and then the server sends the processing results to the client. CGIC is a powerful standard C library that supports CGI development and supports multiple operating systems such as Linux, Unix and Windows. CGIC's main sitehttp://www.boutell.com/cgic/ 3. URL Introduction The client browser sends data to the server in the form of encoding, which is URL encoding. The main work of encoding is to escape the name and value of the form field. The specific method is as follows: the space in each pair of field and value will be replaced by a plus sign (+) character, and the characters that are not letters or numbers will be replaced by their hexadecimal digital form in the format of %HH. HH is the ASCII hexadecimal value of the character.com/cgic/[/url] 3. URL Introduction The client browser sends data to the server in the form of encoding, which is URL encoding. The main work of encoding is to escape the name and value of the form field. The specific method is: the space in each pair of field and value will be replaced by a plus sign (+) character, and the characters that are not letters or numbers will be replaced by their hexadecimal digital form in the format of %HH. HH is the ASCII hexadecimal value of the character.com/cgic/[/url] 3. URL Introduction The client browser sends data to the server in the form of encoding, which is URL encoding. The main work of encoding is to escape the name and value of the form field. The specific method is: the space in each pair of field and value will be replaced by a plus sign (+) character, and the characters that are not letters or numbers will be replaced by their hexadecimal digital form in the format of %HH. HH is the ASCII hexadecimal value of the character. The tag will be replaced with "%0D%0A". The information is arranged in the order in which it appears in the form. The name of the data field and the value of the data field are connected together by the equal sign (=) character. Each name/value pair is connected together by the "&" character. After these encoding processes, the form signal becomes a continuous character stream that contains all the information that will be sent to the server. Because form input information is passed to the script program in encoded form, the CGI extension must decode them before using these parameters. 2. CGIC compilation configuration 1. Download CGIC source code tar -zxvf cgic206.tar.gz 2. Modify the Makefile file CC=arm-none-linux-gnueabi--gcc AR=arm-none-linux-gnueabi--ar RANLIB=arm-none-linux-gnueabi-ranlib CFLAGS=-g -Wall -static cgictest.cgi: cgictest.o libcgic.a $(CC) $(CFLAGS) cgictest.o -o cgictest.cgi ${LIBS} capture: capture.o libcgic.a $(CC) $(CFLAGS) capture.o -o capture ${LIBS} 3. Compile make Compiled files libcgic.a£ºCGIC library capture£ºDebug auxiliary program cgictest.cgi£ºTest program 4. Install CGIC make install The CGIC installation path is libcgic.a Installed in /usr/local/lib cgic.h Installed in /usr/local/include After the CGIC library is installed, you can use CGIC programming 5. Transplantation of CGIC files Copy capture and cgictest.cgi to the /var/www/cgi-bin directory of the development board 6. Run the cgi program. Run it in the client browser. http://192.168.6.210/cgi-bin/cgictest.cgi.cgi[/url] If the webpage content is displayed normally, BOA and CGIC can work normally III. Solution to errors in CGIC transplantation process 1. The html webpage can run, but the CGI program reports an error Boa server reports an error: cgi_header: unable to find LFLF Client browser reports an error: 502 Bad Gateway The CGI was not CGI/1.1 compliant. Solution: Statically compile the CGI program arm-linux-gcc -o hello.cgi hello.c -static 4. CGIC Programming 1. CGI communication method When data is transmitted from the client browser to the Web server, the Web server will pass the received data to the QUERY_STRING or variable according to the transmission type (basically there are two types: GET/POST). The CGI program can receive the data received by the Web server in the program through standard input. When you want to send information to the browser, you only need to send specific file header information to the Web server, and then send the information to the Web server through standard output. After the Web server processes the information sent by the CGI program, it will send the information to the browser. 2. Receive data The data received by GET is stored in the QUERY_STRING variable of the Web server, while the data received by POST is stored in the Web server variable. The difference between the two data receiving methods is that the data received by GET has a length limit, while the data received by POST has no length limit; data sent by GET can be sent in the form of a URL, but data sent by POST must be sent through a Form. 3. CGI variables char *cgiServerSoftware Server software name, or an empty string char *cgiServerName Returns the server name or empty char *cgiGatewayInterface Gateway interface (usually CGI/1.1) or empty char *cgiServerProtocol Network protocol (usually HTTP/1.0) or empty char *cgiServerPort Server port (usually 80),or empty char *cgiRequestMethod request method (usually GET or POST) or empty char *cgiPathInfo indicates the additional virtual path char *cgiPathTranslated Indicates the additional virtual path and is converted to a local path by the server char *cgiscriptName The name of the calling program char *cgiQueryString Contains a GET-method request orTags. No parsing is required unless usedTags are usually parsed automatically by the CGIC library. char *cgiRemoteHost Returns the name of the client's host from the browser char *cgiRemoteAddr Returns the client's IP address from the browser char *cgiAuthType Returns user authorization information char *cgiRemoteUser Identifies the user cgiAuthType. char *cgiRemoteIdent Returns the user's name (the user has passed the user firm agreement) char *cgiContentType Returns the MIME type char *cgiAccept Refer to cgiHeaderContentType() cgiUserAgent char *cgiUserAgent Obtained user browser information char *cgiReferrer Points to the URL that the user accessed. int cgiContentLength Bytes of form or query data are considered standard. FILE *cgiOut CGI output. The cgiHeader functions, like cgiHeaderContentType, are primarily used to output mime headers; used by fprintf() and fwrite(). cgiOut is usually equivalent to stdout. 4. Main functions of CIGC library CGIC program can be compiled with general ANSI C or C++ compiler. Unlike C program, the main function of source code written with CGIC is cgiMain() instead of the usual main. The CGIC function library will automatically connect cgiMain to the corresponding main. CGIC library main function description: cgiFormResultType cgiFormString( char *name, char *result, int max) Used to copy a string from the input domain. Copy the characters in the domain name max-1 bytes to the buffer result. If the domain does not exist, copy an empty string to the result buffer. In this function, all new lines are represented by newline characters. cgiFormResultType cgiFormStringNoNewlines( char *name, char *result, int max) Similar to the cgiFormString function, except that all CRs and LFs are removed. cgiFormResultType cgiFormStringSpaceNeeded( char *name,int *length) Returns the length of the string pointed to by name and places the length in length. cgiFormResultType cgiFormStringMultiple( char *name, char ***ptrToStringArray) If there are multiple input fields for the same name, or the string in the field can change dynamically, use this function. It places the values of all input fields named name in prtToStringArray. void cgiStringArrayFree(char **stringArray) Releases the memory allocated to stringArray. cgiFormResultType cgiFormInteger( char *name, int *result, int defaultV) Takes an integer from the input field and puts it into result. cgiFormResultType cgiFormIntegerBounded( char *name, int *result, int min, int max, int defaultV) If the integer in the input domain is within the bounds, take it out and put it into result. cgiFormResultType cgiFormDouble( char *name, double *result, double defaultV) Take a floating point number from the input domain and put it into result. cgiFormResultType cgiFormDoubleBounded( char *name, double *result, double min, double max, double defaultV) If the floating point number in the input field is within the bounds, take it out and put it into result. cgiFormResultType cgiFormSelectSingle( char *name, char **choicesText, int choicesTotal, int *result, int defaultV) Remove the check box (following the select statement), copy the name of the selection to choicesText, copy the number of selections to choicesTotal, and copy the current selection to result. cgiFormResultType cgiFormSelectMultiple( char *name, char **choicesText, int choicesTotal, int *result, int *invalid) Similar to cgiFormSelectSingle, only result pointing to an integer array represents the selected items. cgiFormResultType cgiFormCheckboxSingle( char *name) If the check box is selected, the function returns cgiFormSuccess, otherwise it returns cgiFormNotFound. cgiFormResultType cgiFormCheckboxMultiple( char *name, char **valuesText, int valuesTotal, int *result, int *invalid) Similar to cgiFormCheckboxSingle, but it handles the case where there are multiple checkboxes with the same name. name points to the name of the checkbox; valuesText points to an array containing the parameters for each checkbox; valuesTotal points to the total number of checkboxes; result is an integer array, with 1 representing each checked checkbox and 0 representing each unchecked checkbox. cgiFormResultType cgiFormRadio( char *name, char **valuesText, int valuesTotal, int *result,int defaultV) Similar to cgiFormCheckboxMultiple, except that there are radio buttons instead of checkboxes. void cgiHeaderLocation(char *redirectUrl) Redirects to the URL specified by redirectUrl. void cgiHeaderStatus(int status, char *statusMessage) Outputs status code status and message statusMessage. void cgiHeaderContentType(char *mimeType) Used to tell the browser what type of document is returned. Called before any output to the browser, otherwise an error will occur or the browser cannot recognize it. cgiEnvironmentResultType cgiWriteEnvironment(char *filename) This function writes the current CGI environment to the file filename for later use in debugging. cgiEnvironmentResultType cgiReadEnvironment(char *filename) This function reads the CGI environment from the file filename for debugging. 5. CGI result encoding CGIC result encoding reference: cgiFormSuccess Submission successful cgiFormTruncated Delete some bytes. cgiFormBadType Incorrect input information (not as required) cgiFormEmpty The submission information is empty. cgiFormNotFound The submission information was not found. cgiFormConstrained The number is within a certain range and is forced below or above the appropriate range. cgiFormNoSuchChoice The value submitted by a single choice is not accepted. Usually indicates a conflict between the form and the program. cgiEnvironmentIO An attempt to read or write a file from the CGI environment or a retrieval failed with an I/O error. cgiEnvironmentMemory An attempt to read or write a file from the CGI environment or a retrieval failed with an out-of-memory error. cgiEnvironmentSuccess An attempt to read from or write to the CGI environment or retrieved file succeeded. 6. CGI environment variables REQUEST_METHOD Request type, such as "GET" or "POST" CONTENT_TYPE The type of data sent CONTENT_LENGTH The length of data sent by the client to the standard input device, in bytes QUERY_STRING Query parameters, such as "id=10010&sn=liigo" SCRIPT_NAMECGI script program name PATH_INFOCGI script program additional path PATH_TRANSLATEDPATH_INFO Corresponding absolute path REMOTE_ADDR The host IP that sent this request REMOTE_HOST The host name sending this request REMOTE_USER The verified legal user name REMOTE_IDENTWEB The login user name of the server AUTH_TYPE The authentication type GATEWAY_INTERFACE The CGI version that the server complies with, such as: CGI/1.1 SERVER_NAME Server host name, domain name or IP SERVER_PORT Server port number SERVER_PROTOCOL Server protocol, such as: HTTP/1.1 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value21 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value21 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value21 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value21 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value21 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value21 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value21 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value21 DOCUMENT_ROOT Document root directory SERVER_SOFTWARE Description text of the server software HTTP_ACCEPT MIME types that the client can receive, separated by commas HTTP_USER_AGENT The web browser that sent this request HTTP_REFERER The document that called this script HTTP_COOKIE Gets the COOKIE key-value pair. Multiple items are separated by semicolons, such as: key1=value1;key2=value2