Network Component  Version 7.19.0
MDK Middleware for IPv4 and IPv6 Networking
Common Gateway Interface (CGI)

Functions reacting on CGI requests to the HTTP server. More...

Functions

void netCGI_ProcessQuery (const char *qstr)
 Process query string received by GET or POST request. [user-provided]. More...
 
void netCGI_ProcessData (uint8_t code, const char *data, uint32_t len)
 Process data received by POST request. [user-provided]. More...
 
uint32_t netCGI_Script (const char *env, char *buf, uint32_t buf_len, uint32_t *pcgi)
 Generate dynamic web data based on a CGI script. [user-provided]. More...
 
const char * netCGI_GetEnvVar (const char *env, char *ansi, uint32_t max_len)
 Process environment variables and convert to ANSI format. [thread-safe]. More...
 
const char * netCGI_Charset (void)
 Override default character encoding in HTML documents. [user-provided]. More...
 
const char * netCGI_ContentType (const char *file_ext)
 Add custom MIME type for unsupported file types. [user-provided]. More...
 
const char * netCGI_CustomHeader (void)
 Add custom HTTP response header. [user-provided]. More...
 
const char * netCGI_Redirect (const char *file_name)
 Redirect resource URL address to a new location. [user-provided]. More...
 
void netCGI_ProcessRequest (const char *method, const char *uri, const char *header, uint32_t header_len)
 Process HTTP request. [user-provided]. More...
 
void netCGI_ProcessCookie (const char *method, const char *uri, const char *cookie, uint32_t cookie_len)
 Process HTTP cookie. [user-provided]. More...
 
netStatus netCGI_SetCookie (const char *cookie)
 Set HTTP cookie to send to the client. [thread-safe]. More...
 
const char * netCGX_ContentType (void)
 Override default Content-Type for CGX script files. [user-provided]. More...
 

Description

Functions reacting on CGI requests to the HTTP server.

To process a query string that was received by a GET request, the function netCGI_ProcessQuery is used while serving a POST request is done with netCGI_ProcessData. The function netCGI_Script generates a HTML web page based on CGI scripting. Processing and conversion of environment variables is done using netCGI_GetEnvVar, while the preferred character set (language) of a browser can be retrieved with netCGI_Charset.

Function Documentation

◆ netCGI_Charset()

const char * netCGI_Charset ( void  )

Override default character encoding in HTML documents. [user-provided].

Returns
pointer to user defined character set type.

The function netCGI_Charset overrides the default character encoding in a web browser. If this function is implemented and returns a non-NULL pointer, the web server adds a character encoding HTTP header. The browser then uses this information to correctly decode the character set.

If this function is not existing (or returns NULL), then the 'charset' parameter is not generated in web server's response. The browser then uses the default character encoding. This might cause troubles in displaying web pages that are encoded in different character sets. Example: an English user might not see the umlaut characters on German web pages.

The netCGI_Charset function is in the HTTP_Server_CGI.c module. The prototype is defined in rl_net.h.

Note
This function is optional.

Code Example

const char *netCGI_Charset (void) {
return ("utf-8");
}

◆ netCGI_ContentType()

const char * netCGI_ContentType ( const char *  file_ext)

Add custom MIME type for unsupported file types. [user-provided].

Parameters
[in]file_extfilename extension, a null-terminated string.
Returns
MIME type information:
  • pointer to user defined Content-Type.
  • NULL for unknown type.

The function netCGI_ContentType allows you to add new MIME types for the Content-Type HTTP header in the response to the web service application requests. The function returns a pointer to the Content-Type HTTP header. You can use this function to add new file types to the Network Component library.

The argument file_ext specifies the file extension of a requested file, which is not supported in Network Component library.

The default content type for unsupported file types is:

Content-Type: application/octet-stream\r\n

This header is used if the file type is not supported in Web server and netCGI_ContentType function does not exist in the project or if it returns a NULL pointer.

The netCGI_ContentType function is in the HTTP_Server_CGI.c module. The prototype is defined in rl_net.h.

Note
This function is optional. If missing, or returning NULL, a default content type is used for unsupported file types.

Code Example

const char *netCGI_ContentType (const char *file_ext) {
// Example
if (strcmp (file_ext, "wav") == 0) {
return ("audio/wav");
}
return (NULL);
}

◆ netCGI_CustomHeader()

const char * netCGI_CustomHeader ( void  )

Add custom HTTP response header. [user-provided].

Returns
pointer to user defined HTTP header.

The function netCGI_CustomHeader allows you to add custom HTTP headers to web server response. If this function is implemented and returns a non-NULL pointer, the web server adds custom HTTP headers. The function returns a pointer to one or more custom HTTP headers. Each header must be terminated with the "\r\n".

With this function you can implement HTTP security headers to prevent web server vulnerabilities.

Note
This function is optional. If missing, or returning NULL, no custom HTTP header is added.

Code Example

const char *netCGI_CustomHeader (void) {
return ("Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n");
}

◆ netCGI_GetEnvVar()

const char * netCGI_GetEnvVar ( const char *  env,
char *  ansi,
uint32_t  max_len 
)

Process environment variables and convert to ANSI format. [thread-safe].

Parameters
[in]envpointer to environment variables.
[out]ansioutput buffer to write converted variable to.
[in]max_lenmaximum length of environment variable.
Returns
status information:
  • pointer to the remaining environment variables to process.
  • NULL if there are no more environment variables to process.

The function netCGI_GetEnvVar processes the string env, which contains the environment variables, and identifies where the first variable ends. The function obtains and stores the first variable and its value in the buffer pointed by ansi, in ANSI format.

The argument max_len specifies the maximum length that can be stored in the ansi buffer. If the decoded environment variable value is longer than this limit, then the function truncates it to max_len to fit it into the buffer.

Note
  • The function can process environment variables from the GET and POST methods.
  • You can call this function from the HTTP_Server_CGI.c module.
  • The web browser uses environment variables to return user-entered information that is requested in the HTTP input form.

Code Example (see netCGI_ProcessQuery)

◆ netCGI_ProcessCookie()

void netCGI_ProcessCookie ( const char *  method,
const char *  uri,
const char *  cookie,
uint32_t  cookie_len 
)

Process HTTP cookie. [user-provided].

Parameters
[in]methodrequested http method, a null-terminated string.
[in]uriresource identifier, a null-terminated string.
[in]cookiehttp request cookie.
[in]cookie_lenlength of http request cookie.
Returns
none.

The function netCGI_ProcessCookie allows you to access HTTP cookies received in an HTTP request. The function is called when received an HTTP request and before opening the resource file. You can use this function to process session cookies provided by a the WEB browser.

The argument method specifies the HTTP request method used in the request, such as: GET, POST, HEADER, and so on. The method is a pointer to the null-terminated string.

The argument uri specifies the HTTP request path, which is a pointer to a null-terminated string. Arguments are not included. The path is pre-processed and all percent encoded characters are already decoded before the function is called.

The argument cookie is a pointer to HTTP cookie header contained in the request. The cookie header may contain more than one cookie. Cookies are separated by a semicolon.

The argument cookie_len specifies the length of the HTTP cookie header.

Note
This function is optional.

Code Example

void netCGI_ProcessCookie (const char *method, const char *uri, const char *cookie, uint32_t cookie_len) {
if (strcmp(cookie, "sessionid=x4aPh6w35t") == 0) {
// Cookie name: sessionid
// Cookie value: x4aPh6w35t
cookie_valid = 1;
}
if (strcmp(uri, "network.cgi") == 0) {
// Name of resource requested
}
..
}

◆ netCGI_ProcessData()

void netCGI_ProcessData ( uint8_t  code,
const char *  data,
uint32_t  len 
)

Process data received by POST request. [user-provided].

Parameters
[in]codecallback context:
  • 0 = www-url-encoded form data.
  • 1 = filename for file upload (null-terminated string).
  • 2 = file upload raw data.
  • 3 = end of file upload (file close requested).
  • 4 = any other type of POST data (single or last stream).
  • 5 = the same as 4, but with more data to follow.
[in]datapointer to POST data.
[in]lenlength of POST data.
Returns
none.

The function netCGI_ProcessData processes the data returned from the POST method of the CGI form. The HTTP server calls this function when a user clicks the SUBMIT button of an input form.

The argument code can have the following types:

Code Data Type Meaning of *data Meaning of len
0 Form data Pointer to data string returned from the POST method Length of data string
1 Filename Pointer to a Filename for the HTTP file upload. Filename is a null-terminated string. Length of a filename
2 File data Pointer to data packet received from the host Length of data packet
3 End of file NULL Don't care
4 Other data Pointer to data string returned from the POST method. A single packet or last packet in data stream Length of data string
5 Other data Pointer to data string returned from the POST method. The same as under 4, but with more data to follow Length of data string

The argument data point to the data that get processed.

The argument len is the data length in bytes.

Note
  • The HTTP server calls the function only if the input form (HTML source) is created with the attribute METHOD=POST. For example:
    <FORM ACTION=index.htm METHOD=POST NAME=CGI>
    ..
    </FORM>
  • Web browsers provide a filename for HTTP file upload with a path included. It is the user's responsibility to remove the path information from the filename.
  • For large files, file data is received in several small packets. The size of data packet depends on the TCP Maximum Segment Size (MSS). This value is typically 1440 bytes.
  • The XML-POST is generated from the web service application.

Code Example

The following example is available in the user code template file HTTP_Server_CGI.c. Customize it to the application's needs.

void netCGI_ProcessData (uint8_t code, const char *data, uint32_t len) {
char var[40];
switch (code) {
case 0:
// Url encoded form data received
do {
// Parse all parameters
data = netCGI_GetEnvVar (data, var, sizeof (var));
if (var[0] != 0) {
// First character is non-null, string exists
if (strcmp (var, "led0=on") == 0) {
// ... Switch LED 0 on
}
}
} while (data);
break;
case 1:
// Filename for file upload received
if (data[0] != 0) {
// Open a file for writing
file = fopen (var, "w");
}
break;
case 2:
// File content data received
if (file != NULL) {
// Write data to a file
fwrite (data, 1, len, file);
}
break;
case 3:
// File upload finished
if (file != NULL) {
// Close a file
fclose (file);
}
break;
case 4:
// Other content type data, last packet
if (strcmp (netHTTPs_GetContentType(), "text/xml; charset=utf-8") == 0) {
// Content type xml, utf-8 encoding
...
}
break;
case 5:
// Other content type data, more to follow
// ... Process data
break;
default:
// Ignore all other codes
break;
}
}

◆ netCGI_ProcessQuery()

void netCGI_ProcessQuery ( const char *  qstr)

Process query string received by GET or POST request. [user-provided].

Parameters
[in]qstrpointer to the query string.
Returns
none.

The function netCGI_ProcessQuery processes the environment variable QUERY_STRING returned by the method GET or by the method POST of the CGI form. The HTTP server calls this function when a user clicks the SUBMIT button on the input form. The function is not called if no URL query string arguments are specified.

The argument qstr points to the QUERY_STRING that is encoded in the URL of the request. The query string is terminated by a space character.

Note
  • The function is called by the HTTP server if the input form (HTML source) is created with the METHOD=GET attribute. For example:
    <FORM ACTION=index.htm METHOD=GET NAME=CGI>
    ..
    </FORM>
  • The function is also called if the input form is created with the METHOD=POST attribute and a query string argument is specified in the form's ACTION. For example:
    <FORM ACTION=service.htm?cmd=frw METHOD=POST NAME=CGI>
    ..
    </FORM>

Code Example

The following example is available in the user code template file HTTP_Server_CGI.c. Customize it to the application's needs.

void netCGI_ProcessQuery (const char *qstr) {
char var[40];
do {
// Loop through all the parameters
qstr = netCGI_GetEnvVar (qstr, var, sizeof (var));
// Check return string, 'qstr' now points to the next parameter
if (var[0] != 0) {
// First character is non-null, string exists
// Example of a parameter "ip=fe80::1c30:6cff:fea2:455e"
if (strncmp (var, "ip=", 3) == 0) {
uint8_t ip_addr[NET_ADDR_IP6_LEN];
// Read parameter IP address submitted by the browser
netIP_aton (&var[3], NET_ADDR_IP6, ip_addr);
...
}
}
} while (qstr);
}

◆ netCGI_ProcessRequest()

void netCGI_ProcessRequest ( const char *  method,
const char *  uri,
const char *  header,
uint32_t  header_len 
)

Process HTTP request. [user-provided].

Parameters
[in]methodrequested http method, a null-terminated string.
[in]uriresource identifier, a null-terminated string.
[in]headerhttp request header.
[in]header_lenlength of http request header.
Returns
none.

The function netCGI_ProcessRequest allows you to access HTTP request parameters. The function is called when an HTTP request is received and before the resource file is opened. You can use this function to extend the existing functionality of the HTTP server with additional options.

The argument method specifies the HTTP request method used in the request, such as: GET, POST, HEADER, and so on. The method is a pointer to the null-terminated string.

The argument uri specifies the HTTP request path, which is a pointer to a null-terminated string. Arguments are not included. The path is pre-processed and all percent encoded characters are already decoded before the function is called.

The argument header is a pointer to HTTP headers contained in the request.

The argument header_len specifies the length of the HTTP request headers.

Note
This function is optional.

Code Example

void netCGI_ProcessRequest (const char *method, const char *uri, const char *header, uint32_t header_len) {
if (strcmp(method, "GET") == 0) {
// GET method is used
}
if (strcmp(uri, "network.cgi") == 0) {
// Name of resource requested
}
// Further process HTTP headers, terminated with "\r\n"
}

◆ netCGI_Redirect()

const char * netCGI_Redirect ( const char *  file_name)

Redirect resource URL address to a new location. [user-provided].

Parameters
[in]file_nameresource filename, a null-terminated string.
Returns
URL redirection information:
  • pointer to user defined Location.
  • NULL for no URL address redirection.

The function netCGI_Redirect allows you to redirect URL address of a missing resource to a new location. The function returns a pointer to the Location HTML header. Web server calls this function, if the requested resource is not found on the server.

When netCGI_Redirect function returns valid URL location, Web server returns 301 Moved Permanently error code with HTML header containing a new location in the response to the web service application request.

The argument file_name specifies the full path name of a requested resource.

The netCGI_ContentType function is in the HTTP_Server_CGI.c module. The prototype is defined in rl_net.h.

Note
This function is optional. If missing, or returning NULL, server returns 404 Not Found to the client on file not found error.

Code Example

const char *netCGI_Redirect (const char *file_name) {
if (strcmp (file_name, "lxi/identification") == 0) {
return ("/lxi_identification.cgx");
}
return (NULL);
}

◆ netCGI_Script()

uint32_t netCGI_Script ( const char *  env,
char *  buf,
uint32_t  buf_len,
uint32_t *  pcgi 
)

Generate dynamic web data based on a CGI script. [user-provided].

Parameters
[in]envenvironment string.
[out]bufoutput data buffer.
[in]buf_lensize of output buffer (from 536 to 1440 bytes).
[in,out]pcgipointer to a session's local buffer of 4 bytes.
  • 1st call = cleared to 0.
  • 2nd call = not altered by the system.
  • 3rd call = not altered by the system, etc.
Returns
number of bytes written to output buffer.
  • return len | (1U<<31) = repeat flag, the system calls this function again for the same script line.
  • return len | (1U<<30) = force transmit flag, the system transmits current packet immediately.

The function netCGI_Script is what the script interpreter calls when interpreting the script to output the dynamic part of the HTTP response. The script interpreter calls netCGI_Script for each line in the script that begins with the command c. You must customize the netCGI_Script function so that it can understand and use the input string from the script.

The argument env is a pointer to the input string to create the dynamic response. It is the same string of bytes that is specified in the CGI script code using the c command.

The argument buf is a pointer to the output buffer where the netCGI_Script function must write the HTTP response.

The argument buf_len specifies the length of the output buffer in bytes.

The argument pcgi is a pointer to a variable that never gets altered by the HTTP Server. Hence, you can use it to store parameters for successive calls of the netCGI_Script function. You might use this to store:

  • loop counters
  • number of sent bytes
  • pointer to a local status buffer.
Note
  • The contents written into the output buffer by the netCGI_Script function must be HTML code.
  • c is a command that is available in the scripting language of the Network Component.
  • The length of the output buffer (buf_len) might vary, because the length is determined by the TCP socket Maximum Segment Size (MSS) negotiation. The buffer length is normally around 1400 bytes for local LAN. But this can be reduced to 500 bytes or less. It also varies because the HTTP Server tries to optimize the number of generated TCP packets. It calls this function again to use the complete available buffer. It stops when there are only 240 or less bytes free in the buffer. This causes the packet to be generated and transmitted. If you want to force the HTTP Server to transmit the packet, you need to or the return value from this function with 1U<<30.
  • If netCGI_Script writes more bytes than buf_len into the output buffer, a system crash from a corruption of the memory link pointers is highly likely.
  • The input string env might contain single-character subcommands to tell the netCGI_Script function how to process the script line correctly. There are no rules for these subcommands, so you can create and use your own commands.
  • The argument pcgi is private to each HTTP Session. The HTTP Server clears the data in the pcgi pointer to 0, before netCGI_Script is called for the first time in each session.
  • netCGI_Script must update the contents in pcgi for each call. You can use the 4 bytes in pcgi to store data in any format.

Code Example

The following example is available in the user code template file HTTP_Server_CGI.c. Customize it to the application's needs.

uint32_t netCGI_Script (const char *env, char *buf, uint32_t buf_len, uint32_t *pcgi) {
uint32_t len = 0;
// Analyze a 'c' script line starting position 2
// c a i <td><input type=text name=ip value="%s" size=40 maxlength=40></td>
char ip_ascii[40];
switch (env[0]) {
case 'a' :
switch (env[2]) {
case 'i':
// Write the local IP address
netIP_ntoa (NET_ADDR_IP6, IpAddr, ip_ascii, sizeof(ip_ascii));
len = sprintf (buf, &env[4], ip_ascii);
break;
..
}
break;
}
return (len);
}

◆ netCGI_SetCookie()

netStatus netCGI_SetCookie ( const char *  cookie)

Set HTTP cookie to send to the client. [thread-safe].

Parameters
[in]cookiecookie definition, a null-terminated string.
Returns
status code that indicates the execution status of the function.

The function netCGI_SetCookie sets the cookie that shall be returned to the client. The cookie is composed of the cookie_name and cookie_value.

The argument cookie is a pointer to a cookie that needs to be set, which is a null-terminated string. The function copies the contents of the cookie to the internal memory. If more than one cookie needs to be set, you can call the function several times to set all the required cookies.

You enable the processing of cookies by specifying the netCGI_ProcessCookie function in the code. If the function is not available, cookies are automatically disabled on the web server.

Possible netStatus return values:

  • netOK: Cookie successfully set.
  • netInvalidParameter: Invalid cookie provided.
  • netError: Cookies not enabled or no memory available for the cookie.
  • netWrongState: Function called from an invalid context, not from a CGI callback function.
Note
When the function ends, the content of cookie becomes irrelevant and may be discarded.

Code Example

void netCGI_ProcessData (uint8_t code, const char *data, uint32_t len) {
if (cookie_valid == 0)
// The cookie not received from the browser, set it
netCGI_SetCookie ("sessionid=x4aPh6w35t");
}
..
}

◆ netCGX_ContentType()

const char * netCGX_ContentType ( void  )

Override default Content-Type for CGX script files. [user-provided].

Returns
pointer to user defined Content-Type.

The function netCGX_ContentType allows you to change the Content-Type HTML header in the response to the web service application requests. The function returns a pointer to the new Content-Type HTML header. You can use this function to override the default content type header from the Network Component library. This content type header is used in cgx script responses.

The default content type header in cgx script response is:

Content-Type: text/xml\r\n

This header is used if the netCGX_ContentType function does not exist in the project or if it returns a NULL pointer.

The netCGX_ContentType function is in the HTTP_Server_CGI.c module. The prototype is defined in rl_net.h.

Note
This function is optional. If missing, or returning NULL, a default "text/xml" content type is used.

Code Example

const char *netCGX_ContentType (void) {
return ("text/xml; charset=utf-8");
}